Claude Platform Docs
Messages模型功能

批次處理

使用 Message Batches API 以非同步方式處理大量 Messages 請求,將成本降低 50% 並提高吞吐量。

「Batch processing」(批次處理)是一種高效處理大量請求的強大方法。批次處理讓您可以將多個請求一起提交以進行非同步處理,而不是一次處理一個請求並立即獲得回應。此模式在以下情況特別有用:

  • 您需要處理大量資料
  • 不需要立即回應
  • 您希望最佳化成本效益
  • 您正在執行大規模評估或分析

Message Batches API 是 Anthropic 對此模式的首個實作。

Message Batches API

Message Batches API 是一種強大且具成本效益的方式,可非同步處理大量 Messages可檢視預覽,內含 API 參考文件連結——按 Tab 鍵直到焦點進入卡片,按 Escape 鍵返回。 請求。此方法非常適合不需要立即回應的任務,大多數批次可在 1 小時內完成,同時將成本降低 50%,並提高「throughput」(吞吐量)。

除了本指南之外,您也可以直接查閱 API 參考文件可檢視預覽,內含 API 參考文件連結——按 Tab 鍵直到焦點進入卡片,按 Escape 鍵返回。。

Message Batches API 的運作方式

當您向 Message Batches API 發送請求時:

  1. 系統會使用提供的 Messages 請求建立新的 Message Batch。
  2. 接著以非同步方式處理該批次,每個請求都會獨立處理。
  3. 您可以輪詢批次的狀態,並在所有請求處理結束後擷取結果。

這對於不需要立即結果的大量操作特別有用,例如:

  • 大規模評估:有效率地處理數千個測試案例。
  • 內容審核:以非同步方式分析大量使用者產生的內容。
  • 資料分析:為大型資料集產生洞察或摘要。
  • 大量內容產生:為各種用途建立大量文字(例如產品描述、文章摘要)。

批次限制

  • 一個 Message Batch 的上限為 100,000 個 Message 請求或 256 MB 的大小,以先達到者為準。
  • 系統會盡可能快速地處理每個批次,大多數批次會在 1 小時內完成。您可以在所有訊息完成後或 24 小時後存取批次結果,以先發生者為準。如果處理未在 24 小時內完成,批次將會過期。
  • 批次結果在建立後 29 天內可供使用。之後,您仍然可以檢視該批次,但其結果將無法再下載。
  • 批次的範圍限定於 Claude Console 中的工作區。您可以檢視在您的請求所執行的工作區內建立的所有批次(及其結果)。
  • 「Rate limit」(速率限制)同時適用於 Batches API HTTP 請求以及批次中等待處理的請求數量。請參閱 Message Batches API 速率限制。此外,處理速度可能會根據目前需求和您的請求量而減慢。在這種情況下,您可能會看到更多請求在 24 小時後過期。
  • 由於高吞吐量和並行處理,批次可能會略微超過您在 Claude Console 中為工作區設定的支出限制。
  • 每個批次請求的 max_tokens可檢視預覽,內含 API 參考文件連結——按 Tab 鍵直到焦點進入卡片,按 Escape 鍵返回。 必須至少為 1。批次中不支援 max_tokens: 0(快取預熱),因為在批次處理期間寫入的臨時快取項目很可能會在後續請求執行之前過期。

支援的模型

所有現行模型都支援 Message Batches API。

可以批次處理的內容

幾乎任何您可以向 Messages API 發出的請求都可以包含在批次中。這包括:

  • 視覺
  • 「Tool use」(工具使用),包括所有伺服器工具(網路搜尋、網頁擷取、程式碼執行、MCP 連接器、顧問和工具搜尋)
  • 系統訊息
  • 多輪對話
  • 「Extended thinking」(擴展思考)
  • 大多數 beta 功能

由於批次中的每個請求都是獨立處理的,您可以在單一批次中混合不同類型的請求。

少數 Messages API 參數在批次請求中不受支援。包含其中任何一個都會傳回驗證錯誤:

參數原因
stream: true批次結果以單一檔案傳回,而非串流。
speed(快速模式)快速模式調整的是同步延遲,這不適用於非同步批次處理。
fallbacks(伺服器端備援)伺服器端備援不適用於批次。若要重試被拒絕的請求,請參閱 Message Batches 中的拒絕。
max_tokens: 0請參閱批次限制。

定價

Batches API 可大幅節省成本。所有用量均以標準 API 價格的 50% 計費。

