批次處理是一種強大的方法,可以有效地處理大量請求。與其逐個處理請求並立即獲得回應,批次處理允許您將多個請求一起提交以進行非同步處理。此模式特別適用於以下情況:
Message Batches API 是 Anthropic 對此模式的首次實現。
This feature is not eligible for Zero Data Retention (ZDR). Data is retained according to the feature's standard retention policy.
Message Batches API 是一種強大且具有成本效益的方式,可以非同步處理大量 Messages 請求。此方法非常適合不需要立即回應的任務,大多數批次在不到 1 小時內完成,同時將成本降低 50% 並提高吞吐量。
您可以 直接探索 API 參考,以及閱讀本指南。
當您向 Message Batches API 發送請求時:
Was this page helpful?
這對於不需要立即結果的批量操作特別有用,例如:
所有 活躍模型 都支持 Message Batches API。
任何您可以向 Messages API 發出的請求都可以包含在批次中。這包括:
由於批次中的每個請求都是獨立處理的,您可以在單個批次中混合不同類型的請求。
由於批次可能需要超過 5 分鐘才能處理,請考慮在使用提示詞快取處理具有共享上下文的批次時,使用 1 小時快取持續時間 以獲得更好的快取命中率。
Batches API 提供顯著的成本節省。所有使用費用按標準 API 價格的 50% 計費。
| Model | Batch input | Batch output |
|---|---|---|
| Claude Opus 4.6 | $2.50 / MTok | $12.50 / MTok |
| Claude Opus 4.5 | $2.50 / MTok | $12.50 / MTok |
| Claude Opus 4.1 | $7.50 / MTok | $37.50 / MTok |
| Claude Opus 4 | $7.50 / MTok | $37.50 / MTok |
| Claude Sonnet 4.6 | $1.50 / MTok | $7.50 / MTok |
| Claude Sonnet 4.5 | $1.50 / MTok | $7.50 / MTok |
| Claude Sonnet 4 | $1.50 / MTok | $7.50 / MTok |
| Claude Sonnet 3.7 (deprecated) | $1.50 / MTok | $7.50 / MTok |
| Claude Haiku 4.5 | $0.50 / MTok | $2.50 / MTok |
| Claude Haiku 3.5 | $0.40 / MTok | $2 / MTok |
| Claude Opus 3 (deprecated) | $7.50 / MTok | $37.50 / MTok |
| Claude Haiku 3 | $0.125 / MTok | $0.625 / MTok |
Message Batch 由創建 Message 的請求列表組成。單個請求的形狀包括:
custom_idparams 對象您可以通過將此列表傳遞到 requests 參數來 創建批次:
curl https://api.anthropic.com/v1/messages/batches \
--header "x-api-key: $ANTHROPIC_API_KEY" \
--header "anthropic-version: 2023-06-01" \
--header "content-type: application/json" \
--data \
'{
"requests": [
{
"custom_id": "my-first-request",
"params": {
"model": "claude-opus-4-6",
"max_tokens": 1024,
"messages": [
{"role": "user", "content": "Hello, world"}
]
}
},
{
"custom_id": "my-second-request",
"params": {
"model": "claude-opus-4-6",
"max_tokens": 1024,
"messages": [
{"role": "user", "content": "Hi again, friend"}
]
}
}
]
}'在此示例中,兩個單獨的請求被批處理在一起以進行非同步處理。每個請求都有一個唯一的 custom_id 並包含您用於 Messages API 調用的標準參數。
使用 Messages API 測試您的批次請求
對每個消息請求的 params 對象的驗證是非同步執行的,驗證錯誤在整個批次處理結束時返回。您可以通過首先使用 Messages API 驗證您的請求形狀來確保您正確構建輸入。
首次創建批次時,響應將具有 in_progress 的處理狀態。
{
"id": "msgbatch_01HkcTjaV5uDC8jWR4ZsDV8d",
"type": "message_batch",
"processing_status": "in_progress",
"request_counts": {
"processing": 2,
"succeeded": 0,
"errored": 0,
"canceled": 0,
"expired": 0
},
"ended_at": null,
"created_at": "2024-09-24T18:37:24.100435Z",
"expires_at": "2024-09-25T18:37:24.100435Z",
"cancel_initiated_at": null,
"results_url": null
}Message Batch 的 processing_status 字段指示批次處理所處的階段。它首先為 in_progress,然後在批次中的所有請求完成處理且結果準備好後更新為 ended。您可以通過訪問 Console 或使用 檢索端點 來監控批次的狀態。
要輪詢 Message Batch,您需要其 id,該 ID 在創建批次時的響應中提供,或通過列出批次獲得。您可以實現一個輪詢循環,定期檢查批次狀態,直到處理結束:
#!/bin/sh
until [[ $(curl -s "https://api.anthropic.com/v1/messages/batches/$MESSAGE_BATCH_ID" \
--header "x-api-key: $ANTHROPIC_API_KEY" \
--header "anthropic-version: 2023-06-01" \
| grep -o '"processing_status":[[:space:]]*"[^"]*"' \
| cut -d'"' -f4) == "ended" ]]; do
echo "Batch $MESSAGE_BATCH_ID is still processing..."
sleep 60
done
echo "Batch $MESSAGE_BATCH_ID has finished processing"您可以使用 列表端點 列出 Workspace 中的所有 Message Batches。該 API 支持分頁,根據需要自動獲取其他頁面:
#!/bin/sh
if ! command -v jq &> /dev/null; then
echo "Error: This script requires jq. Please install it first."
exit 1
fi
BASE_URL="https://api.anthropic.com/v1/messages/batches"
has_more=true
after_id=""
while [ "$has_more" = true ]; do
# Construct URL with after_id if it exists
if [ -n "$after_id" ]; then
url="${BASE_URL}?limit=20&after_id=${after_id}"
else
url="$BASE_URL?limit=20"
fi
response=$(curl -s "$url" \
--header "x-api-key: $ANTHROPIC_API_KEY" \
--header "anthropic-version: 2023-06-01")
# Extract values using jq
has_more=$(echo "$response" | jq -r '.has_more')
after_id=$(echo "$response" | jq -r '.last_id')
# Process and print each entry in the data array
echo "$response" | jq -c '.data[]' | while read -r entry; do
echo "$entry" | jq '.'
done
done批次處理結束後,批次中的每個 Messages 請求都有一個結果。有 4 種結果類型:
| 結果類型 | 描述 |
|---|---|
succeeded | 請求成功。包括訊息結果。 |
errored | 請求遇到錯誤,未建立訊息。可能的錯誤包括無效請求和內部伺服器錯誤。您不會因這些請求而被計費。 |
canceled | 使用者在此請求發送到模型之前取消了批次。您不會因這些請求而被計費。 |
expired | 批次在此請求發送到模型之前達到 24 小時過期時間。您不會因這些請求而被計費。 |
您將看到批次結果的概覽,其中包含批次的 request_counts,顯示有多少請求達到這四種狀態中的每一種。
批次的結果可在 Message Batch 上的 results_url 屬性下載,如果組織權限允許,也可在 Console 中下載。由於結果的潛在大小,建議串流結果而不是一次性下載所有結果。
#!/bin/sh
curl "https://api.anthropic.com/v1/messages/batches/msgbatch_01HkcTjaV5uDC8jWR4ZsDV8d" \
--header "anthropic-version: 2023-06-01" \
--header "x-api-key: $ANTHROPIC_API_KEY" \
| grep -o '"results_url":[[:space:]]*"[^"]*"' \
| cut -d'"' -f4 \
| while read -r url; do
curl -s "$url" \
--header "anthropic-version: 2023-06-01" \
--header "x-api-key: $ANTHROPIC_API_KEY" \
| sed 's/}{/}\n{/g' \
| while IFS= read -r line
do
result_type=$(echo "$line" | sed -n 's/.*"result":[[:space:]]*{[[:space:]]*"type":[[:space:]]*"\([^"]*\)".*/\1/p')
custom_id=$(echo "$line" | sed -n 's/.*"custom_id":[[:space:]]*"\([^"]*\)".*/\1/p')
error_type=$(echo "$line" | sed -n 's/.*"error":[[:space:]]*{[[:space:]]*"type":[[:space:]]*"\([^"]*\)".*/\1/p')
case "$result_type" in
"succeeded")
echo "Success! $custom_id"
;;
"errored")
if [ "$error_type" = "invalid_request_error" ]; then
# Request body must be fixed before re-sending request
echo "Validation error: $custom_id"
else
# Request can be retried directly
echo "Server error: $custom_id"
fi
;;
"expired")
echo "Expired: $line"
;;
esac
done
done
結果採用 .jsonl 格式,其中每一行都是一個有效的 JSON 物件,代表 Message Batch 中單個請求的結果。對於每個串流結果,您可以根據其 custom_id 和結果類型執行不同的操作。以下是一組結果範例:
{"custom_id":"my-second-request","result":{"type":"succeeded","message":{"id":"msg_014VwiXbi91y3JMjcpyGBHX5","type":"message","role":"assistant","model":"claude-opus-4-6","content":[{"type":"text","text":"Hello again! It's nice to see you. How can I assist you today? Is there anything specific you'd like to chat about or any questions you have?"}],"stop_reason":"end_turn","stop_sequence":null,"usage":{"input_tokens":11,"output_tokens":36}}}}
{"custom_id":"my-first-request","result":{"type":"succeeded","message":{"id":"msg_01FqfsLoHwgeFbguDgpz48m7","type":"message","role":"assistant","model":"claude-opus-4-6","content":[{"type":"text","text":"Hello! How can I assist you today? Feel free to ask me any questions or let me know if there's anything you'd like to chat about."}],"stop_reason":"end_turn","stop_sequence":null,"usage":{"input_tokens":10,"output_tokens":34}}}}如果您的結果有錯誤,其 result.error 將設定為標準錯誤形狀。
批次結果可能不符合輸入順序
批次結果可以按任何順序返回,可能不符合建立批次時請求的順序。在上面的範例中,第二個批次請求的結果在第一個之前返回。要正確將結果與其對應的請求相匹配,請始終使用 custom_id 欄位。
您可以使用取消端點取消目前正在處理的 Message Batch。取消後立即,批次的 processing_status 將為 canceling。您可以使用上述相同的輪詢技術等待取消完成。已取消的批次最終狀態為 ended,可能包含取消前已處理的請求的部分結果。
#!/bin/sh
curl --request POST https://api.anthropic.com/v1/messages/batches/$MESSAGE_BATCH_ID/cancel \
--header "x-api-key: $ANTHROPIC_API_KEY" \
--header "anthropic-version: 2023-06-01"回應將顯示批次處於 canceling 狀態:
{
"id": "msgbatch_013Zva2CMHLNnXjNJJKqJ2EF",
"type": "message_batch",
"processing_status": "canceling",
"request_counts": {
"processing": 2,
"succeeded": 0,
"errored": 0,
"canceled": 0,
"expired": 0
},
"ended_at": null,
"created_at": "2024-09-24T18:37:24.100435Z",
"expires_at": "2024-09-25T18:37:24.100435Z",
"cancel_initiated_at": "2024-09-24T18:39:03.114875Z",
"results_url": null
}Message Batches API 支援提示詞快取,允許您可能降低批次請求的成本和處理時間。來自提示詞快取和 Message Batches 的定價折扣可以疊加,在同時使用兩項功能時提供更大的成本節省。但是,由於批次請求是非同步且並行處理的,快取命中是以盡力而為的基礎提供的。使用者通常根據其流量模式體驗 30% 到 98% 的快取命中率。
為了最大化批次請求中快取命中的可能性:
cache_control 區塊在批次中實現提示詞快取的範例:
curl https://api.anthropic.com/v1/messages/batches \
--header "x-api-key: $ANTHROPIC_API_KEY" \
--header "anthropic-version: 2023-06-01" \
--header "content-type: application/json" \
--data \
'{
"requests": [
{
"custom_id": "my-first-request",
"params": {
"model": "claude-opus-4-6",
"max_tokens": 1024,
"system": [
{
"type": "text",
"text": "You are an AI assistant tasked with analyzing literary works. Your goal is to provide insightful commentary on themes, characters, and writing style.\n"
},
{
"type": "text",
"text": "<the entire contents of Pride and Prejudice>",
"cache_control": {"type": "ephemeral"}
}
],
"messages": [
{"role": "user", "content": "Analyze the major themes in Pride and Prejudice."}
]
}
},
{
"custom_id": "my-second-request",
"params": {
"model": "claude-opus-4-6",
"max_tokens": 1024,
"system": [
{
"type": "text",
"text": "You are an AI assistant tasked with analyzing literary works. Your goal is to provide insightful commentary on themes, characters, and writing style.\n"
},
{
"type": "text",
"text": "<the entire contents of Pride and Prejudice>",
"cache_control": {"type": "ephemeral"}
}
],
"messages": [
{"role": "user", "content": "Write a summary of Pride and Prejudice."}
]
}
}
]
}'在此範例中,批次中的兩個請求都包含相同的系統訊息和標記有 cache_control 的完整傲慢與偏見文本,以增加快取命中的可能性。
output-300k-2026-03-24 測試版標頭將 max_tokens 上限提高到 300,000,用於使用 Claude Opus 4.6 或 Claude Sonnet 4.6 的批次請求。包含該標頭以在單次轉換中生成遠長於標準限制(根據模型為 64k 到 128k)的輸出。
擴展輸出僅在 Message Batches API 上可用,不在同步 Messages API 上可用。它在 Claude API 上受支援,在 Amazon Bedrock、Vertex AI 或 Microsoft Foundry 上不可用。
使用擴展輸出進行長篇幅生成,例如書籍長度的草稿和技術文件、詳盡的結構化資料提取、大型程式碼生成框架和長推理鏈。
單次 300k 令牌生成可能需要超過一小時才能完成,因此請根據 24 小時處理窗口計劃您的批次提交。標準批次定價(標準 API 價格的 50%)適用。
curl https://api.anthropic.com/v1/messages/batches \
--header "x-api-key: $ANTHROPIC_API_KEY" \
--header "anthropic-version: 2023-06-01" \
--header "anthropic-beta: output-300k-2026-03-24" \
--header "content-type: application/json" \
--data \
'{
"requests": [
{
"custom_id": "long-form-request",
"params": {
"model": "claude-opus-4-6",
"max_tokens": 300000,
"messages": [
{"role": "user", "content": "Write a comprehensive technical guide to building distributed systems, covering architecture patterns, consistency models, fault tolerance, and operational best practices."}
]
}
}
]
}'為了充分利用 Batches API:
custom_id 值來輕鬆匹配結果與請求,因為順序不保證。如果遇到意外行為:
request_too_large 錯誤。custom_id。created_at(不是處理 ended_at)時間以來已不超過 29 天。如果超過 29 天,結果將不再可查看。請注意,批次中一個請求的失敗不會影響其他請求的處理。
工作區隔離:批次在建立它們的工作區內隔離。它們只能由與該工作區相關聯的 API 金鑰或有權限在 Console 中查看工作區批次的使用者存取。
結果可用性:批次結果在批次建立後 29 天內可用,允許充足的時間進行檢索和處理。
批次處理在批次建立後最多 29 天內儲存請求和回應資料。您可以在處理後隨時使用 DELETE /v1/messages/batches/{batch_id} 端點刪除訊息批次。要刪除進行中的批次,請先取消它。非同步處理需要伺服器端儲存輸入和輸出,直到批次完成和結果檢索。
有關所有功能的 ZDR 資格,請參閱 API 和資料保留。