Documentation Index
Fetch the complete documentation index at: https://docs.apiyi.com/llms.txt
Use this file to discover all available pages before exploring further.
概念定义
批处理是将多个LLM请求打包异步处理的技术,通过牺牲实时性换取更高的吞吐量和更低的成本。
详细解释
批处理彻底改变了大规模LLM应用的经济模型。与实时API调用相比,批处理通过集中调度和优化资源利用,实现了50%的成本降低和数倍的吞吐量提升。
2025年批处理的关键特性:
- 异步执行:24小时内完成,不保证即时响应
- 成本优惠:所有主流提供商均提供50%折扣
- 规模化:单批次支持数万请求,千万级token
- 可追踪:每个请求独立ID,便于结果匹配
适用场景对比:
- 批处理适合:文档分析、数据标注、内容生成、定期报告
- 实时处理适合:聊天机器人、实时翻译、紧急决策、用户交互
工作原理
请求格式(JSONL)
{"custom_id": "req-001", "method": "POST", "url": "/v1/chat/completions", "body": {"model": "gpt-4-turbo", "messages": [{"role": "user", "content": "分析这份财报..."}]}}
{"custom_id": "req-002", "method": "POST", "url": "/v1/chat/completions", "body": {"model": "gpt-4-turbo", "messages": [{"role": "user", "content": "总结这篇文章..."}]}}
{"custom_id": "req-003", "method": "POST", "url": "/v1/chat/completions", "body": {"model": "gpt-4-turbo", "messages": [{"role": "user", "content": "提取关键信息..."}]}}
提交与追踪
import asyncio
from openai import OpenAI
client = OpenAI()
# 1. 上传批处理文件
batch_file = client.files.create(
file=open("batch_requests.jsonl", "rb"),
purpose="batch"
)
# 2. 创建批处理任务
batch_job = client.batches.create(
input_file_id=batch_file.id,
endpoint="/v1/chat/completions",
completion_window="24h"
)
# 3. 监控进度
while batch_job.status not in ["completed", "failed"]:
batch_job = client.batches.retrieve(batch_job.id)
print(f"进度: {batch_job.request_counts.completed}/{batch_job.request_counts.total}")
await asyncio.sleep(60)
# 4. 获取结果
if batch_job.status == "completed":
results = client.files.content(batch_job.output_file_id)
队列管理系统
QLM架构(2025标准)
class QueueManager:
def __init__(self):
self.queues = {
"high_priority": PriorityQueue(),
"standard": Queue(),
"batch": BatchQueue()
}
def route_request(self, request):
if request.deadline < 1_minute:
return self.queues["high_priority"]
elif request.deadline < 1_hour:
return self.queues["standard"]
else:
return self.queues["batch"]
def optimize_batch(self, requests):
# 智能分组优化
return group_by_similarity(requests)
性能指标:
- 吞吐量:200 → 1,500 tokens/秒(7.5倍提升)
- 延迟:2.5秒 → 0.8秒(68%降低)
- GPU利用率:60% → 95%(58%提升)
批量大小优化
最佳实践矩阵
| 任务类型 | 最优批量 | GPU利用率 | 延迟影响 |
|---|
| 简单分类 | 5,000-10,000 | 95% | 最小 |
| 文本生成 | 1,000-3,000 | 90% | 中等 |
| 复杂推理 | 100-500 | 85% | 较大 |
| 多模态处理 | 50-200 | 80% | 显著 |
动态调整策略
def adaptive_batch_size(queue_depth, gpu_memory, avg_token_length):
base_size = 1000
# 根据队列深度调整
if queue_depth > 10000:
base_size *= 2
elif queue_depth < 1000:
base_size //= 2
# 根据GPU内存调整
memory_factor = min(gpu_memory / 40_000, 2.0) # 40GB基准
# 根据平均长度调整
length_factor = 1000 / avg_token_length
return int(base_size * memory_factor * length_factor)
成本优化策略
1. 智能调度
class CostOptimizer:
def schedule_jobs(self, jobs):
# 按紧急程度分类
urgent = [j for j in jobs if j.deadline < 1_hour]
normal = [j for j in jobs if 1_hour <= j.deadline < 6_hours]
batch = [j for j in jobs if j.deadline >= 6_hours]
# 批量任务享受50%折扣
batch_cost = sum(j.estimated_cost for j in batch) * 0.5
normal_cost = sum(j.estimated_cost for j in normal) * 0.8
urgent_cost = sum(j.estimated_cost for j in urgent)
return urgent + normal + batch, batch_cost + normal_cost + urgent_cost
2. 模型选择
- 轻量任务用小模型:GPT-4o-mini批处理
- 复杂任务用大模型:Claude 3.5 Sonnet批处理
- 混合策略:路由不同任务到最优模型
3. 压缩技术
- Token压缩:减少20-30%输入长度
- 响应截断:限制最大生成长度
- 重复内容缓存:相似请求复用结果
监控与可观测性
关键指标
metrics = {
"throughput": "tokens/second",
"latency_p50": "seconds",
"latency_p99": "seconds",
"gpu_utilization": "percentage",
"queue_depth": "count",
"error_rate": "percentage",
"cost_per_token": "dollars"
}
2025监控工具
- LangSmith:端到端追踪和调试
- OpenLLMetry:标准化可观测性
- Coralogix AI:智能告警和根因分析
- 自定义仪表板:Grafana + Prometheus
实际应用案例
1. 文档处理系统
# 法律文档批量分析
tasks = [
{"doc_id": doc.id, "task": "extract_entities"},
{"doc_id": doc.id, "task": "summarize"},
{"doc_id": doc.id, "task": "classify_risk"}
]
# 处理速度:1,200 → 5,000 文件/小时
2. 内容生成平台
# 批量生成产品描述
products = load_product_catalog()
batch_generate_descriptions(products,
batch_size=1000,
model="gpt-4-turbo",
temperature=0.7
)
# 成本降低:73%
3. 数据标注服务
# 大规模数据集标注
dataset = load_unlabeled_data()
batch_annotate(dataset,
batch_size=5000,
annotation_schema=schema,
quality_threshold=0.95
)
# GPU利用率:60% → 95%
最佳实践
-
请求打包
- 相似任务分组处理
- 统一prompt模板减少变化
- 合理设置批次大小
-
错误处理
- 实现请求级重试
- 失败隔离,不影响整批
- 详细错误日志记录
-
结果处理
相关概念
延伸阅读