关于 batch-processing
为使用 Anthropic Messages API 的开发者提供批量处理指导,涵盖提交请求、追踪状态、处理结果及失败重试,适合非实时的大规模任务。
主要功能
- 01创建 JSONL 批量请求
- 02提交并轮询批次状态
- 03流式处理批次结果
- 04处理失败与过期请求
- 05为大批量任务降低成本
适用场景
- 01批量处理文档
- 02运行模型评估与基准测试
- 03执行 ETL 和数据增强
- 04生成训练数据
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ thelobbi/ claude --skill batch-processing安装后在 Claude Code 中输入/batch-processing确认已加载。
详细介绍
批处理技能
利用 Anthropic 的 Message Batches API,以 50% 的成本处理大批量工作负载。
何时使用此技能
- 处理 10K+ 份文档
- 模型评估与基准测试
- ETL 和数据丰富
- 训练数据生成
- 批量内容分析
- 任何对时效性要求不高的工作负载
成本节省
| 处理类型 | 成本 |
|---|---|
| 标准 API | 100% |
| Batch API | 50% |
示例: 1M 个 token @ $3/1M = $3(标准)对比 $1.50(批处理)
批处理生命周期
Created → Processing → Ended (completed/failed/expired/canceled)
- 处理时间: 最长 24 小时
- 结果保留时间: 29 天
- 全面支持功能: 工具、视觉、系统提示词
核心实现
第 1 步:创建 JSONL 文件
import json
# Each line is a complete request
requests = [
{
"custom_id": "request-1",
"params": {
"model": "claude-sonnet-5",
"max_tokens": 1024,
"messages": [{"role": "user", "content": "Summarize: Document 1..."}]
}
},
{
"custom_id": "request-2",
"params": {
"model": "claude-sonnet-5",
"max_tokens": 1024,
"messages": [{"role": "user", "content": "Summarize: Document 2..."}]
}
}
]
# Write JSONL file
with open("batch_requests.jsonl", "w") as f:
for request in requests:
f.write(json.dumps(request) + "\n")
第 2 步:提交批次
import anthropic
client = anthropic.Anthropic()
# Create batch from file
with open("batch_requests.jsonl", "rb") as f:
batch = client.beta.messages.batches.create(
requests=f
)
print(f"Batch ID: {batch.id}")
print(f"Status: {batch.processing_status}")
第 3 步:轮询直至完成
import time
def wait_for_batch(client, batch_id, poll_interval=60):
"""Poll until batch completes"""
while True:
batch = client.beta.messages.batches.retrieve(batch_id)
if batch.processing_status == "ended":
print(f"Batch completed!")
print(f" Succeeded: {batch.request_counts.succeeded}")
print(f" Errored: {batch.request_counts.errored}")
print(f" Expired: {batch.request_counts.expired}")
return batch
print(f"Status: {batch.processing_status} - waiting...")
time.sleep(poll_interval)
第 4 步:流式传输结果
def process_results(client, batch_id):
"""Stream and process batch results"""
results = {}
for result in client.beta.messages.batches.results(batch_id):
custom_id = result.custom_id
if result.result.type == "succeeded":
message = result.result.message
results[custom_id] = {
"status": "success",
"content": message.content[0].text,
"usage": message.usage
}
elif result.result.type == "errored":
results[custom_id] = {
"status": "error",
"error": result.result.error
}
elif result.result.type == "expired":
results[custom_id] = {
"status": "expired"
}
return results
完整工作流
import anthropic
import json
import time
def run_batch_job(documents):
"""Complete batch processing workflow"""
client = anthropic.Anthropic()
# 1. Create requests
requests = []
for i, doc in enumerate(documents):
requests.append({
"custom_id": f"doc-{i}",
"params": {
"model": "claude-sonnet-5",
"max_tokens": 1024,
"messages": [{"role": "user", "content": f"Summarize: {doc}"}]
}
})
# 2. Write JSONL
with open("batch.jsonl", "w") as f:
for req in requests:
f.write(json.dumps(req) + "\n")
# 3. Submit batch
with open("batch.jsonl", "rb") as f:
batch = client.beta.messages.batches.create(requests=f)
print(f"Batch submitted: {batch.id}")
# 4. Wait for completion
while True:
batch = client.beta.messages.batches.retrieve(batch.id)
if batch.processing_status == "ended":
break
time.sleep(60)
# 5. Collect results
results = {}
for result in client.beta.messages.batches.results(batch.id):
if result.result.type == "succeeded":
results[result.custom_id] = result.result.message.content[0].text
return results
错误处理
重试失败的请求
def retry_failed(client, original_batch_id):
"""Retry failed and expired requests"""
retry_requests = []
for result in client.beta.messages.batches.results(original_batch_id):
if result.result.type in ["errored", "expired"]:
# Re-create the request (you'll need to store original params)
retry_requests.append({
"custom_id": result.custom_id,
"params": get_original_params(result.custom_id) # Your implementation
})
if retry_requests:
# Write and submit retry batch
with open("retry.jsonl", "w") as f:
for req in retry_requests:
f.write(json.dumps(req) + "\n")
with open("retry.jsonl", "rb") as f:
return client.beta.messages.batches.create(requests=f)
return None
错误类型
| 结果类型 | 操作 |
|---|---|
succeeded | 正常处理 |
errored | 检查错误,必要时重试 |
expired | 请求耗时超过 24 小时,重试 |
canceled | 批次已取消 |
API 参考
端点
| 方法 | 端点 | 用途 |
|---|---|---|
| POST | /v1/messages/batches | 创建批次 |
| GET | /v1/messages/batches/{id} | 获取批次状态 |
| GET | /v1/messages/batches | 列出批次 |
| POST | /v1/messages/batches/{id}/cancel | 取消批次 |
| GET | /v1/messages/batches/{id}/results | 流式传输结果 |
请求格式
{
"custom_id": "unique-identifier",
"params": {
"model": "claude-sonnet-5",
"max_tokens": 1024,
"system": "Optional system prompt",
"messages": [{"role": "user", "content": "..."}],
"tools": []
}
}
最佳实践
应做事项:
- 用于请求数 >100 的工作负载
- 使用唯一的 custom_id 进行跟踪
- 保存原始参数,以便重试
- 通过轮询监控批次状态
- 以流式 JSONL 处理结果
不应做事项:
- 不要用于对时效性要求高的请求
- 不要期待立即获得结果
- 不要忘记处理过期请求
- 不要忽略错误结果
成本优化建议
- 批处理相似请求 - 使用相同模型和相似提示词
- 结合缓存 - 在批处理前缓存静态上下文
- 使用合适的模型 - 简单任务用 Haiku,复杂任务用 Sonnet
- 优化提示词 - 提示词越短,成本越低
使用场景:文档处理
# Process 10,000 documents at 50% cost
documents = load_documents("data/*.txt") # 10K files
# Create batch with consistent format
requests = [{
"custom_id": doc.id,
"params": {
"model": "claude-haiku-4-5", # Cheapest for bulk
"max_tokens": 512,
"system": "Extract key information as JSON.",
"messages": [{"role": "user", "content": doc.content}]
}
} for doc in documents]
# Run batch job
results = run_batch_job(requests)
# Cost: ~50% of standard API!
另请参阅
- llm-integration - API 基础知识
- prompt-caching - 缓存上下文
- streaming - 实时输出
评论
支持 Markdown