---
title: 批次處理
url: https://platform.claude.com/docs/zh-TW/build-with-claude/batch-processing
description: 使用 Message Batches API 以非同步方式處理大量 Messages 請求，將成本降低 50% 並提高吞吐量。
featureMetadata:
  status: stable
  zdr:
    eligibility: not-eligible
    note: 保留 29 天；需要非同步儲存。
  supportedModels:
    - claude-fable-5-2
    - claude-mythos-5-2
    - claude-fable-5-1
    - claude-mythos-5-1
    - claude-fable-5
    - claude-mythos-5
    - claude-mythos-preview
    - claude-opus-5-5
    - claude-opus-5
    - claude-sonnet-5-5
    - claude-sonnet-5
    - claude-haiku-5-5
    - claude-haiku-4-5-20251001
    - claude-opus-4-8
    - claude-opus-4-7
    - claude-opus-4-6
    - claude-sonnet-4-6
    - claude-opus-4-5-20251101
    - claude-sonnet-4-5-20250929
  supportedPlatforms:
    Claude API: stable
    Claude Platform on AWS: stable
    Claude Models on Google Cloud (Anthropic managed): stable
---

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

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

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

# Message Batches API

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

除了本指南之外，您也可以[直接查閱 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 天內可供使用。之後，您仍然可以檢視該批次，但其結果將無法再下載。
* 批次的範圍限定於 Claude Console 中的[工作區](https://platform.claude.com/settings/workspaces)。您可以檢視在您的請求所執行的工作區內建立的所有批次（及其結果）。
* 「Rate limit」（速率限制）同時適用於 Batches API HTTP 請求以及批次中等待處理的請求數量。請參閱 [Message Batches API 速率限制](https://platform.claude.com/docs/zh-TW/api/rate-limits#message-batches-api)。此外，處理速度可能會根據目前需求和您的請求量而減慢。在這種情況下，您可能會看到更多請求在 24 小時後過期。
* 由於高吞吐量和並行處理，批次可能會略微超過您在 Claude Console 中為工作區設定的[支出限制](https://platform.claude.com/settings/billing)。
* 每個批次請求的 [`max_tokens`](https://platform.claude.com/docs/zh-TW/api/messages/create#create.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 連接器、顧問和工具搜尋）
* 系統訊息
* 多輪對話
* 「Extended thinking」（擴展思考）
* 大多數 beta 功能

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

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

| 參數                                                                                                                         | 原因                                                                                                                                                              |
| -------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `stream: true`                                                                                                             | 批次結果以單一檔案傳回，而非串流。                                                                                                                                               |
| `speed`（[快速模式](https://platform.claude.com/docs/zh-TW/build-with-claude/fast-mode)）                                        | 快速模式調整的是同步延遲，這不適用於非同步批次處理。                                                                                                                                      |
| `fallbacks`（[伺服器端備援](https://platform.claude.com/docs/zh-TW/build-with-claude/refusals-and-fallback#server-side-fallback)） | 伺服器端備援不適用於批次。若要重試被拒絕的請求，請參閱 [Message Batches 中的拒絕](https://platform.claude.com/docs/zh-TW/build-with-claude/refusals-and-fallback#refusals-in-message-batches)。 |
| `max_tokens: 0`                                                                                                            | 請參閱[批次限制](https://platform.claude.com/docs/zh-TW/build-with-claude/batch-processing#batch-limitations)。                                                         |

<Tip>
  由於批次處理可能需要超過 5 分鐘，在處理具有共用上下文的批次時，請考慮搭配提示快取使用 [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.2                                                                                                                                                          | $4 / MTok    | $20 / MTok    |
| Claude Mythos 5.2 ([limited availability](https://support.claude.com/en/articles/14604842))                                                                               | $4 / MTok    | $20 / MTok    |
| 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 Claude Models on Google Cloud (Google managed) and Bedrock](https://platform.claude.com/docs/zh-TW/about-claude/model-deprecations)) | $7.50 / MTok | $37.50 / MTok |
| Claude Opus 4 ([retired, except on Claude Models on Google Cloud (Google managed)](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 Claude Models on Google Cloud (Google managed) and Bedrock](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  |

* **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`](https://platform.claude.com/docs/zh-TW/api/messages/batches/create#create.requests.custom_id)。長度必須為 1 到 64 個字元，且只能包含英數字元、連字號和底線（符合 `^[a-zA-Z0-9_-]{1,64}$`）。
* 包含標準 [Messages API](https://platform.claude.com/docs/zh-TW/api/messages/create) 參數的 [`params`](https://platform.claude.com/docs/zh-TW/api/messages/batches/create#create.requests.params) 物件

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

<CodeGroup>
  ```bash cURL
  curl https://api.anthropic.com/v1/messages/batches \
    -H "x-api-key: $ANTHROPIC_API_KEY" \
    -H "anthropic-version: 2026-10-21" \
    -H "content-type: application/json" \
    -d '{
      "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 UserMessageParam { Content = "Hello, world" }]
              }
          },
          new()
          {
              CustomID = "my-second-request",
              Params = new()
              {
                  Model = Model.ClaudeOpus5_5,
                  MaxTokens = 1024,
                  Messages = [new UserMessageParam { 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: Anthropic::Model::CLAUDE_OPUS_5_5,
          max_tokens: 1024,
          messages: [
            { role: "user", content: "Hello, world" }
          ]
        }
      },
      {
        custom_id: "my-second-request",
        params: {
          model: Anthropic::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`](https://platform.claude.com/docs/zh-TW/api/messages/batches/retrieve#message_batch.processing_status) 欄位表示批次目前所處的處理階段。它一開始為 `in_progress`，然後在批次中的所有請求都完成處理且結果準備就緒後更新為 `ended`。您可以造訪 [Console](https://platform.claude.com/settings/workspaces/default/batches) 或使用擷取端點來監控批次的狀態。

(See the `messages/batches/retrieve` method in [the API reference](https://platform.claude.com/docs/zh-TW/api/messages/batches/retrieve).)

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

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

<CodeGroup>
  ```bash cURL
  # 檢查狀態；重複執行直到 processing_status 為 "ended"
  curl "https://api.anthropic.com/v1/messages/batches/$MESSAGE_BATCH_ID" \
    -H "x-api-key: $ANTHROPIC_API_KEY" \
    -H "anthropic-version: 2026-10-21"
  ```

  ```bash CLI
  # 檢查狀態；重複執行直到 processing_status 為 "ended"
  ant messages:batches retrieve --message-batch-id "$MESSAGE_BATCH_ID"
  ```

  ```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)列出工作區中的所有 Message Batches。此 API 支援分頁，會視需要自動擷取其他頁面：

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

  ```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` 物件會計算仍在處理中的請求，以及各結果類型的請求數量。

(See `message_batch.request_counts` on `messages/batches/retrieve` in [the API reference](https://platform.claude.com/docs/zh-TW/api/messages/batches/retrieve#message_batch.request_counts).)

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

<CodeGroup>
  ```bash cURL
  # 串流傳輸批次的 .jsonl 結果，每行一筆結果。
  # 若需逐筆處理結果（重試、驗證錯誤），請使用 Claude SDK。
  curl "https://api.anthropic.com/v1/messages/batches/msgbatch_01HkcTjaV5uDC8jWR4ZsDV8d/results" \
    -H "anthropic-version: 2026-10-21" \
    -H "x-api-key: $ANTHROPIC_API_KEY"
  ```

  ```bash CLI
  # 每行印出一筆結果，例如 `{"custom_id":"test-1","result":{"type":"succeeded",…}}`。
  # 若要逐筆處理結果（重試、驗證錯誤），請使用其他分頁中的 Claude SDK
  # 範例。
  ant messages:batches results \
    --message-batch-id msgbatch_01HkcTjaV5uDC8jWR4ZsDV8d \
    --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.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.Raw())
      {
          case "succeeded":
              Console.WriteLine($"Success! {result.CustomID}");
              break;
          case "errored":
              if (result.Result.TryPickErrored(out var errored)
                  && errored.Error.Error.Type.Raw() == "invalid_request_error")
              {
                  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.error.type == :invalid_request_error
        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)。

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

<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
  curl -X POST https://api.anthropic.com/v1/messages/batches/$MESSAGE_BATCH_ID/cancel \
    -H "x-api-key: $ANTHROPIC_API_KEY" \
    -H "anthropic-version: 2026-10-21"
  ```

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

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

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

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

<CodeGroup>
  ```bash cURL
  curl https://api.anthropic.com/v1/messages/batches \
    -H "x-api-key: $ANTHROPIC_API_KEY" \
    -H "anthropic-version: 2026-10-21" \
    -H "content-type: application/json" \
    -d '{
      "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 UserMessageParam { 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 UserMessageParam { 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: Anthropic::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: Anthropic::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 連接器、顧問和工具搜尋）都可在批次請求中運作。批次工作程序執行的伺服器端「agentic loop」（代理迴圈）與同步 Messages API 相同。

由於不需要維持開啟的連線，批次迴圈在傳回 `stop_reason: "pause_turn"` 之前，**在一個回合中可以執行比同步請求更多的迭代**。如果批次結果以 `pause_turn` 傳回，表示該回合未完成；您可以在後續請求（批次或同步）中提交暫停的助理內容來繼續該回合，方式完全如 [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 和 Claude Platform on AWS 上受支援，目前無法在 Amazon Bedrock、Claude Models on Google Cloud (Google managed) 或 Microsoft Foundry 上使用。
</Note>

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

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

<CodeGroup>
  ```bash cURL
  curl https://api.anthropic.com/v1/messages/batches \
    -H "x-api-key: $ANTHROPIC_API_KEY" \
    -H "anthropic-version: 2026-10-21" \
    -H "anthropic-beta: output-300k-2026-03-24" \
    -H "content-type: application/json" \
    -d '{
      "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 BetaUserMessageParam { 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: Anthropic::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 天，將無法再檢視結果。
* 確認批次未被取消。

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

## 批次儲存與隱私

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

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

## 常見問題

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

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

## 可用性

批次處理在所有模型上可供使用。

### API 支援

#### [Messages API](https://platform.claude.com/docs/zh-TW/build-with-claude/working-with-messages)

* 可用性：可用

| 狀態 | 雲端平台                                                                                                                                                                                                                                                                                 |
| -- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| 可用 | Claude API, [Claude Platform on AWS](https://platform.claude.com/docs/zh-TW/build-with-claude/claude-platform-on-aws), [Claude Models on Google Cloud (Anthropic managed)](https://platform.claude.com/docs/zh-TW/build-with-claude/claude-models-on-google-cloud/anthropic-managed) |

#### [Managed Agents](https://platform.claude.com/docs/zh-TW/managed-agents/overview)

* 可用性：不可用

### 資料處理

[資料處理概覽](https://platform.claude.com/docs/zh-TW/manage-claude/api-and-data-retention#feature-eligibility)

| 項目   | 零資料保留                                                                                                             | HIPAA |
| ---- | ----------------------------------------------------------------------------------------------------------------- | ----- |
| 狀態   | 不符合資格                                                                                                             | 不符合資格 |
| 詳細資訊 | 保留 29 天；需要非同步儲存。 [深入了解](https://platform.claude.com/docs/zh-TW/build-with-claude/batch-processing#data-retention) | —     |

適用端點：

* `/v1/messages/batches`

批次處理會在批次建立後儲存請求和回應資料最長 29 天。處理完成後，您可以隨時使用 [`DELETE /v1/messages/batches/{batch_id}`](https://platform.claude.com/docs/zh-TW/api/messages/batches/delete) 端點刪除訊息批次。若要刪除處理中的批次，請先將其取消。非同步處理需要在伺服器端儲存輸入和輸出，直到批次完成並擷取結果為止。

## 後續步驟

<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>
