Was this page helpful?
批次處理是一種高效處理大量請求的強大方法。批次處理不是一次處理一個請求並立即回應,而是允許您將多個請求一起提交以進行非同步處理。這種模式在以下情況特別有用:
Message Batches API 是 Anthropic 對此模式的首次實作。
此功能不符合零資料保留(Zero Data Retention,ZDR)的資格。資料將依據該功能的標準保留政策進行保留。
Message Batches API 是一種強大且具成本效益的方式,可非同步處理大量 Messages 請求。這種方法非常適合不需要立即回應的任務,大多數批次在 1 小時內完成,同時降低 50% 的成本並提高吞吐量。
除了本指南外,您還可以直接探索 API 參考文件。
當您向 Message Batches API 發送請求時:
這對於不需要立即結果的大量操作特別有用,例如:
max_tokens 必須至少為 1。批次內不支援 max_tokens: 0(快取預熱),因為在批次處理期間寫入的臨時快取項目可能會在後續請求執行之前過期。所有現行模型都支援 Message Batches API。
幾乎任何您可以向 Messages API 發出的請求都可以包含在批次中。這包括:
由於批次中的每個請求都是獨立處理的,您可以在單一批次中混合不同類型的請求。
少數 Messages API 參數在批次請求中不受支援。包含以下任何參數都會傳回驗證錯誤:
| 參數 | 原因 |
|---|---|
stream: true | 批次結果以單一檔案形式傳回,而非串流。 |
speed(快速模式) | 快速模式調整同步延遲,這不適用於非同步批次處理。 |
store / previous_thread_event_id(Threads) | Threads 是有狀態的;批次請求則不是。 |
cache_hint / context_hint | 這些路由提示僅適用於同步請求排程。 |
max_tokens: 0 | 請參閱批次限制。 |
research_preview_2026_02: "active" | 研究預覽模式在批次路徑上不可用。 |
由於批次處理可能需要超過 5 分鐘,在處理具有共享上下文的批次時,請考慮搭配提示快取使用 1 小時快取持續時間,以獲得更好的快取命中率。
Batches API 提供顯著的成本節省。所有使用量均按標準 API 價格的 50% 收費。
| 模型 | 批次輸入 | 批次輸出 |
|---|---|---|
| Claude Fable 5 | $5 / MTok | $25 / MTok |
| Claude Mythos 5(限量供應) | $5 / MTok | $25 / MTok |
| Claude Opus 4.8 | $2.50 / MTok | $12.50 / MTok |
| Claude Opus 4.7 | $2.50 / MTok | $12.50 / MTok |
| 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(已停用,Vertex AI 除外) | $7.50 / MTok | $37.50 / MTok |
Message Batch 由建立 Message 的請求清單組成。單一請求的結構包含:
custom_id。必須為 1 到 64 個字元,且只能包含英數字元、連字號和底線(符合 ^[a-zA-Z0-9_-]{1,64}$)。params 物件您可以透過將此清單傳入 requests 參數來建立批次:
在此範例中,兩個獨立的請求被批次處理在一起以進行非同步處理。每個請求都有唯一的 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 在建立批次時的回應中提供,或透過列出批次取得。您可以實作一個輪詢迴圈,定期檢查批次狀態,直到處理結束:
您可以使用列表端點列出您 Workspace 中的所有 Message Batches。API 支援分頁,會根據需要自動擷取額外頁面:
批次處理結束後,批次中的每個 Messages 請求都會有一個結果。共有 4 種結果類型:
| 結果類型 | 描述 |
|---|---|
succeeded | 請求成功。包含訊息結果。 |
errored | 請求遇到錯誤,未建立訊息。可能的錯誤包括無效請求和內部伺服器錯誤。您不會為這些請求付費。 |
canceled | 使用者在此請求發送到模型之前取消了批次。您不會為這些請求付費。 |
expired | 批次在此請求發送到模型之前達到 24 小時過期時間。您不會為這些請求付費。 |
您將透過批次的 request_counts 看到結果概覽,其中顯示達到這四種狀態的請求數量。
批次結果可在 Message Batch 的 results_url 屬性下載,如果組織權限允許,也可在 Console 中下載。由於結果可能很大,建議串流結果而不是一次下載全部。
結果為 .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-8","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-8","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,可能包含在取消前已處理的請求的部分結果。
回應將顯示批次處於 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 區塊在批次中實作提示快取的範例:
在此範例中,批次中的兩個請求都包含相同的系統訊息和標記為 cache_control 的《傲慢與偏見》全文,以增加快取命中的可能性。
所有伺服器工具(網頁搜尋、網頁擷取、程式碼執行、MCP 連接器、advisor 和工具搜尋)都可在批次請求中使用。批次工作程序執行與同步 Messages API 相同的伺服器端代理迴圈。
由於沒有需要維持的開放連線,批次迴圈在傳回 stop_reason: "pause_turn" 之前,每輪執行的迭代次數比同步請求更多。如果批次結果傳回 pause_turn,表示該輪尚未完成;您可以透過在後續請求(批次或同步)中提交暫停的助手內容來繼續,完全按照 pause_turn 接續模式中所示的方式進行。
批次工作程序還會針對每個組織限制 web_search 的速率,以確保高度並行的批次處理不會耗盡您組織的網頁搜尋速率限制。批次會自動重試受限制的請求;您不需要自行處理此問題,但非常大的網頁搜尋批次可能需要更長時間才能完成。
output-300k-2026-03-24 測試版標頭可將使用 Claude Opus 4.8、Claude Opus 4.7、Claude Opus 4.6 或 Claude Sonnet 4.6 的批次請求的 max_tokens 上限提高到 300,000。包含此標頭可在單一輪次中生成遠超過標準限制(根據模型不同為 64k 到 128k)的輸出。
擴展輸出僅在 Message Batches API 上可用,不適用於同步 Messages API。它在 Claude API 和 AWS 上的 Claude Platform 上受支援,目前在 Amazon Bedrock、Vertex AI 或 Microsoft Foundry 上不可用。
擴展輸出適用於長篇生成,例如書籍長度的草稿和技術文件、詳盡的結構化資料擷取、大型程式碼生成框架以及長推理鏈。
單次 300k token 的生成可能需要超過一小時才能完成,因此請在規劃批次提交時考慮 24 小時的處理時間窗口。適用標準批次定價(標準 API 價格的 50%)。
要充分利用 Batches API:
custom_id 值,以便輕鬆將結果與請求配對,因為順序無法保證。如果遇到非預期的行為:
request_too_large 錯誤。custom_id。created_at(而非處理 ended_at)時間起未超過 29 天。如果超過 29 天,結果將不再可檢視。請注意,批次中一個請求的失敗不會影響其他請求的處理。
Workspace 隔離:批次在其建立的 Workspace 內隔離。它們只能由與該 Workspace 關聯的 API 金鑰存取,或由有權在 Console 中檢視 Workspace 批次的使用者存取。
結果可用性:批次結果在批次建立後 29 天內可用,提供充足的時間進行擷取和處理。
批次處理會在批次建立後儲存請求和回應資料長達 29 天。您可以在處理完成後隨時使用 DELETE /v1/messages/batches/{batch_id} 端點刪除訊息批次。要刪除進行中的批次,請先取消它。非同步處理需要在伺服器端儲存輸入和輸出,直到批次完成和結果擷取為止。
有關所有功能的 ZDR 資格,請參閱 API 與資料保留。
| Claude Sonnet 4.6 | $1.50 / MTok | $7.50 / MTok |
| Claude Sonnet 4.5 | $1.50 / MTok | $7.50 / MTok |
| Claude Sonnet 4(已停用,Bedrock 和 Vertex AI 除外) | $1.50 / MTok | $7.50 / MTok |
| Claude Haiku 4.5 | $0.50 / MTok | $2.50 / MTok |
| Claude Haiku 3.5(已停用,Bedrock 和 Vertex AI 除外) | $0.40 / MTok | $2 / MTok |
from anthropic.types.message_create_params import MessageCreateParamsNonStreaming
from anthropic.types.messages.batch_create_params import Request
client = anthropic.Anthropic()
message_batch = client.messages.batches.create(
requests=[
Request(
custom_id="my-first-request",
params=MessageCreateParamsNonStreaming(
model="claude-opus-4-8",
max_tokens=1024,
messages=[
{
"role": "user",
"content": "Hello, world",
}
],
),
),
Request(
custom_id="my-second-request",
params=MessageCreateParamsNonStreaming(
model="claude-opus-4-8",
max_tokens=1024,
messages=[
{
"role": "user",
"content": "Hi again, friend",
}
],
),
),
]
)
print(message_batch)import time
client = anthropic.Anthropic()
MESSAGE_BATCH_ID = "msgbatch_01HkcTjaV5uDC8jWR4ZsDV8d"
message_batch = None
while True:
message_batch = client.messages.batches.retrieve(MESSAGE_BATCH_ID)
if message_batch.processing_status == "ended":
break
print(f"Batch {MESSAGE_BATCH_ID} is still processing...")
time.sleep(60)
print(message_batch)client = anthropic.Anthropic()
# 根據需要自動擷取更多頁面。
for message_batch in client.messages.batches.list(limit=20):
print(message_batch)client = anthropic.Anthropic()
# 以節省記憶體的區塊方式串流結果檔案,一次處理一個
for result in client.messages.batches.results(
"msgbatch_01HkcTjaV5uDC8jWR4ZsDV8d",
):
match result.result.type:
case "succeeded":
print(f"Success! {result.custom_id}")
case "errored":
if result.result.error.error.type == "invalid_request_error":
# 重新傳送請求前必須先修正請求主體
print(f"Validation error {result.custom_id}")
else:
# 請求可直接重試
print(f"Server error {result.custom_id}")
case "expired":
print(f"Request expired {result.custom_id}")client = anthropic.Anthropic()
MESSAGE_BATCH_ID = "msgbatch_01HkcTjaV5uDC8jWR4ZsDV8d"
message_batch = client.messages.batches.cancel(
MESSAGE_BATCH_ID,
)
print(message_batch)from anthropic.types.message_create_params import MessageCreateParamsNonStreaming
from anthropic.types.messages.batch_create_params import Request
client = anthropic.Anthropic()
message_batch = client.messages.batches.create(
requests=[
Request(
custom_id="my-first-request",
params=MessageCreateParamsNonStreaming(
model="claude-opus-4-8",
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.",
}
],
),
),
Request(
custom_id="my-second-request",
params=MessageCreateParamsNonStreaming(
model="claude-opus-4-8",
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.",
}
],
),
),
]
)from anthropic.types.beta.message_create_params import MessageCreateParamsNonStreaming
from anthropic.types.beta.messages.batch_create_params import Request
client = anthropic.Anthropic()
message_batch = client.beta.messages.batches.create(
betas=["output-300k-2026-03-24"],
requests=[
Request(
custom_id="long-form-request",
params=MessageCreateParamsNonStreaming(
model="claude-opus-4-8",
max_tokens=300_000,
messages=[
{
"role": "user",
"content": "Write a comprehensive technical guide to building distributed systems, covering architecture patterns, consistency models, fault tolerance, and operational best practices.",
}
],
),
),
],
)
print(message_batch)