---
title: 批次處理
url: https://platform.claude.com/docs/zh-TW/build-with-claude/batch-processing
description: 使用 Message Batches API 非同步處理大量 Messages 請求，將成本降低 50% 並提高吞吐量。
---

「Batch processing」（批次處理）是一種高效處理大量請求的強大方法。批次處理不是一次處理一個請求並立即回應，而是允許您將多個請求一起提交以進行非同步處理。此模式在以下情況特別有用：

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

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

<Note>
  若要了解「zero data retention」（零資料保留），即 ZDR 如何適用於此功能，請參閱 [API 與資料保留](https://platform.claude.com/docs/zh-TW/manage-claude/api-and-data-retention)。
</Note>

# Message Batches API

Message Batches API 是一種強大且具成本效益的方式，可非同步處理大量 [Messages](https://platform.claude.com/docs/zh-TW/api/messages/create) 請求。此方法非常適合不需要立即回應的任務，大多數批次在 1 小時內完成，同時將成本降低 50% 並提高吞吐量。

除了本指南之外，您也可以[直接探索 API 參考文件](https://platform.claude.com/docs/zh-TW/api/messages/batches/create)。

## Message Batches API 的運作方式

當您向 Message Batches API 傳送請求時：

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

這對於不需要立即結果的大量作業特別有用，例如：

* 大規模評估：高效處理數千個測試案例。
* 內容審核：非同步分析大量使用者產生的內容。
* 資料分析：為大型資料集產生洞察或摘要。
* 大量內容生成：為各種用途建立大量文字（例如產品描述、文章摘要）。

### 批次限制

* 一個 Message Batch 的上限為 100,000 個 Message 請求或 256 MB 大小，以先達到者為準。
* 系統會盡快處理每個批次，大多數批次在 1 小時內完成。您可以在所有訊息完成後或 24 小時後（以先到者為準）存取批次結果。若處理未在 24 小時內完成，批次將會過期。
* 批次結果在建立後 29 天內可供使用。之後您仍可檢視該 Batch，但其結果將無法再下載。
* 批次的範圍限定於 [Workspace](https://platform.claude.com/settings/workspaces)。您可以檢視在您請求所執行的 Workspace 中建立的所有批次（及其結果）。
* 「Rate limit」（速率限制）同時適用於 Batches API HTTP 請求以及批次中等待處理的請求數量。請參閱 [Message Batches API 速率限制](https://platform.claude.com/docs/zh-TW/api/rate-limits#message-batches-api)。此外，處理速度可能會根據目前需求和您的請求量而減慢。在這種情況下，您可能會看到更多請求在 24 小時後過期。
* 由於高吞吐量和並行處理，批次可能會略微超出您 Workspace 所設定的[支出限制](https://platform.claude.com/settings/billing)。
* 每個批次請求的 `max_tokens` 必須至少為 `1`。批次內不支援 `max_tokens: 0`（[快取預熱](https://platform.claude.com/docs/zh-TW/build-with-claude/prompt-caching#pre-warming-the-cache)），因為在批次處理期間寫入的暫時性快取項目很可能在後續請求執行之前就已過期。

### 支援的模型

所有[現行模型](https://platform.claude.com/docs/zh-TW/models/overview)皆支援 Message Batches API。

### 可批次處理的內容

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

* 視覺
* 「Tool use」（工具使用），包括所有[伺服器工具](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/server-tools)（網頁搜尋、網頁擷取、程式碼執行、MCP 連接器、advisor 以及工具搜尋）
* 系統訊息
* 多輪對話
* 「Extended thinking」（擴展思考）
* 大多數 beta 功能

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

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

| 參數                                                                                  | 原因                                                                                                      |
| ----------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- |
| `stream: true`                                                                      | 批次結果以單一檔案傳回，而非串流。                                                                                       |
| `speed`（[快速模式](https://platform.claude.com/docs/zh-TW/build-with-claude/fast-mode)） | 快速模式調整的是同步延遲，這不適用於非同步批次處理。                                                                              |
| `max_tokens: 0`                                                                     | 請參閱[批次限制](https://platform.claude.com/docs/zh-TW/build-with-claude/batch-processing#batch-limitations)。 |

<Tip>
  由於批次處理可能需要超過 5 分鐘，在處理具有共享上下文的批次時，請考慮搭配「prompt caching」（提示快取）使用 [1 小時快取時長](https://platform.claude.com/docs/zh-TW/build-with-claude/prompt-caching#1-hour-cache-duration)，以獲得更好的快取命中率。
</Tip>

## 定價

Batches API 提供顯著的成本節省。所有用量皆以標準 API 價格的 50% 計費。

| Model                                                                                                                                   | Batch input  | Batch output  |
| :-------------------------------------------------------------------------------------------------------------------------------------- | :----------- | :------------ |
| Claude Fable 5.1                                                                                                                        | $5 / MTok    | $25 / MTok    |
| Claude Mythos 5.1 ([limited availability](https://support.claude.com/en/articles/14604842))                                             | $5 / MTok    | $25 / MTok    |
| Claude Fable 5                                                                                                                          | $5 / MTok    | $25 / MTok    |
| Claude Mythos 5 ([limited availability](https://support.claude.com/en/articles/14604842))                                               | $5 / MTok    | $25 / MTok    |
| Claude Opus 5.5                                                                                                                         | $2 / MTok    | $10 / MTok    |
| Claude Opus 5                                                                                                                           | $2.50 / MTok | $12.50 / 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 ([retired, except on Bedrock and Google Cloud](https://platform.claude.com/docs/zh-TW/about-claude/model-deprecations)) | $7.50 / MTok | $37.50 / MTok |
| Claude Opus 4 ([retired, except on Google Cloud](https://platform.claude.com/docs/zh-TW/about-claude/model-deprecations))               | $7.50 / MTok | $37.50 / MTok |
| Claude Sonnet 5.5                                                                                                                       | $1 / MTok    | $5 / MTok     |
| Claude Sonnet 5                                                                                                                         | $1 / MTok    | $5 / MTok     |
| Claude Sonnet 4.6                                                                                                                       | $1.50 / MTok | $7.50 / MTok  |
| Claude Sonnet 4.5                                                                                                                       | $1.50 / MTok | $7.50 / MTok  |
| Claude Sonnet 4 ([retired, except on Bedrock and Google Cloud](https://platform.claude.com/docs/zh-TW/about-claude/model-deprecations)) | $1.50 / MTok | $7.50 / MTok  |
| Claude Haiku 5.5 (for prompts up to 100,000 tokens)                                                                                     | $0.05 / MTok | $0.25 / MTok  |
| Claude Haiku 5.5 (for prompts over 100,000 tokens)                                                                                      | $0.25 / MTok | $1.25 / MTok  |
| Claude Haiku 4.5                                                                                                                        | $0.50 / MTok | $2.50 / MTok  |
| Claude Haiku 3.5 ([retired, except on Google Cloud](https://platform.claude.com/docs/zh-TW/about-claude/model-deprecations))            | $0.40 / MTok | $2 / MTok     |

* **MTok:** Million tokens. $5 / MTok is $5 for every million tokens.
* **Limited access:** Available only to organizations verified through Anthropic’s verification programs, such as the [Cyber Verification Program](https://support.claude.com/en/articles/14604842). To request access, apply to the program that covers your use case.
* **Retired:** May still be available on other cloud platforms. See [Model deprecations](https://platform.claude.com/docs/zh-TW/about-claude/model-deprecations) for more.

## 如何使用 Message Batches API

### 準備並建立您的批次

一個 Message Batch 由一組建立 Message 的請求清單組成。單一請求的結構包含：

* 用於識別 Messages 請求的唯一 `custom_id`。必須為 1 到 64 個字元，且僅包含英數字元、連字號和底線（符合 `^[a-zA-Z0-9_-]{1,64}$`）。
* 一個包含標準 [Messages API](https://platform.claude.com/docs/zh-TW/api/messages/create) 參數的 `params` 物件

您可以將此清單傳入 `requests` 參數來[建立批次](https://platform.claude.com/docs/zh-TW/api/messages/batches/create)：

<CodeGroup>
  ```bash cURL
  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-5-5",
                  "max_tokens": 1024,
                  "messages": [
                      {"role": "user", "content": "Hello, world"}
                  ]
              }
          },
          {
              "custom_id": "my-second-request",
              "params": {
                  "model": "claude-opus-5-5",
                  "max_tokens": 1024,
                  "messages": [
                      {"role": "user", "content": "Hi again, friend"}
                  ]
              }
          }
      ]
  }'
  ```

  ```bash CLI
  ant messages:batches create <<'YAML'
  requests:
    - custom_id: my-first-request
      params:
        model: claude-opus-5-5
        max_tokens: 1024
        messages:
          - role: user
            content: Hello, world
    - custom_id: my-second-request
      params:
        model: claude-opus-5-5
        max_tokens: 1024
        messages:
          - role: user
            content: Hi again, friend
  YAML
  ```

  ```python Python
  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)
  ```

  ```typescript TypeScript
  const client = new Anthropic();

  const messageBatch = await client.messages.batches.create({
    requests: [
      {
        custom_id: "my-first-request",
        params: {
          model: "claude-opus-5-5",
          max_tokens: 1024,
          messages: [{ role: "user", content: "Hello, world" }]
        }
      },
      {
        custom_id: "my-second-request",
        params: {
          model: "claude-opus-5-5",
          max_tokens: 1024,
          messages: [{ role: "user", content: "Hi again, friend" }]
        }
      }
    ]
  });

  console.log(messageBatch);
  ```

  ```csharp C#
  using Anthropic;
  using Anthropic.Models.Messages;
  using Anthropic.Models.Messages.Batches;

  AnthropicClient client = new();

  var batch = await client.Messages.Batches.Create(new BatchCreateParams
  {
      Requests =
      [
          new()
          {
              CustomID = "my-first-request",
              Params = new()
              {
                  Model = Model.ClaudeOpus5_5,
                  MaxTokens = 1024,
                  Messages =
                  [
                      new() { Role = Role.User, Content = "Hello, world" }
                  ]
              }
          },
          new()
          {
              CustomID = "my-second-request",
              Params = new()
              {
                  Model = Model.ClaudeOpus5_5,
                  MaxTokens = 1024,
                  Messages =
                  [
                      new() { Role = Role.User, Content = "Hi again, friend" }
                  ]
              }
          }
      ]
  });

  Console.WriteLine(batch);
  ```

  ```go Go
  client := anthropic.NewClient()

  batch, _ := client.Messages.Batches.New(context.Background(),
  	anthropic.MessageBatchNewParams{
  		Requests: []anthropic.MessageBatchNewParamsRequest{
  			{
  				CustomID: "my-first-request",
  				Params: anthropic.MessageBatchNewParamsRequestParams{
  					Model:     anthropic.ModelClaudeOpus5_5,
  					MaxTokens: 1024,
  					Messages: []anthropic.MessageParam{
  						anthropic.NewUserMessage(
  							anthropic.NewTextBlock("Hello, world"),
  						),
  					},
  				},
  			},
  			{
  				CustomID: "my-second-request",
  				Params: anthropic.MessageBatchNewParamsRequestParams{
  					Model:     anthropic.ModelClaudeOpus5_5,
  					MaxTokens: 1024,
  					Messages: []anthropic.MessageParam{
  						anthropic.NewUserMessage(
  							anthropic.NewTextBlock("Hi again, friend"),
  						),
  					},
  				},
  			},
  		},
  	})

  fmt.Println(batch.ID)
  ```

  ```java Java
  AnthropicClient client = AnthropicOkHttpClient.fromEnv();

  BatchCreateParams params = BatchCreateParams.builder()
    .addRequest(
      BatchCreateParams.Request.builder()
        .customId("my-first-request")
        .params(
          BatchCreateParams.Request.Params.builder()
            .model(Model.CLAUDE_OPUS_5_5)
            .maxTokens(1024)
            .addUserMessage("Hello, world")
            .build()
        )
        .build()
    )
    .addRequest(
      BatchCreateParams.Request.builder()
        .customId("my-second-request")
        .params(
          BatchCreateParams.Request.Params.builder()
            .model(Model.CLAUDE_OPUS_5_5)
            .maxTokens(1024)
            .addUserMessage("Hi again, friend")
            .build()
        )
        .build()
    )
    .build();

  MessageBatch messageBatch = client.messages().batches().create(params);

  System.out.println(messageBatch);
  ```

  ```php PHP
  $client = new Client();

  $batch = $client->messages->batches->create(
      requests: [
          [
              'custom_id' => 'my-first-request',
              'params' => [
                  'model' => 'claude-opus-5-5',
                  'max_tokens' => 1024,
                  'messages' => [
                      ['role' => 'user', 'content' => 'Hello, world']
                  ]
              ]
          ],
          [
              'custom_id' => 'my-second-request',
              'params' => [
                  'model' => 'claude-opus-5-5',
                  'max_tokens' => 1024,
                  'messages' => [
                      ['role' => 'user', 'content' => 'Hi again, friend']
                  ]
              ]
          ]
      ],
  );

  echo $batch->id;
  ```

  ```ruby Ruby
  client = Anthropic::Client.new

  batch = client.messages.batches.create(
    requests: [
      {
        custom_id: "my-first-request",
        params: {
          model: "claude-opus-5-5",
          max_tokens: 1024,
          messages: [
            { role: "user", content: "Hello, world" }
          ]
        }
      },
      {
        custom_id: "my-second-request",
        params: {
          model: "claude-opus-5-5",
          max_tokens: 1024,
          messages: [
            { role: "user", content: "Hi again, friend" }
          ]
        }
      }
    ]
  )

  puts batch
  ```
</CodeGroup>

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

<Tip>
  **使用 Messages API 測試您的批次請求**

  每個訊息請求的 `params` 物件驗證是以非同步方式執行的，驗證錯誤會在整個批次處理結束時傳回。您可以先使用 [Messages API](https://platform.claude.com/docs/zh-TW/api/messages/create) 驗證您的請求結構，以確保您正確建構輸入。
</Tip>

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

```json 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` 欄位表示批次所處的處理階段。它從 `in_progress` 開始，一旦批次中的所有請求處理完成且結果就緒，便會更新為 `ended`。您可以造訪 [Console](https://platform.claude.com/settings/workspaces/default/batches) 或使用[擷取端點](https://platform.claude.com/docs/zh-TW/api/messages/batches/retrieve)來監控批次的狀態。

#### 輪詢 Message Batch 完成狀態

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

<CodeGroup>
  ```bash cURL
  #!/bin/sh
  # ...
  # 檢查狀態；重複執行直到 processing_status 為 "ended"
  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" \
    | jq -r '.processing_status'
  ```

  ```bash CLI
  #!/bin/bash
  # ...
  # 檢查狀態；重複執行直到 processing_status 為 "ended"
  ant messages:batches retrieve \
    --message-batch-id "$MESSAGE_BATCH_ID" \
    --transform processing_status --raw-output
  ```

  ```python Python
  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)
  ```

  ```typescript TypeScript
  const client = new Anthropic();

  const messageBatchId = "msgbatch_01HkcTjaV5uDC8jWR4ZsDV8d";

  let messageBatch;
  while (true) {
    messageBatch = await client.messages.batches.retrieve(messageBatchId);
    if (messageBatch.processing_status === "ended") {
      break;
    }

    console.log(`Batch ${messageBatchId} is still processing... waiting`);
    await new Promise((resolve) => setTimeout(resolve, 60_000));
  }
  console.log(messageBatch);
  ```

  ```csharp C#
  AnthropicClient client = new();
  string messageBatchId = Environment.GetEnvironmentVariable("MESSAGE_BATCH_ID");

  MessageBatch messageBatch = null;
  while (true)
  {
      messageBatch = await client.Messages.Batches.Retrieve(messageBatchId);
      if (messageBatch.ProcessingStatus == "ended")
      {
          break;
      }

      Console.WriteLine($"Batch {messageBatchId} is still processing...");
      await Task.Delay(60000);
  }
  Console.WriteLine(messageBatch);
  ```

  ```go Go
  client := anthropic.NewClient()
  messageBatchID := os.Getenv("MESSAGE_BATCH_ID")

  var messageBatch *anthropic.MessageBatch
  for {
  	var err error
  	messageBatch, err = client.Messages.Batches.Get(context.TODO(), messageBatchID, anthropic.MessageBatchGetParams{})
  	if err != nil {
  		log.Fatal(err)
  	}
  	if messageBatch.ProcessingStatus == "ended" {
  		break
  	}

  	fmt.Printf("Batch %s is still processing...\n", messageBatchID)
  	time.Sleep(60 * time.Second)
  }
  fmt.Println(messageBatch)
  ```

  ```java Java
  import com.anthropic.models.messages.batches.MessageBatch;
  // ...
          AnthropicClient client = AnthropicOkHttpClient.fromEnv();
          String messageBatchId = "msgbatch_01HkcTjaV5uDC8jWR4ZsDV8d";

          MessageBatch messageBatch = null;
          while (true) {
              messageBatch = client.messages().batches().retrieve(messageBatchId);
              if (messageBatch.processingStatus().equals(MessageBatch.ProcessingStatus.ENDED)) {
                  break;
              }

              System.out.println("Batch " + messageBatchId + " is still processing...");
              Thread.sleep(60000);
          }
          System.out.println(messageBatch);
  ```

  ```php PHP
  $client = new Client();
  $messageBatchId = getenv("MESSAGE_BATCH_ID");

  $messageBatch = null;
  while (true) {
      $messageBatch = $client->messages->batches->retrieve(
          messageBatchID: $messageBatchId,
      );
      if ($messageBatch->processingStatus === "ended") {
          break;
      }

      echo "Batch {$messageBatchId} is still processing...\n";
      sleep(60);
  }
  echo json_encode($messageBatch, JSON_PRETTY_PRINT);
  ```

  ```ruby Ruby
  client = Anthropic::Client.new

  message_batch_id = ENV["MESSAGE_BATCH_ID"]
  message_batch = nil
  loop do
    message_batch = client.messages.batches.retrieve(message_batch_id)
    break if message_batch.processing_status == :ended

    puts "Batch #{message_batch_id} is still processing..."
    sleep 60
  end
  puts message_batch
  ```
</CodeGroup>

### 列出所有 Message Batches

您可以使用[列表端點](https://platform.claude.com/docs/zh-TW/api/messages/batches/list)列出您 Workspace 中的所有 Message Batches。API 支援分頁，會視需要自動擷取額外頁面：

<CodeGroup>
  ```bash cURL
  #!/bin/sh
  # 擷取一頁。當回應的 has_more 為 true 時，將其
  # last_id 作為 after_id 傳入以擷取下一頁。（SDK 與 CLI
  # 會自動執行分頁。）
  curl -s "https://api.anthropic.com/v1/messages/batches?limit=20" \
    --header "x-api-key: $ANTHROPIC_API_KEY" \
    --header "anthropic-version: 2023-06-01"
  ```

  ```bash CLI
  # 視需要自動擷取更多頁面
  ant messages:batches list --limit 20
  ```

  ```python Python
  client = anthropic.Anthropic()

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

  ```typescript TypeScript
  const client = new Anthropic();

  // 視需要自動擷取更多頁面。
  for await (const messageBatch of client.messages.batches.list({
    limit: 20
  })) {
    console.log(messageBatch);
  }
  ```

  ```csharp C#
  AnthropicClient client = new();

  var parameters = new BatchListParams
  {
      Limit = 20
  };

  // 視需要自動擷取更多頁面
  var page = await client.Messages.Batches.List(parameters);
  await foreach (var messageBatch in page.Paginate())
  {
      Console.WriteLine(messageBatch);
  }
  ```

  ```go Go
  client := anthropic.NewClient()

  // 視需要自動擷取更多頁面
  iter := client.Messages.Batches.ListAutoPaging(context.TODO(), anthropic.MessageBatchListParams{
  	Limit: anthropic.Int(20),
  })

  for iter.Next() {
  	messageBatch := iter.Current()
  	fmt.Println(messageBatch)
  }

  if err := iter.Err(); err != nil {
  	log.Fatal(err)
  }
  ```

  ```java Java
  AnthropicClient client = AnthropicOkHttpClient.fromEnv();

  // 視需要自動擷取更多頁面
  for (MessageBatch messageBatch : client
    .messages()
    .batches()
    .list(BatchListParams.builder().limit(20).build())
    .autoPager()) {
    System.out.println(messageBatch);
  }
  ```

  ```php PHP
  $client = new Client();

  // 視需要自動擷取更多頁面
  foreach ($client->messages->batches->list(limit: 20)->pagingEachItem() as $messageBatch) {
      echo $messageBatch->id . "\n";
  }
  ```

  ```ruby Ruby
  client = Anthropic::Client.new

  # 視需要自動擷取更多頁面
  client.messages.batches.list(limit: 20).auto_paging_each do |message_batch|
    puts message_batch
  end
  ```
</CodeGroup>

### 擷取批次結果

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

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

批次的 `request_counts` 顯示您結果的概覽，指出有多少請求達到這四種狀態中的每一種。

批次的結果可透過 Message Batch 上的 `results_url` 屬性下載，若組織權限允許，也可在 Console 中取得。由於結果可能非常龐大，建議以[串流方式取回結果](https://platform.claude.com/docs/zh-TW/api/messages/batches/results)，而非一次全部下載。

<CodeGroup>
  ```bash cURL
  #!/bin/sh
  # 取得批次的 results_url，然後串流其所指向的 .jsonl 結果。
  # 若需逐筆結果處理（重試、驗證錯誤），
  # 請使用其他分頁中的 SDK 範例。
  RESULTS_URL=$(curl -s "https://api.anthropic.com/v1/messages/batches/msgbatch_01HkcTjaV5uDC8jWR4ZsDV8d" \
    --header "anthropic-version: 2023-06-01" \
    --header "x-api-key: $ANTHROPIC_API_KEY" \
    | jq -r '.results_url')

  curl -s "$RESULTS_URL" \
    --header "anthropic-version: 2023-06-01" \
    --header "x-api-key: $ANTHROPIC_API_KEY" \
    | jq -r '"\(.result.type): \(.custom_id)"'
  ```

  ```bash CLI
  # 每個結果列印一行，例如 `{"custom_id":"test-1","type":"succeeded",…}`。
  # 若需逐一處理結果（重試、驗證錯誤），請使用其他分頁中的
  # SDK 範例。
  ant messages:batches results \
    --message-batch-id msgbatch_01HkcTjaV5uDC8jWR4ZsDV8d \
    --transform '{custom_id,"type":result.type,"error":result.error.error.type}' \
    --format jsonl
  ```

  ```python Python
  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}")
  ```

  ```typescript TypeScript
  const client = new Anthropic();

  // 以節省記憶體的分塊方式串流結果檔案，逐一處理
  for await (const result of await client.messages.batches.results(
    "msgbatch_01HkcTjaV5uDC8jWR4ZsDV8d"
  )) {
    switch (result.result.type) {
      case "succeeded":
        console.log(`Success! ${result.custom_id}`);
        break;
      case "errored":
        if (result.result.error.type === "invalid_request_error") {
          // 重新傳送請求前必須先修正請求主體
          console.log(`Validation error: ${result.custom_id}`);
        } else {
          // 請求可直接重試
          console.log(`Server error: ${result.custom_id}`);
        }
        break;
      case "expired":
        console.log(`Request expired: ${result.custom_id}`);
        break;
    }
  }
  ```

  ```csharp C#
  AnthropicClient client = new();

  await foreach (var result in client.Messages.Batches.ResultsStreaming("msgbatch_01HkcTjaV5uDC8jWR4ZsDV8d"))
  {
      switch (result.Result.Type)
      {
          case "succeeded":
              Console.WriteLine($"Success! {result.CustomID}");
              break;
          case "errored":
              if (result.Result.Error?.Type == "invalid_request")
              {
                  Console.WriteLine($"Validation error: {result.CustomID}");
              }
              else
              {
                  Console.WriteLine($"Server error: {result.CustomID}");
              }
              break;
          case "expired":
              Console.WriteLine($"Request expired: {result.CustomID}");
              break;
      }
  }
  ```

  ```go Go
  client := anthropic.NewClient()

  stream := client.Messages.Batches.ResultsStreaming(context.TODO(), "msgbatch_01HkcTjaV5uDC8jWR4ZsDV8d", anthropic.MessageBatchResultsParams{})

  for stream.Next() {
  	result := stream.Current()

  	switch variant := result.Result.AsAny().(type) {
  	case anthropic.MessageBatchSucceededResult:
  		fmt.Printf("Success! %s\n", result.CustomID)
  	case anthropic.MessageBatchErroredResult:
  		fmt.Printf("Error: %s - %s\n", result.CustomID, variant.Error.Error.Message)
  	case anthropic.MessageBatchExpiredResult:
  		fmt.Printf("Request expired: %s\n", result.CustomID)
  	}
  }

  if err := stream.Err(); err != nil {
  	log.Fatal(err)
  }
  ```

  ```java Java
  import com.anthropic.core.http.StreamResponse;
  import com.anthropic.models.messages.batches.BatchResultsParams;
  import com.anthropic.models.messages.batches.MessageBatchIndividualResponse;
  // ...
      AnthropicClient client = AnthropicOkHttpClient.fromEnv();

      // 以節省記憶體的區塊串流讀取結果檔案，一次處理一個
      try (
        StreamResponse<MessageBatchIndividualResponse> streamResponse = client
          .messages()
          .batches()
          .resultsStreaming(
            BatchResultsParams.builder()
              .messageBatchId("msgbatch_01HkcTjaV5uDC8jWR4ZsDV8d")
              .build()
          )
      ) {
        streamResponse
          .stream()
          .forEach(result -> {
            switch (result.result().type().value()) {
              case SUCCEEDED -> System.out.println("Success! " + result.customId());
              case ERRORED -> {
                if (result.result().asErrored().error().error().isInvalidRequestError()) {
                  // 重新傳送請求前必須先修正請求主體
                  System.out.println("Validation error: " + result.customId());
                } else {
                  // 可直接重試請求
                  System.out.println("Server error: " + result.customId());
                }
              }
              case EXPIRED -> System.out.println("Request expired: " + result.customId());
            }
          });
      }
  ```

  ```php PHP
  use Anthropic\Messages\Batches\MessageBatchErroredResult;
  use Anthropic\Messages\Batches\MessageBatchExpiredResult;
  use Anthropic\Messages\Batches\MessageBatchSucceededResult;

  $client = new Client();

  foreach ($client->messages->batches->resultsStream(messageBatchID: 'msgbatch_01HkcTjaV5uDC8jWR4ZsDV8d') as $result) {
      switch (true) {
          case $result->result instanceof MessageBatchSucceededResult:
              echo "Success! {$result->customID}\n";
              break;
          case $result->result instanceof MessageBatchErroredResult:
              if ($result->result->error->error->type === "invalid_request_error") {
                  echo "Validation error: {$result->customID}\n";
              } else {
                  echo "Server error: {$result->customID}\n";
              }
              break;
          case $result->result instanceof MessageBatchExpiredResult:
              echo "Request expired: {$result->customID}\n";
              break;
      }
  }
  ```

  ```ruby Ruby
  client = Anthropic::Client.new

  client.messages.batches.results_streaming("msgbatch_01HkcTjaV5uDC8jWR4ZsDV8d").each do |result|
    outcome = result.result
    case outcome
    when Anthropic::Models::Messages::MessageBatchSucceededResult
      puts "Success! #{result.custom_id}"
    when Anthropic::Models::Messages::MessageBatchErroredResult
      if outcome.error.type == :invalid_request
        puts "Validation error: #{result.custom_id}"
      else
        puts "Server error: #{result.custom_id}"
      end
    when Anthropic::Models::Messages::MessageBatchExpiredResult
      puts "Request expired: #{result.custom_id}"
    end
  end
  ```
</CodeGroup>

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

```jsonl .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` 將設為標準的[錯誤結構](https://platform.claude.com/docs/zh-TW/api/errors#error-shapes)。

<Tip>
  **批次結果可能與輸入順序不符**

  批次結果可能以任何順序傳回，且可能與建立批次時的請求順序不符。在前述範例中，第二個批次請求的結果在第一個之前傳回。若要正確地將結果與其對應的請求配對，請務必使用 `custom_id` 欄位。
</Tip>

### 取消 Message Batch

您可以使用[取消端點](https://platform.claude.com/docs/zh-TW/api/messages/batches/cancel)取消目前正在處理的 Message Batch。取消後，批次的 `processing_status` 會立即變為 `canceling`。您可以使用前述相同的輪詢技術等待取消完成。已取消的批次最終狀態為 `ended`，且可能包含取消前已處理之請求的部分結果。

<CodeGroup>
  ```bash cURL
  #!/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"
  ```

  ```bash CLI
  #!/bin/bash
  # ...
  ant messages:batches cancel --message-batch-id "$MESSAGE_BATCH_ID"
  ```

  ```python Python
  client = anthropic.Anthropic()

  MESSAGE_BATCH_ID = "msgbatch_01HkcTjaV5uDC8jWR4ZsDV8d"

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

  ```typescript TypeScript
  const client = new Anthropic();

  const messageBatch = await client.messages.batches.cancel(MESSAGE_BATCH_ID);
  console.log(messageBatch);
  ```

  ```csharp C#
  AnthropicClient client = new();
  string messageBatchId = Environment.GetEnvironmentVariable("MESSAGE_BATCH_ID");

  var messageBatch = await client.Messages.Batches.Cancel(messageBatchId);
  Console.WriteLine(messageBatch);
  ```

  ```go Go
  client := anthropic.NewClient()
  messageBatchID := os.Getenv("MESSAGE_BATCH_ID")

  messageBatch, err := client.Messages.Batches.Cancel(context.TODO(), messageBatchID, anthropic.MessageBatchCancelParams{})
  if err != nil {
  	log.Fatal(err)
  }
  fmt.Println(messageBatch)
  ```

  ```java Java
  import com.anthropic.models.messages.batches.*;
  // ...
      AnthropicClient client = AnthropicOkHttpClient.fromEnv();

      MessageBatch messageBatch = client
        .messages()
        .batches()
        .cancel("msgbatch_01HkcTjaV5uDC8jWR4ZsDV8d");
      System.out.println(messageBatch);
  ```

  ```php PHP
  $client = new Client();

  $messageBatch = $client->messages->batches->cancel(
      messageBatchID: 'msgbatch_example_id',
  );
  echo $messageBatch;
  ```

  ```ruby Ruby
  client = Anthropic::Client.new

  message_batch_id = ENV.fetch("MESSAGE_BATCH_ID")
  message_batch = client.messages.batches.cancel(message_batch_id)
  puts message_batch
  ```
</CodeGroup>

回應顯示批次處於 `canceling` 狀態：

```json 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 支援提示快取，讓您有機會降低批次請求的成本和處理時間。提示快取和 Message Batches 的定價折扣可以疊加，當兩項功能一起使用時可提供更大的成本節省。然而，由於批次請求是以非同步且並行的方式處理，快取命中是以盡力而為的方式提供。使用者通常會體驗到 30% 到 98% 的快取命中率，視其流量模式而定。

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

1. 在批次中的每個 Message 請求中包含相同的 `cache_control` 區塊。
2. 維持穩定的請求流，以防止快取項目在其 5 分鐘的生命週期後過期。
3. 組織您的請求結構，以盡可能共享更多快取內容。

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

<CodeGroup>
  ```bash cURL
  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-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."}
                  ]
              }
          },
          {
              "custom_id": "my-second-request",
              "params": {
                  "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."}
                  ]
              }
          }
      ]
  }'
  ```

  ```bash CLI
  ant messages:batches create <<'YAML'
  requests:
    - custom_id: my-first-request
      params:
        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.
          - 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-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.
          - 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.
  YAML
  ```

  ```python Python
  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.",
                      }
                  ],
              ),
          ),
      ]
  )
  ```

  ```typescript TypeScript
  const client = new Anthropic();

  const messageBatch = await client.messages.batches.create({
    requests: [
      {
        custom_id: "my-first-request",
        params: {
          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." }
          ]
        }
      },
      {
        custom_id: "my-second-request",
        params: {
          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." }]
        }
      }
    ]
  });
  ```

  ```csharp C#
  using Anthropic;
  using Anthropic.Models.Messages;
  using Anthropic.Models.Messages.Batches;

  AnthropicClient client = new()
  {
      ApiKey = Environment.GetEnvironmentVariable("ANTHROPIC_API_KEY")
  };

  var messageBatch = await client.Messages.Batches.Create(new BatchCreateParams
  {
      Requests =
      [
          new()
          {
              CustomID = "my-first-request",
              Params = new()
              {
                  Model = Model.ClaudeOpus5_5,
                  MaxTokens = 1024,
                  System = new List<TextBlockParam>
                  {
                      new()
                      {
                          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"
                      },
                      new()
                      {
                          Text = "<the entire contents of Pride and Prejudice>",
                          CacheControl = new()
                      }
                  },
                  Messages =
                  [
                      new() { Role = Role.User, Content = "Analyze the major themes in Pride and Prejudice." }
                  ]
              }
          },
          new()
          {
              CustomID = "my-second-request",
              Params = new()
              {
                  Model = Model.ClaudeOpus5_5,
                  MaxTokens = 1024,
                  System = new List<TextBlockParam>
                  {
                      new()
                      {
                          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"
                      },
                      new()
                      {
                          Text = "<the entire contents of Pride and Prejudice>",
                          CacheControl = new()
                      }
                  },
                  Messages =
                  [
                      new() { Role = Role.User, Content = "Write a summary of Pride and Prejudice." }
                  ]
              }
          }
      ]
  });
  ```

  ```go Go
  client := anthropic.NewClient()

  messageBatch, err := client.Messages.Batches.New(context.TODO(), anthropic.MessageBatchNewParams{
  	Requests: []anthropic.MessageBatchNewParamsRequest{
  		{
  			CustomID: "my-first-request",
  			Params: anthropic.MessageBatchNewParamsRequestParams{
  				Model:     anthropic.ModelClaudeOpus5_5,
  				MaxTokens: 1024,
  				System: []anthropic.TextBlockParam{
  					{
  						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",
  					},
  					{
  						Text:         "<the entire contents of Pride and Prejudice>",
  						CacheControl: anthropic.NewCacheControlEphemeralParam(),
  					},
  				},
  				Messages: []anthropic.MessageParam{
  					anthropic.NewUserMessage(anthropic.NewTextBlock("Analyze the major themes in Pride and Prejudice.")),
  				},
  			},
  		},
  		{
  			CustomID: "my-second-request",
  			Params: anthropic.MessageBatchNewParamsRequestParams{
  				Model:     anthropic.ModelClaudeOpus5_5,
  				MaxTokens: 1024,
  				System: []anthropic.TextBlockParam{
  					{
  						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",
  					},
  					{
  						Text:         "<the entire contents of Pride and Prejudice>",
  						CacheControl: anthropic.NewCacheControlEphemeralParam(),
  					},
  				},
  				Messages: []anthropic.MessageParam{
  					anthropic.NewUserMessage(anthropic.NewTextBlock("Write a summary of Pride and Prejudice.")),
  				},
  			},
  		},
  	},
  })
  if err != nil {
  	log.Fatal(err)
  }
  fmt.Println(messageBatch)
  ```

  ```java Java
  import com.anthropic.models.messages.CacheControlEphemeral;
  // ...
  import com.anthropic.models.messages.batches.*;
  // ...
      AnthropicClient client = AnthropicOkHttpClient.fromEnv();

      BatchCreateParams createParams = BatchCreateParams.builder()
        .addRequest(
          BatchCreateParams.Request.builder()
            .customId("my-first-request")
            .params(
              BatchCreateParams.Request.Params.builder()
                .model(Model.CLAUDE_OPUS_5_5)
                .maxTokens(1024)
                .systemOfTextBlockParams(
                  List.of(
                    TextBlockParam.builder()
                      .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"
                      )
                      .build(),
                    TextBlockParam.builder()
                      .text("<the entire contents of Pride and Prejudice>")
                      .cacheControl(CacheControlEphemeral.builder().build())
                      .build()
                  )
                )
                .addUserMessage("Analyze the major themes in Pride and Prejudice.")
                .build()
            )
            .build()
        )
        .addRequest(
          BatchCreateParams.Request.builder()
            .customId("my-second-request")
            .params(
              BatchCreateParams.Request.Params.builder()
                .model(Model.CLAUDE_OPUS_5_5)
                .maxTokens(1024)
                .systemOfTextBlockParams(
                  List.of(
                    TextBlockParam.builder()
                      .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"
                      )
                      .build(),
                    TextBlockParam.builder()
                      .text("<the entire contents of Pride and Prejudice>")
                      .cacheControl(CacheControlEphemeral.builder().build())
                      .build()
                  )
                )
                .addUserMessage("Write a summary of Pride and Prejudice.")
                .build()
            )
            .build()
        )
        .build();

      MessageBatch messageBatch = client.messages().batches().create(createParams);
  ```

  ```php PHP
  $client = new Client();

  $messageBatch = $client->messages->batches->create(
      requests: [
          [
              'custom_id' => 'my-first-request',
              'params' => [
                  '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.']
                  ]
              ]
          ],
          [
              'custom_id' => 'my-second-request',
              'params' => [
                  '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.']
                  ]
              ]
          ]
      ],
  );
  ```

  ```ruby Ruby
  client = Anthropic::Client.new

  message_batch = client.messages.batches.create(
    requests: [
      {
        custom_id: "my-first-request",
        params: {
          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." }
          ]
        }
      },
      {
        custom_id: "my-second-request",
        params: {
          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." }
          ]
        }
      }
    ]
  )
  ```
</CodeGroup>

在此範例中，批次中的兩個請求都包含相同的系統訊息以及標記了 `cache_control` 的《傲慢與偏見》全文，以提高快取命中的可能性。

### 伺服器工具與代理迴圈

所有[伺服器工具](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/server-tools)（網頁搜尋、網頁擷取、程式碼執行、MCP 連接器、advisor 以及工具搜尋）皆可在批次請求中運作。批次工作程序執行與同步 Messages API 相同的伺服器端代理迴圈。

由於沒有需要維持的開放連線，批次迴圈在傳回 `stop_reason: "pause_turn"` 之前，**每輪執行的迭代次數**比同步請求更多。如果批次結果傳回 `pause_turn`，表示該輪尚未完成；您可以在後續請求（批次或同步）中提交暫停的 assistant 內容來繼續，方式與 [pause\_turn 接續模式](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/server-tools#the-server-side-loop-and-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` 限制的輸出。

<Note>
  擴展輸出僅在 Message Batches API 上提供，不適用於同步 Messages API。它在 Claude API 和 AWS 上的 Claude Platform 受支援，目前在 Amazon Bedrock、Google Cloud 或 Microsoft Foundry 上不可用。
</Note>

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

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

<CodeGroup>
  ```bash cURL
  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-5-5",
                  "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."}
                  ]
              }
          }
      ]
  }'
  ```

  ```bash CLI
  ant beta:messages:batches create --beta output-300k-2026-03-24 <<'YAML'
  requests:
    - custom_id: long-form-request
      params:
        model: claude-opus-5-5
        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.
  YAML
  ```

  ```python Python
  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)
  ```

  ```typescript TypeScript
  const client = new Anthropic();

  const messageBatch = await client.beta.messages.batches.create({
    betas: ["output-300k-2026-03-24"],
    requests: [
      {
        custom_id: "long-form-request",
        params: {
          model: "claude-opus-5-5",
          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."
            }
          ]
        }
      }
    ]
  });

  console.log(messageBatch);
  ```

  ```csharp C#
  using Anthropic;
  using Anthropic.Models.Beta.Messages;
  using Anthropic.Models.Beta.Messages.Batches;
  using Model = Anthropic.Models.Messages.Model;

  AnthropicClient client = new();

  var batch = await client.Beta.Messages.Batches.Create(new BatchCreateParams
  {
      Betas = ["output-300k-2026-03-24"],
      Requests =
      [
          new()
          {
              CustomID = "long-form-request",
              Params = new()
              {
                  Model = Model.ClaudeOpus5_5,
                  MaxTokens = 300_000,
                  Messages =
                  [
                      new() { Role = Role.User, Content = "Write a comprehensive technical guide to building distributed systems, covering architecture patterns, consistency models, fault tolerance, and operational best practices." }
                  ]
              }
          }
      ]
  });

  Console.WriteLine(batch);
  ```

  ```go Go
  client := anthropic.NewClient()

  batch, err := client.Beta.Messages.Batches.New(context.Background(),
  	anthropic.BetaMessageBatchNewParams{
  		Betas: []anthropic.AnthropicBeta{"output-300k-2026-03-24"},
  		Requests: []anthropic.BetaMessageBatchNewParamsRequest{
  			{
  				CustomID: "long-form-request",
  				Params: anthropic.BetaMessageBatchNewParamsRequestParams{
  					Model:     anthropic.ModelClaudeOpus5_5,
  					MaxTokens: 300_000,
  					Messages: []anthropic.BetaMessageParam{
  						anthropic.NewBetaUserMessage(
  							anthropic.NewBetaTextBlock("Write a comprehensive technical guide to building distributed systems, covering architecture patterns, consistency models, fault tolerance, and operational best practices."),
  						),
  					},
  				},
  			},
  		},
  	})
  if err != nil {
  	panic(err)
  }

  fmt.Println(batch.ID)
  ```

  ```java Java
  import com.anthropic.models.beta.messages.batches.*;

  void main() {
    AnthropicClient client = AnthropicOkHttpClient.fromEnv();

    BatchCreateParams params = BatchCreateParams.builder()
      .addBeta("output-300k-2026-03-24")
      .addRequest(
        BatchCreateParams.Request.builder()
          .customId("long-form-request")
          .params(
            BatchCreateParams.Request.Params.builder()
              .model(Model.CLAUDE_OPUS_5_5)
              .maxTokens(300_000L)
              .addUserMessage("Write a comprehensive technical guide to building distributed systems, covering architecture patterns, consistency models, fault tolerance, and operational best practices.")
              .build()
          )
          .build()
      )
      .build();

    BetaMessageBatch messageBatch = client.beta().messages().batches().create(params);

    IO.println(messageBatch);
  }
  ```

  ```php PHP
  $client = new Client();

  $batch = $client->beta->messages->batches->create(
      betas: ['output-300k-2026-03-24'],
      requests: [
          [
              'custom_id' => 'long-form-request',
              'params' => [
                  '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.']
                  ]
              ]
          ]
      ],
  );

  echo $batch->id;
  ```

  ```ruby Ruby
  client = Anthropic::Client.new

  batch = client.beta.messages.batches.create(
    betas: ["output-300k-2026-03-24"],
    requests: [
      {
        custom_id: "long-form-request",
        params: {
          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." }
          ]
        }
      }
    ]
  )

  puts batch
  ```
</CodeGroup>

### 有效批次處理的最佳實務

若要充分利用 Batches API：

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

### 常見問題疑難排解

若遇到非預期的行為：

* 確認批次請求總大小未超過 256 MB。如果請求大小過大，您可能會收到 413 `request_too_large` 錯誤。
* 檢查批次中的所有請求是否都使用[支援的模型](https://platform.claude.com/docs/zh-TW/build-with-claude/batch-processing#supported-models)。
* 確保批次中的每個請求都有唯一的 `custom_id`。
* 確保距離批次 `created_at`（而非處理 `ended_at`）時間未超過 29 天。若已超過 29 天，結果將無法再檢視。
* 確認批次尚未被取消。

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

## 批次儲存與隱私

* **Workspace 隔離**：批次隔離於其建立所在的 Workspace 內。它們只能由同一 Workspace 中的 API 請求存取，或由有權限在 Console 中檢視 Workspace 批次的使用者存取。

* **結果可用性**：批次結果在批次建立後 29 天內可供使用，提供充足的時間進行擷取和處理。

## 資料保留

批次處理會在批次建立後儲存請求和回應資料最多 29 天。您可以在處理後隨時使用 `DELETE /v1/messages/batches/{batch_id}` 端點刪除訊息批次。若要刪除進行中的批次，請先取消它。非同步處理需要在伺服器端儲存輸入和輸出，直到批次完成並擷取結果為止。

關於所有功能的 ZDR 資格，請參閱 [API 與資料保留](https://platform.claude.com/docs/zh-TW/manage-claude/api-and-data-retention)。

## 常見問題

<AccordionGroup>
  <Accordion title="批次處理需要多長時間？">
    批次處理最多可能需要 24 小時，但許多批次會更快完成。實際處理時間取決於批次大小、目前需求以及您的請求量。批次有可能過期而未在 24 小時內完成。
  </Accordion>

  <Accordion title="Batches API 是否適用於所有模型？">
    請參閱[支援的模型](https://platform.claude.com/docs/zh-TW/build-with-claude/batch-processing#supported-models)以取得支援模型的清單。
  </Accordion>

  <Accordion title="我可以將 Message Batches API 與其他 API 功能一起使用嗎？">
    可以，Message Batches API 支援 Messages API 中幾乎所有可用的功能，包括大多數 beta 功能。少數參數（`stream`、`speed` 和 `max_tokens: 0`）不受支援。請參閱[可以批次處理的內容](https://platform.claude.com/docs/zh-TW/build-with-claude/batch-processing#what-can-be-batched)以取得完整清單。
  </Accordion>

  <Accordion title="Message Batches API 如何影響定價？">
    與標準 API 價格相比，Message Batches API 對所有用量提供 50% 的折扣。這適用於輸入 token、輸出 token 以及任何特殊 token。如需更多定價資訊，請造訪[定價](https://claude.com/pricing#anthropic-api)。
  </Accordion>

  <Accordion title="批次提交後可以更新嗎？">
    不可以，批次一旦提交便無法修改。如果您需要進行變更，應取消目前的批次並提交新的批次。請注意，取消可能不會立即生效。
  </Accordion>

  <Accordion title="Message Batches API 是否有速率限制？它們是否與 Messages API 速率限制互相影響？">
    Message Batches API 除了對需要處理的請求數量有限制外，還有基於 HTTP 請求的速率限制。請參閱 [Message Batches API 速率限制](https://platform.claude.com/docs/zh-TW/api/rate-limits#message-batches-api)。使用 Batches API 不會影響 Messages API 的速率限制。
  </Accordion>

  <Accordion title="如何處理批次請求中的錯誤？">
    當您擷取結果時，每個請求都有一個 `result` 欄位，指出它是 `succeeded`、`errored`、`canceled` 還是 `expired`。對於 `errored` 結果，會提供額外的錯誤資訊。請在 [API 參考文件](https://platform.claude.com/docs/zh-TW/api/messages/batches/create)中檢視錯誤回應物件。
  </Accordion>

  <Accordion title="Message Batches API 如何處理隱私和資料分離？">
    Message Batches API 的設計具備強大的隱私和資料分離措施：

    1. 批次及其結果隔離於其建立所在的 Workspace 內。這表示它們只能由同一 Workspace 中的 API 請求存取。
    2. 批次中的每個請求皆獨立處理，請求之間不會有資料洩漏。
    3. 結果僅在有限時間內（29 天）可用，並遵循 Anthropic 的[資料保留政策](https://support.claude.com/en/articles/7996866-how-long-do-you-store-personal-data)。
    4. 在 Console 中下載批次結果的功能可以在組織層級或依個別 workspace 停用。
  </Accordion>

  <Accordion title="我可以在 Message Batches API 中使用提示快取嗎？">
    可以，Message Batches API 可以搭配提示快取使用。然而，由於非同步批次請求可能以並行且任意順序處理，快取命中是以盡力而為的方式提供。
  </Accordion>
</AccordionGroup>

## 後續步驟

<CardGroup cols={2}>
  <Card title="搜尋結果" icon="magnifying-glass" href="https://platform.claude.com/docs/zh-TW/build-with-claude/search-results">
    透過提供附有來源標註的搜尋結果，為 RAG 應用程式啟用自然引用。
  </Card>

  <Card title="提示快取" icon="database" href="https://platform.claude.com/docs/zh-TW/build-with-claude/prompt-caching">
    透過快取批次中各請求共享的提示前綴，降低成本與延遲。
  </Card>
</CardGroup>
