---
title: バッチ処理
url: https://platform.claude.com/docs/ja/build-with-claude/batch-processing
description: Message Batches APIを使用して大量のMessagesリクエストを非同期で処理し、コストを50パーセント削減してスループットを向上させます。
featureMetadata:
  status: stable
  zdr:
    eligibility: not-eligible
    note: 29日間保持。非同期ストレージが必要です。
  supportedModels:
    - 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」（バッチ処理）は、大量のリクエストを効率的に処理するための強力なアプローチです。リクエストを1つずつ処理して即座にレスポンスを受け取る代わりに、バッチ処理では複数のリクエストをまとめて送信し、非同期で処理できます。このパターンは特に次のような場合に役立ちます。

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

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

# 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リクエストを含む新しいメッセージバッチを作成します。
2. その後、バッチは非同期で処理され、各リクエストは独立して処理されます。
3. バッチのステータスをポーリングし、すべてのリクエストの処理が終了したら結果を取得できます。

これは、即座の結果を必要としない一括操作に特に役立ちます。例えば次のようなものです。

* 大規模な評価：数千のテストケースを効率的に処理します。
* コンテンツモデレーション：大量のユーザー生成コンテンツを非同期で分析します。
* データ分析：大規模なデータセットのインサイトや要約を生成します。
* 一括コンテンツ生成：さまざまな目的のために大量のテキストを作成します（例：商品説明、記事の要約）。

### バッチの制限