模型批次 Token
名稱輸入輸出
Claude Fable 5.2For demanding reasoning and long-horizon agentic work
US$4 /
US$20 / MTok
Claude Opus 5.5For long-running agentic coding and knowledge work
US$2 / MTok
US$10 / MTok
Claude Sonnet 5.5The best combination of speed and intelligence
US$1 / MTok
US$5 / MTok
Claude Haiku 5.5For high-volume, latency-sensitive tasks such as classification, extraction, and routing
US$0.05 / MTok適用於不超過 100,000 個 Token 的提示詞
US$0.25 / MTok
US$0.25 / MTok適用於超過 100,000 個 Token 的提示詞
US$1.25 / MTok
US$4 / MTok
US$20 / MTok
US$5 / MTok
US$25 / MTok
US$5 / MTok
US$25 / MTok
US$5 / MTok
US$25 / MTok
US$5 / MTok
US$25 / MTok
US$2.50 / MTok
US$12.50 / MTok
US$2.50 / MTok
US$12.50 / MTok
US$2.50 / MTok
US$12.50 / MTok
US$2.50 / MTok
US$12.50 / MTok
US$2.50 / MTok
US$12.50 / MTok
Claude Opus 4.1
US$7.50 / MTok
US$37.50 / MTok
Claude Opus 4
US$7.50 / MTok
US$37.50 / MTok
US$1 / MTok
US$5 / MTok
US$1.50 / MTok
US$7.50 / MTok
US$1.50 / MTok
US$7.50 / MTok
Claude Sonnet 4
US$1.50 / MTok
US$7.50 / MTok
US$0.50 / MTok
US$2.50 / MTok

如何使用 Message Batches API

準備並建立您的批次

Message Batch 由建立 Message 的請求清單組成。單一請求的結構包括:

  • 用於識別 Messages 請求的唯一 custom_id可檢視預覽,內含 API 參考文件連結——按 Tab 鍵直到焦點進入卡片,按 Escape 鍵返回。。長度必須為 1 到 64 個字元,且只能包含英數字元、連字號和底線(符合 ^[a-zA-Z0-9_-]{1,64}$)。
  • 包含標準 Messages API可檢視預覽,內含 API 參考文件連結——按 Tab 鍵直到焦點進入卡片,按 Escape 鍵返回。 參數的 params可檢視預覽,內含 API 參考文件連結——按 Tab 鍵直到焦點進入卡片,按 Escape 鍵返回。 物件

您可以將此清單傳入 requests 參數來建立批次可檢視預覽,內含 API 參考文件連結——按 Tab 鍵直到焦點進入卡片,按 Escape 鍵返回。:

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-5-5",
                max_tokens=1024,
                messages=[
                    {
                        "role": "user",
                        "content": "Hello, world",
                    }
                ],
            ),
        ),
        Request(
            custom_id="my-second-request",
            params=MessageCreateParamsNonStreaming(
                model="claude-opus-5-5",
                max_tokens=1024,
                messages=[
                    {
                        "role": "user",
                        "content": "Hi again, friend",
                    }
                ],
            ),
        ),
    ]
)

print(message_batch)

在此範例中,兩個獨立的請求被批次在一起以進行非同步處理。每個請求都有唯一的 custom_id,並包含您在 Messages API 呼叫中會使用的標準參數。

批次首次建立時,回應的處理狀態為 in_progress。

Output
{
  "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可檢視預覽,內含 API 參考文件連結——按 Tab 鍵直到焦點進入卡片,按 Escape 鍵返回。 欄位表示批次目前所處的處理階段。它一開始為 in_progress,然後在批次中的所有請求都完成處理且結果準備就緒後更新為 ended。您可以造訪 Console 或使用擷取端點來監控批次的狀態。

Retrieve a Message Batch

GET/v1/messages/batches/{message_batch_id}

This endpoint is idempotent and can be used to poll for Message Batch completion. To access the results of a Message Batch, make a request to the results_url field in the response.

輪詢 Message Batch 完成狀態

若要輪詢 Message Batch,您需要其 id,該 id 會在建立批次時的回應中提供,或透過列出批次取得。您可以實作一個輪詢迴圈,定期檢查批次狀態,直到處理結束:

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)

列出所有 Message Batches

您可以使用列出端點可檢視預覽,內含 API 參考文件連結——按 Tab 鍵直到焦點進入卡片,按 Escape 鍵返回。列出工作區中的所有 Message Batches。此 API 支援分頁,會視需要自動擷取其他頁面:

