---
title: バッチ処理
url: https://platform.claude.com/docs/ja/build-with-claude/batch-processing
description: Message Batches APIを使用して大量のMessagesリクエストを非同期で処理し、コストを50%削減してスループットを向上させます。
---

バッチ処理は、大量のリクエストを効率的に処理するための強力なアプローチです。リクエストを1つずつ即座に応答しながら処理する代わりに、バッチ処理では複数のリクエストをまとめて送信し、非同期で処理できます。このパターンは特に以下の場合に有用です。

* 大量のデータを処理する必要がある場合
* 即座の応答が不要な場合
* コスト効率を最適化したい場合
* 大規模な評価や分析を実行している場合

Message Batches APIは、このパターンのAnthropicによる最初の実装です。

<Note>
  「zero data retention」（ゼロデータ保持）、すなわちZDRがこの機能にどのように適用されるかについては、[APIとデータ保持](https://platform.claude.com/docs/ja/manage-claude/api-and-data-retention)を参照してください。
</Note>

# Message Batches API

Message Batches APIは、大量の[Messages](https://platform.claude.com/docs/ja/api/messages/create)リクエストを非同期で処理するための強力でコスト効率の高い方法です。このアプローチは即座の応答を必要としないタスクに適しており、ほとんどのバッチは1時間未満で完了し、コストを50%削減してスループットを向上させます。

このガイドに加えて、[APIリファレンスを直接確認する](https://platform.claude.com/docs/ja/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内で作成されたすべてのバッチ（およびその結果）を表示できます。
* レート制限は、Batches APIのHTTPリクエストと、処理待ちのバッチ内のリクエスト数の両方に適用されます。[Message Batches APIのレート制限](https://platform.claude.com/docs/ja/api/rate-limits#message-batches-api)を参照してください。さらに、現在の需要とリクエスト量に基づいて処理が遅くなる場合があります。その場合、24時間後に期限切れになるリクエストが増える可能性があります。
* 高いスループットと並行処理のため、バッチはWorkspaceで設定された[支出制限](https://platform.claude.com/settings/billing)をわずかに超える場合があります。
* 各バッチリクエストには、少なくとも`1`の`max_tokens`が必要です。`max_tokens: 0`（[キャッシュの事前ウォーミング](https://platform.claude.com/docs/ja/build-with-claude/prompt-caching#pre-warming-the-cache)）はバッチ内ではサポートされていません。これは、バッチ処理中に書き込まれた一時的なキャッシュエントリが、後続のリクエストが実行される前に期限切れになる可能性が高いためです。

### サポートされているモデル

すべての[アクティブなモデル](https://platform.claude.com/docs/ja/models/overview)がMessage Batches APIをサポートしています。

### バッチ処理できるもの

Messages APIに対して行えるほぼすべてのリクエストをバッチに含めることができます。これには以下が含まれます。

* ビジョン
* すべての[サーバーツール](https://platform.claude.com/docs/ja/agents-and-tools/tool-use/server-tools)（ウェブ検索、ウェブフェッチ、コード実行、MCPコネクタ、アドバイザー、ツール検索）を含むツール使用
* システムメッセージ
* マルチターン会話
* 拡張思考
* ほとんどのベータ機能

バッチ内の各リクエストは独立して処理されるため、単一のバッチ内で異なるタイプのリクエストを混在させることができます。

少数のMessages APIパラメータは、バッチリクエストで**サポートされていません**。これらのいずれかを含めると、検証エラーが返されます。

| パラメータ                                                                                 | 理由                                                                                                             |
| ------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- |
| `stream: true`                                                                        | バッチの結果はストリームではなく、単一のファイルとして返されます。                                                                              |
| `speed`（[Fast mode](https://platform.claude.com/docs/ja/build-with-claude/fast-mode)） | Fast modeは同期処理のレイテンシを調整するものであり、非同期のバッチ処理には適用されません。                                                             |
| `max_tokens: 0`                                                                       | [バッチの制限事項](https://platform.claude.com/docs/ja/build-with-claude/batch-processing#batch-limitations)を参照してください。 |

<Tip>
  バッチの処理には5分以上かかる場合があるため、共有コンテキストを持つバッチを処理する際のキャッシュヒット率を向上させるために、プロンプトキャッシングで[1時間のキャッシュ期間](https://platform.claude.com/docs/ja/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/ja/about-claude/model-deprecations)) | $7.50 / MTok | $37.50 / MTok |
| Claude Opus 4 ([retired, except on Google Cloud](https://platform.claude.com/docs/ja/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/ja/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/ja/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/ja/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/ja/api/messages/create)パラメータを持つ`params`オブジェクト

このリストを`requests`パラメータに渡すことで、[バッチを作成](https://platform.claude.com/docs/ja/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>

この例では、2つの別々のリクエストが非同期処理のためにまとめてバッチ化されています。各リクエストには一意の`custom_id`があり、Messages API呼び出しで使用する標準パラメータが含まれています。

<Tip>
  **Messages APIでバッチリクエストをテストする**

  各メッセージリクエストの`params`オブジェクトの検証は非同期で実行され、検証エラーはバッチ全体の処理が終了したときに返されます。最初に[Messages API](https://platform.claude.com/docs/ja/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/ja/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 Batchのリスト表示

[リストエンドポイント](https://platform.claude.com/docs/ja/api/messages/batches/list)を使用して、Workspace内のすべてのMessage Batchをリスト表示できます。APIはページネーションをサポートしており、必要に応じて追加のページを自動的に取得します。

<CodeGroup>
  ```bash cURL
  #!/bin/sh
  # 1ページを取得します。レスポンスの 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リクエストには結果があります。4つの結果タイプがあります。

| 結果タイプ       | 説明                                                                                     |
| ----------- | -------------------------------------------------------------------------------------- |
| `succeeded` | リクエストが成功しました。メッセージ結果が含まれます。                                                            |
| `errored`   | リクエストでエラーが発生し、メッセージが作成されませんでした。考えられるエラーには、無効なリクエストや内部サーバーエラーが含まれます。これらのリクエストには課金されません。 |
| `canceled`  | このリクエストがモデルに送信される前に、ユーザーがバッチをキャンセルしました。これらのリクエストには課金されません。                             |
| `expired`   | このリクエストがモデルに送信される前に、バッチが24時間の有効期限に達しました。これらのリクエストには課金されません。                            |

バッチの`request_counts`は結果の概要を示し、これら4つの状態のそれぞれに到達したリクエストの数を示します。

バッチの結果は、Message Batchの`results_url`プロパティでダウンロードでき、組織の権限が許可する場合はConsoleでも利用できます。結果のサイズが大きくなる可能性があるため、一度にすべてをダウンロードするのではなく、[結果をストリーミング](https://platform.claude.com/docs/ja/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
  # 結果ごとに1行を出力します。例: `{"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()

  # 結果ファイルをメモリ効率の良いチャンク単位でストリーミングし、1つずつ処理します
  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();

  // 結果ファイルをメモリ効率の良いチャンクでストリーミングし、一度に1つずつ処理します
  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();

      // 結果ファイルをメモリ効率の良いチャンク単位でストリーミングし、1つずつ処理します
      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`形式で、各行はMessage Batch内の単一リクエストの結果を表す有効なJSONオブジェクトです。ストリーミングされた各結果について、その`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/ja/api/errors#error-shapes)に設定されます。

<Tip>
  **バッチ結果は入力順序と一致しない場合があります**

  バッチ結果は任意の順序で返される可能性があり、バッチ作成時のリクエストの順序と一致しない場合があります。前述の例では、2番目のバッチリクエストの結果が最初のものより前に返されています。結果を対応するリクエストと正しく一致させるには、常に`custom_id`フィールドを使用してください。
</Tip>

### Message Batchのキャンセル

[キャンセルエンドポイント](https://platform.claude.com/docs/ja/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 Batchでのプロンプトキャッシングの使用

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/ja/agents-and-tools/tool-use/server-tools)（ウェブ検索、ウェブフェッチ、コード実行、MCPコネクタ、アドバイザー、ツール検索）はバッチリクエストで動作します。バッチワーカーは、同期Messages APIと同じサーバーサイドのエージェントループを実行します。

維持すべきオープン接続がないため、バッチループは`stop_reason: "pause_turn"`を返す前に、同期リクエストよりも**ターンあたりより多くの反復**を実行します。バッチ結果が`pause_turn`で返された場合、ターンは完了していません。[pause\_turn継続パターン](https://platform.claude.com/docs/ja/agents-and-tools/tool-use/server-tools#the-server-side-loop-and-pause-turn)に示されているとおり、一時停止されたアシスタントコンテンツを後続のリクエスト（バッチまたは同期）で送信することで継続できます。

バッチワーカーはさらに、高度に並行したバッチ処理が組織のウェブ検索レート制限を使い果たさないように、組織ごとに`web_search`をスロットリングします。バッチはスロットリングされたリクエストを自動的に再試行します。これを自分で処理する必要はありませんが、非常に大きなウェブ検索バッチは完了までに時間がかかる場合があります。

### 拡張出力（ベータ）

`output-300k-2026-03-24`ベータヘッダーは、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に引き上げます。このヘッダーを含めると、1回のターンで標準の128kの`max_tokens`制限をはるかに超える長さの出力を生成できます。

<Note>
  拡張出力はMessage Batches APIでのみ利用可能で、同期Messages APIでは利用できません。Claude APIおよびAWS上のClaude Platformでサポートされており、現在Amazon Bedrock、Google Cloud、またはMicrosoft Foundryでは利用できません。
</Note>

書籍の長さの草稿や技術文書、網羅的な構造化データ抽出、大規模なコード生成スキャフォールド、長い推論チェーンなどの長文生成に拡張出力を使用してください。

単一の300kトークン生成は完了までに1時間以上かかる場合があるため、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/ja/build-with-claude/batch-processing#supported-models)を使用していることを確認します。
* バッチ内の各リクエストに一意の`custom_id`があることを確認します。
* バッチの`created_at`（処理の`ended_at`ではない）時刻から29日未満であることを確認します。29日以上経過している場合、結果は表示できなくなります。
* バッチがキャンセルされていないことを確認します。

バッチ内の1つのリクエストの失敗は、他のリクエストの処理に影響しないことに注意してください。

## バッチのストレージとプライバシー

* **Workspaceの分離**: バッチは作成されたWorkspace内で分離されます。同じWorkspace内のAPIリクエスト、またはConsoleでWorkspaceバッチを表示する権限を持つユーザーのみがアクセスできます。

* **結果の利用可能性**: バッチ結果はバッチ作成後29日間利用可能で、取得と処理に十分な時間を確保できます。

## データ保持

バッチ処理は、バッチ作成後最大29日間、リクエストとレスポンスのデータを保存します。処理後はいつでも`DELETE /v1/messages/batches/{batch_id}`エンドポイントを使用してメッセージバッチを削除できます。処理中のバッチを削除するには、まずキャンセルしてください。非同期処理では、バッチの完了と結果の取得まで、入力と出力の両方をサーバーサイドで保存する必要があります。

すべての機能にわたるZDR適格性については、[APIとデータ保持](https://platform.claude.com/docs/ja/manage-claude/api-and-data-retention)を参照してください。

## よくある質問

<AccordionGroup>
  <Accordion title="バッチの処理にはどのくらい時間がかかりますか？">
    バッチの処理には最大24時間かかる場合がありますが、多くはそれより早く完了します。実際の処理時間は、バッチのサイズ、現在の需要、およびリクエスト量によって異なります。バッチが期限切れになり、24時間以内に完了しない可能性があります。
  </Accordion>

  <Accordion title="Batches APIはすべてのモデルで利用できますか？">
    サポートされているモデルのリストについては、[サポートされているモデル](https://platform.claude.com/docs/ja/build-with-claude/batch-processing#supported-models)を参照してください。
  </Accordion>

  <Accordion title="Message Batches APIを他のAPI機能と一緒に使用できますか？">
    はい、Message Batches APIは、ほとんどのベータ機能を含め、Messages APIで利用可能なほぼすべての機能をサポートしています。少数のパラメータ（`stream`、`speed`、`max_tokens: 0`）はサポートされていません。完全な一覧については、[バッチ処理できるもの](https://platform.claude.com/docs/ja/build-with-claude/batch-processing#what-can-be-batched)を参照してください。
  </Accordion>

  <Accordion title="Message Batches APIは料金にどのように影響しますか？">
    Message Batches APIは、標準API価格と比較してすべての使用量に50%の割引を提供します。これは入力トークン、出力トークン、および特別なトークンに適用されます。料金の詳細については、[料金](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/ja/api/rate-limits#message-batches-api)を参照してください。Batches APIの使用は、Messages APIのレート制限に影響しません。
  </Accordion>

  <Accordion title="バッチリクエストのエラーをどのように処理しますか？">
    結果を取得すると、各リクエストには`succeeded`、`errored`、`canceled`、または`expired`のいずれかを示す`result`フィールドがあります。`errored`の結果については、追加のエラー情報が提供されます。[APIリファレンス](https://platform.claude.com/docs/ja/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/ja/build-with-claude/search-results">
    ソース帰属を伴う検索結果を提供することで、RAGアプリケーションの自然な引用を有効にします。
  </Card>

  <Card title="プロンプトキャッシング" icon="database" href="https://platform.claude.com/docs/ja/build-with-claude/prompt-caching">
    バッチ内のリクエスト間で共有されるプロンプトプレフィックスをキャッシュすることで、コストとレイテンシを削減します。
  </Card>
</CardGroup>