* メッセージバッチは、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/ja/api/rate-limits#message-batches-api)を参照してください。さらに、現在の需要とリクエスト量に応じて処理が遅くなる場合があります。その場合、24時間後に期限切れになるリクエストが増える可能性があります。
* 高スループットと並行処理のため、バッチはClaude Consoleでワークスペースに設定された[支出上限](https://platform.claude.com/settings/billing)をわずかに超える場合があります。
* バッチ化された各リクエストの[`max_tokens`](https://platform.claude.com/docs/ja/api/messages/create#create.max_tokens)は`1`以上である必要があります。`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コネクタ、アドバイザー、ツール検索）を含む）
* システムメッセージ
* マルチターン会話
* 拡張思考
* ほとんどのベータ機能

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

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

| パラメータ                                                                                                                           | 理由                                                                                                                                                                                        |
| ------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `stream: true`                                                                                                                  | バッチの結果はストリームではなく、単一のファイルとして返されます。                                                                                                                                                         |
| `speed`（[高速モード](https://platform.claude.com/docs/ja/build-with-claude/fast-mode)）                                               | 高速モードは同期処理のレイテンシを調整するものであり、非同期のバッチ処理には適用されません。                                                                                                                                            |
| `fallbacks`（[サーバーサイドフォールバック](https://platform.claude.com/docs/ja/build-with-claude/refusals-and-fallback#server-side-fallback)） | サーバーサイドフォールバックはバッチには適用されません。拒否されたリクエストを再試行するには、[Message Batchesにおける拒否](https://platform.claude.com/docs/ja/build-with-claude/refusals-and-fallback#refusals-in-message-batches)を参照してください。 |
| `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 Claude Models on Google Cloud (Google managed) and Bedrock](https://platform.claude.com/docs/ja/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/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 Claude Models on Google Cloud (Google managed) and Bedrock](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  |

* **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を作成するリクエストのリストで構成されます。個々のリクエストの構造は次のとおりです。

* Messagesリクエストを識別するための一意の[`custom_id`](https://platform.claude.com/docs/ja/api/messages/batches/create#create.requests.custom_id)。1〜64文字で、英数字、ハイフン、アンダースコアのみを含む必要があります（`^[a-zA-Z0-9_-]{1,64}$`に一致）。
* 標準の[Messages API](https://platform.claude.com/docs/ja/api/messages/create)パラメータを含む[`params`](https://platform.claude.com/docs/ja/api/messages/batches/create#create.requests.params)オブジェクト

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

この例では、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
}
```

### バッチの追跡

メッセージバッチの[`processing_status`](https://platform.claude.com/docs/ja/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/ja/api/messages/batches/retrieve).)

#### メッセージバッチの完了をポーリングする

メッセージバッチをポーリングするには、その`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>

### すべてのメッセージバッチを一覧表示する

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

<CodeGroup>
  ```bash cURL
  # 1ページを取得します。レスポンスの 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リクエストには結果が存在します。結果の種類は4つあります。

| 結果の種類       | 説明                                                                                     |
| ----------- | -------------------------------------------------------------------------------------- |
| `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/ja/api/messages/batches/retrieve#message_batch.request_counts).)

バッチの結果は、メッセージバッチの[`results_url`](https://platform.claude.com/docs/ja/api/messages/batches/retrieve#message_batch.results_url)プロパティからダウンロードでき、組織の権限で許可されている場合はConsoleからもダウンロードできます。結果のサイズが大きくなる可能性があるため、一度にすべてをダウンロードするのではなく、[結果をストリーミング](https://platform.claude.com/docs/ja/api/messages/batches/results)で取得することをお勧めします。

<CodeGroup>
  ```bash cURL
  # バッチの .jsonl 結果をストリーミングします。1行に1件の結果が含まれます。
  # 結果ごとの処理（リトライ、検証エラーなど）には 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
  # 1行に1つの結果を出力します。例: `{"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()

  # 結果ファイルをメモリ効率の良いチャンクでストリーミングし、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.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();

          // 結果ファイルをメモリ効率の良いチャンク単位でストリーミングし、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.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オブジェクトです。ストリーミングされた各結果について、その`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)に設定されます。

バッチの結果には、バッチを作成したリクエストのAPIバージョンが使用されます。

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

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

### メッセージバッチのキャンセル

[キャンセルエンドポイント](https://platform.claude.com/docs/ja/api/messages/batches/cancel)を使用して、現在処理中のメッセージバッチをキャンセルできます。キャンセル直後、バッチの`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/ja/agents-and-tools/tool-use/server-tools)（ウェブ検索、ウェブフェッチ、コード実行、MCPコネクタ、アドバイザー、ツール検索）はバッチリクエストで動作します。バッチワーカーは、同期のMessages APIと同じサーバーサイドのエージェントループを実行します。

維持すべきオープンな接続がないため、バッチループは`stop_reason: "pause_turn"`を返す前に、同期リクエストよりも**1ターン内でより多くの反復**を実行できます。バッチの結果が`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に引き上げます。このヘッダーを含めることで、標準の128kの`max_tokens`制限をはるかに超える出力を1ターンで生成できます。

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

拡張出力は、書籍並みの長さの草稿や技術文書などの長文生成、網羅的な構造化データ抽出、大規模なコード生成の足場づくり、長い推論チェーンなどに使用してください。

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

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

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

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

* **結果の利用可能性：** バッチの結果はバッチ作成後29日間利用でき、取得と処理のための十分な時間が確保されています。

## よくある質問

<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`、`fallbacks`、および`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. バッチとその結果は、作成されたワークスペース内で分離されます。つまり、同じワークスペース内の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/ja/build-with-claude/working-with-messages)

* 利用可能状況：利用可能

| ステータス | クラウドプラットフォーム                                                                                                                                                                                                                                                                   |
| ----- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| 利用可能  | Claude API, [Claude Platform on AWS](https://platform.claude.com/docs/ja/build-with-claude/claude-platform-on-aws), [Claude Models on Google Cloud (Anthropic managed)](https://platform.claude.com/docs/ja/build-with-claude/claude-models-on-google-cloud/anthropic-managed) |

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

* 利用可能状況：利用不可

### データの取り扱い

[データの取り扱いの概要](https://platform.claude.com/docs/ja/manage-claude/api-and-data-retention#feature-eligibility)

| 項目    | ゼロデータ保持                                                                                                               | HIPAA |
| ----- | --------------------------------------------------------------------------------------------------------------------- | ----- |
| ステータス | 対象外                                                                                                                   | 対象外   |
| 詳細    | 29日間保持。非同期ストレージが必要です。 [詳細はこちら](https://platform.claude.com/docs/ja/build-with-claude/batch-processing#data-retention) | —     |

対象エンドポイント：

* `/v1/messages/batches`

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

## 次のステップ

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