client = anthropic.Anthropic()

# 會視需要自動擷取更多頁面。
for message_batch in client.messages.batches.list(limit=20):
    print(message_batch)

擷取批次結果

批次處理結束後,批次中的每個 Messages 請求都會有一個結果。共有四種結果類型:

結果類型說明
succeeded請求成功。包含訊息結果。
errored請求遇到錯誤,且未建立訊息。可能的錯誤包括無效的請求和內部伺服器錯誤。這些請求不會向您收費。
canceled使用者在此請求傳送至模型之前取消了批次。這些請求不會向您收費。
expired批次在此請求傳送至模型之前已達到 24 小時的過期時間。這些請求不會向您收費。

批次的 request_counts 物件會計算仍在處理中的請求,以及各結果類型的請求數量。

request_counts: MessageBatchRequestCounts { canceled, errored, expired, 2 more }

Tallies requests within the Message Batch, categorized by their status.

Requests start as processing and move to one of the other statuses only once processing of the entire batch ends. The sum of all values always matches the total number of requests in the batch.

canceled: number

Number of requests in the Message Batch that have been canceled.

This is zero until processing of the entire Message Batch has ended.

default0
errored: number

Number of requests in the Message Batch that encountered an error.

This is zero until processing of the entire Message Batch has ended.

default0
expired: number

Number of requests in the Message Batch that have expired.

This is zero until processing of the entire Message Batch has ended.

default0
processing: number

Number of requests in the Message Batch that are processing.

default0
succeeded: number

Number of requests in the Message Batch that have completed successfully.

This is zero until processing of the entire Message Batch has ended.

default0

批次的結果可從 Message Batch 上的 results_url可檢視預覽,內含 API 參考文件連結——按 Tab 鍵直到焦點進入卡片,按 Escape 鍵返回。 屬性下載,若組織權限允許,也可在 Console 中下載。由於結果可能很大,建議以串流方式傳回結果可檢視預覽,內含 API 參考文件連結——按 Tab 鍵直到焦點進入卡片,按 Escape 鍵返回。,而不是一次全部下載。

client = anthropic.Anthropic()

# 以節省記憶體的區塊串流讀取結果檔案,一次處理一個
for result in client.messages.batches.results(
    "msgbatch_01HkcTjaV5uDC8jWR4ZsDV8d",
):
    outcome = result.result
    match outcome.type:
        case "succeeded":
            print(f"Success! {result.custom_id}")
        case "errored":
            if outcome.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}")

結果採用 .jsonl 格式,其中每一行都是一個有效的 JSON 物件,代表 Message Batch 中單一請求的結果。對於每個串流傳回的結果,您可以根據其 custom_id 和結果類型執行不同的操作。以下是一組範例結果:

.jsonl file
{"custom_id":"my-second-request","result":{"type":"succeeded","message":{"id":"msg_014VwiXbi91y3JMjcpyGBHX5","type":"message","role":"assistant","model":"claude-opus-5-5","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-5-5","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 將設定為標準的錯誤結構。

批次結果使用建立該批次之請求的 API 版本。

取消 Message Batch

您可以使用取消端點可檢視預覽,內含 API 參考文件連結——按 Tab 鍵直到焦點進入卡片,按 Escape 鍵返回。取消目前正在處理的 Message Batch。取消後,批次的 processing_status 會立即變為 canceling。您可以使用前面描述的相同輪詢技術,等待取消完成。已取消的批次最終狀態為 ended,並且可能包含在取消之前已處理之請求的部分結果。

client = anthropic.Anthropic()

MESSAGE_BATCH_ID = "msgbatch_01HkcTjaV5uDC8jWR4ZsDV8d"

message_batch = client.messages.batches.cancel(
    MESSAGE_BATCH_ID,
)
print(message_batch)

回應顯示批次處於 canceling 狀態:

Output
{
  "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 中使用提示快取

Message Batches API 支援「prompt caching」(提示快取),可能讓您降低批次請求的成本和處理時間。提示快取和 Message Batches 的定價折扣可以疊加,當兩個功能一起使用時可節省更多成本。然而,由於批次請求是以非同步且並行的方式處理,快取命中是以盡力而為的方式提供。使用者的快取命中率通常介於 30% 到 98% 之間,視其流量模式而定。

若要最大化批次請求中快取命中的可能性:

  1. 在批次中的每個 Message 請求中包含相同的 cache_control 區塊。
  2. 維持穩定的請求串流,以防止快取項目在其 5 分鐘的存留期後過期。
  3. 建構您的請求,以盡可能共用更多快取內容。

在批次中實作提示快取的範例:

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-5-5",
                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-5-5",
                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 標記的《傲慢與偏見》全文,以提高快取命中的可能性。

伺服器工具與代理迴圈

所有伺服器工具(網路搜尋、網頁擷取、程式碼執行、MCP 連接器、顧問和工具搜尋)都可在批次請求中運作。批次工作程序執行的伺服器端「agentic loop」(代理迴圈)與同步 Messages API 相同。

由於不需要維持開啟的連線,批次迴圈在傳回 stop_reason: "pause_turn" 之前,在一個回合中可以執行比同步請求更多的迭代。如果批次結果以 pause_turn 傳回,表示該回合未完成;您可以在後續請求(批次或同步)中提交暫停的助理內容來繼續該回合,方式完全如 pause_turn 延續模式所示。

批次工作程序還會針對每個組織對 web_search 進行節流,以免高度並行的批次處理耗盡您組織的網路搜尋速率限制。批次會自動重試被節流的請求;您不需要自行處理,但非常大型的網路搜尋批次可能需要更長的時間才能完成。

擴展輸出(beta)

output-300k-2026-03-24 beta 標頭會將使用 Claude Opus 5.5、Claude Opus 5、Claude Opus 4.8、Claude Opus 4.7、Claude Opus 4.6、Claude Sonnet 5.5、Claude Sonnet 5、Claude Sonnet 4.6 或 Claude Haiku 5.5 的批次請求的 max_tokens 上限提高至 300,000。包含此標頭即可在單一回合中產生遠超過標準 128k max_tokens 限制的輸出。

將擴展輸出用於長篇內容產生,例如書籍長度的草稿和技術文件、詳盡的結構化資料擷取、大型程式碼產生框架,以及長推理鏈。

單次 300k token 的產生可能需要超過一小時才能完成,因此請在規劃批次提交時考量 24 小時的處理時間範圍。適用標準批次定價(標準 API 價格的 50%)。

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-5-5",
                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)

有效批次處理的最佳實務

若要有效使用 Batches API:

  • 定期監控批次處理狀態,並為失敗的請求實作適當的重試邏輯。
  • 使用有意義的 custom_id 值,以便輕鬆將結果與請求配對,因為順序無法保證。
  • 考慮將非常大的資料集拆分成多個批次,以便更好地管理。
  • 使用 Messages API 試執行單一請求結構,以避免驗證錯誤。

常見問題疑難排解

如果遇到非預期的行為:

  • 確認批次請求的總大小未超過 256 MB。如果請求大小過大,您可能會收到 413 request_too_large 錯誤。
  • 檢查您是否對批次中的所有請求使用支援的模型。
  • 確保批次中的每個請求都有唯一的 custom_id。
  • 確保距離批次 created_at(而非處理 ended_at)時間不到 29 天。如果已超過 29 天,將無法再檢視結果。
  • 確認批次未被取消。

請注意,批次中一個請求的失敗不會影響其他請求的處理。

批次儲存與隱私

  • 工作區隔離: 批次會在其建立所在的工作區內隔離。它們只能由同一工作區中的 API 請求存取,或由有權限在 Console 中檢視工作區批次的使用者存取。

  • 結果可用性: 批次結果在批次建立後 29 天內可供使用,讓您有充足的時間進行擷取和處理。

常見問題

可用性

批次處理
Availability requirements for 批次處理 are the same across all supported platforms.
API
  • Messages API
  • Managed Agents 不支援
模型
  • 所有模型

資料處理

資料處理概覽

適用端點

  • /v1/messages/batches
零資料保留不符合資格

保留 29 天;需要非同步儲存。 深入了解

HIPAA不符合資格

批次處理會在批次建立後儲存請求和回應資料最長 29 天。處理完成後,您可以隨時使用 DELETE /v1/messages/batches/{batch_id}可檢視預覽,內含 API 參考文件連結——按 Tab 鍵直到焦點進入卡片,按 Escape 鍵返回。 端點刪除訊息批次。若要刪除處理中的批次,請先將其取消。非同步處理需要在伺服器端儲存輸入和輸出,直到批次完成並擷取結果為止。

後續步驟

透過提供附有來源歸屬的搜尋結果,為 RAG 應用程式取得自然的引用。

透過快取批次中各請求共用的提示前綴,降低成本和延遲。

這個頁面有幫助嗎?