---
title: プロンプトキャッシング
url: https://platform.claude.com/docs/ja/build-with-claude/prompt-caching
description: "`cache_control` を使用してプロンプトのプレフィックスをキャッシュし、自動キャッシングまたは5分もしくは1時間のTTLを持つ明示的なブレークポイントによって、コストとレイテンシを削減します。"
featureMetadata:
  zdr:
    eligibility: eligible
    note: Excludes [Covered Models](https://platform.claude.com/docs/en/manage-claude/api-and-data-retention#model-specific-data-retention-requirements). プロンプトとClaudeの出力は保存されません。KVキャッシュ表現と暗号学的ハッシュはキャッシュのTTLの間メモリに保持され、期限切れ後すみやかに削除されます。
  supportedModels:
    - claude-fable-5-2
    - claude-mythos-5-2
    - claude-fable-5-1
    - claude-mythos-5-1
    - claude-fable-5
    - claude-mythos-5
    - claude-mythos-preview
    - claude-opus-5-5
    - claude-opus-5
    - claude-sonnet-5-5
    - claude-sonnet-5
    - claude-haiku-5-5
    - claude-haiku-4-5-20251001
    - claude-opus-4-8
    - claude-opus-4-7
    - claude-opus-4-6
    - claude-sonnet-4-6
    - claude-opus-4-5-20251101
    - claude-sonnet-4-5-20250929
  supportedPlatforms:
    Claude API: stable
    Claude Platform on AWS: stable
    Claude Models on Google Cloud (Anthropic managed): stable
    Amazon Bedrock: stable
    Amazon Bedrock (InvokeModel): stable
    Claude Models on Google Cloud (Google managed): stable
    Microsoft Foundry: stable
---

**APIサポート**：使用方法は製品によって異なります。

* **Messages API**：トップレベルまたはブロックで`cache_control`を指定して有効にします。
* **Managed Agents**：常時有効。キャッシュエントリの有効期間はデフォルトで5分で、キャッシュの読み取りと書き込みはセッションの使用量に表示されます。

「prompt caching」（プロンプトキャッシング）は、API がプロンプト内の特定のプレフィックスから処理を再開できるようにすることで、API の使用を最適化します。これにより、反復的なタスクや一貫した要素を含むプロンプトの処理時間とコストが大幅に削減されます。

プロンプトキャッシングを有効にするには、2つの方法があります。

* **[自動キャッシング](https://platform.claude.com/docs/ja/build-with-claude/prompt-caching#automatic-caching)：** リクエストのトップレベルに単一の `cache_control` フィールドを追加します。システムは最後のキャッシュ可能なブロックに自動的にキャッシュブレークポイントを適用し、会話が長くなるにつれてそれを前方に移動させます。増え続けるメッセージ履歴を自動的にキャッシュしたいマルチターンの会話に最適です。
* **[明示的なキャッシュブレークポイント](https://platform.claude.com/docs/ja/build-with-claude/prompt-caching#explicit-cache-breakpoints)：** 個々のコンテンツブロックに直接 `cache_control` を配置し、キャッシュする内容をきめ細かく制御します。

最も簡単な始め方は自動キャッシングです。

<CodeGroup>
  ```bash cURL
  curl https://api.anthropic.com/v1/messages \
    -H "content-type: application/json" \
    -H "x-api-key: $ANTHROPIC_API_KEY" \
    -H "anthropic-version: 2026-10-21" \
    -d '{
      "model": "claude-opus-5-5",
      "max_tokens": 1024,
      "cache_control": {"type": "ephemeral"},
      "system": "You are an AI assistant tasked with analyzing literary works. Your goal is to provide insightful commentary on themes, characters, and writing style.",
      "messages": [
        {
          "role": "user",
          "content": "Analyze the major themes in Pride and Prejudice."
        }
      ]
    }'
  ```

  ```bash CLI
  ant messages create <<'YAML'
  model: claude-opus-5-5
  max_tokens: 1024
  cache_control:
    type: ephemeral
  system: >-
    You are an AI assistant tasked with analyzing literary works. Your goal is
    to provide insightful commentary on themes, characters, and writing style.
  messages:
    - role: user
      content: Analyze the major themes in Pride and Prejudice.
  YAML
  ```

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

  response = client.messages.create(
      model="claude-opus-5-5",
      max_tokens=1024,
      cache_control={"type": "ephemeral"},
      system="You are an AI assistant tasked with analyzing literary works. Your goal is to provide insightful commentary on themes, characters, and writing style.",
      messages=[
          {
              "role": "user",
              "content": "Analyze the major themes in 'Pride and Prejudice'.",
          }
      ],
  )
  print(response.usage.model_dump_json())
  ```

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

  const response = await client.messages.create({
    model: "claude-opus-5-5",
    max_tokens: 1024,
    cache_control: { type: "ephemeral" },
    system:
      "You are an AI assistant tasked with analyzing literary works. Your goal is to provide insightful commentary on themes, characters, and writing style.",
    messages: [
      {
        role: "user",
        content: "Analyze the major themes in 'Pride and Prejudice'."
      }
    ]
  });
  console.log(response.usage);
  ```

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

  var parameters = new MessageCreateParams
  {
      Model = Model.ClaudeOpus5_5,
      MaxTokens = 1024,
      CacheControl = new CacheControlEphemeral(),
      System = "You are an AI assistant tasked with analyzing literary works. Your goal is to provide insightful commentary on themes, characters, and writing style.",
      Messages =
      [
          new UserMessageParam { Content = "Analyze the major themes in 'Pride and Prejudice'." }
      ]
  };

  var message = await client.Messages.Create(parameters);
  Console.WriteLine(message.Usage);
  ```

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

  response, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
  	Model:        anthropic.ModelClaudeOpus5_5,
  	MaxTokens:    1024,
  	CacheControl: anthropic.NewCacheControlEphemeralParam(),
  	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."},
  	},
  	Messages: []anthropic.MessageParam{
  		anthropic.NewUserMessage(anthropic.NewTextBlock("Analyze the major themes in 'Pride and Prejudice'.")),
  	},
  })
  if err != nil {
  	log.Fatal(err)
  }
  fmt.Println(response.Usage.RawJSON())
  ```

  ```java Java
  import com.anthropic.models.messages.CacheControlEphemeral;
  // ...
  void main() {
      AnthropicClient client = AnthropicOkHttpClient.fromEnv();

      MessageCreateParams params = MessageCreateParams.builder()
          .model(Model.CLAUDE_OPUS_5_5)
          .maxTokens(1024)
          .cacheControl(CacheControlEphemeral.builder().build())
          .system("You are an AI assistant tasked with analyzing literary works. Your goal is to provide insightful commentary on themes, characters, and writing style.")
          .addUserMessage("Analyze the major themes in 'Pride and Prejudice'.")
          .build();

      Message message = client.messages().create(params);
      IO.println(message.usage());
  }
  ```

  ```php PHP
  use Anthropic\Messages\CacheControlEphemeral;
  use Anthropic\Messages\Model;
  // ...
  $client = new Client();

  $response = $client->messages->create(
      maxTokens: 1024,
      messages: [
          ['role' => 'user', 'content' => "Analyze the major themes in 'Pride and Prejudice'."]
      ],
      model: Model::CLAUDE_OPUS_5_5,
      cacheControl: CacheControlEphemeral::with(),
      system: 'You are an AI assistant tasked with analyzing literary works. Your goal is to provide insightful commentary on themes, characters, and writing style.',
  );
  echo json_encode($response->usage);
  ```

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

  response = client.messages.create(
    model: Anthropic::Model::CLAUDE_OPUS_5_5,
    max_tokens: 1024,
    cache_control: {type: "ephemeral"},
    system_: "You are an AI assistant tasked with analyzing literary works. Your goal is to provide insightful commentary on themes, characters, and writing style.",
    messages: [
      {
        role: "user",
        content: "Analyze the major themes in 'Pride and Prejudice'."
      }
    ]
  )
  puts response.usage
  ```
</CodeGroup>

自動キャッシングでは、システムは最後のキャッシュ可能なブロックまで（そのブロックを含む）のすべてのコンテンツをキャッシュします。同じプレフィックスを持つ後続のリクエストでは、キャッシュされたコンテンツが自動的に再利用されます。

***

## プロンプトキャッシングの仕組み

プロンプトキャッシングを有効にしてリクエストを送信すると、次のように処理されます。

1. システムは、指定されたキャッシュブレークポイントまでのプロンプトプレフィックスが、最近のクエリによってすでにキャッシュされているかどうかを確認します。
2. 見つかった場合は、キャッシュされたバージョンを使用し、処理時間とコストを削減します。
3. 見つからない場合は、プロンプト全体を処理し、レスポンスが開始された時点でプレフィックスをキャッシュします。

これは特に次のような場合に役立ちます。

* 多数の例を含むプロンプト
* 大量のコンテキストや背景情報
* 一貫した指示を伴う反復的なタスク
* 長いマルチターンの会話

デフォルトでは、キャッシュの有効期間は5分です。キャッシュされたコンテンツが使用されるたびに、キャッシュは追加コストなしで更新されます。

有効期間は、キャッシュエントリを書き込むまたは読み取るリクエストの開始時点から測定され、そのレスポンスの終了時点からではありません。レスポンスの生成に費やされた時間も有効期間に含まれます。たとえば、レスポンスのストリーミングに4分かかる場合、同じキャッシュ済みプレフィックスを再利用する後続のリクエストは、そのレスポンスの完了から約1分以内に開始する必要があります。

<Note>
  5分では短すぎる場合、Anthropic は[追加料金](https://platform.claude.com/docs/ja/build-with-claude/prompt-caching#pricing)で1時間のキャッシュ期間も提供しています。

  詳細については、[1時間のキャッシュ期間](https://platform.claude.com/docs/ja/build-with-claude/prompt-caching#1-hour-cache-duration)を参照してください。
</Note>

<Tip>
  **プロンプトキャッシングはプレフィックス全体をキャッシュします**

  プロンプトキャッシングは、`cache_control` で指定されたブロックまで（そのブロックを含む）のプロンプト全体、つまり `tools`、`system`、`messages`（この順序）を参照します。
</Tip>

***

## 料金

プロンプトキャッシングには独自の料金体系があります。次の表は、サポートされている各モデルの100万トークンあたりの料金を示しています。

| Model                                                                                                                                                                  | Base input tokens | 5m cache writes | 1h cache writes | Cache hits and refreshes | Output tokens |
| :--------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :---------------- | :-------------- | :-------------- | :----------------------- | :------------ |
| Claude Fable 5.2                                                                                                                                                       | $8 / MTok         | $10 / MTok      | $16 / MTok      | $0.20 / MTok<sup>1</sup> | $40 / MTok    |
| Claude Mythos 5.2 ([limited availability](https://support.claude.com/en/articles/14604842))                                                                            | $8 / MTok         | $10 / MTok      | $16 / MTok      | $0.20 / MTok<sup>1</sup> | $40 / MTok    |
| Claude Fable 5.1                                                                                                                                                       | $10 / MTok        | $12.50 / MTok   | $20 / MTok      | $0.25 / MTok<sup>1</sup> | $50 / MTok    |
| Claude Mythos 5.1 ([limited availability](https://support.claude.com/en/articles/14604842))                                                                            | $10 / MTok        | $12.50 / MTok   | $20 / MTok      | $0.25 / MTok<sup>1</sup> | $50 / MTok    |
| Claude Fable 5                                                                                                                                                         | $10 / MTok        | $12.50 / MTok   | $20 / MTok      | $1 / MTok                | $50 / MTok    |
| Claude Mythos 5 ([limited availability](https://support.claude.com/en/articles/14604842))                                                                              | $10 / MTok        | $12.50 / MTok   | $20 / MTok      | $1 / MTok                | $50 / MTok    |
| Claude Opus 5.5                                                                                                                                                        | $4 / MTok         | $5 / MTok       | $8 / MTok       | $0.20 / MTok<sup>2</sup> | $20 / MTok    |
| Claude Opus 5                                                                                                                                                          | $5 / MTok         | $6.25 / MTok    | $10 / MTok      | $0.50 / MTok             | $25 / MTok    |
| Claude Opus 4.8                                                                                                                                                        | $5 / MTok         | $6.25 / MTok    | $10 / MTok      | $0.50 / MTok             | $25 / MTok    |
| Claude Opus 4.7                                                                                                                                                        | $5 / MTok         | $6.25 / MTok    | $10 / MTok      | $0.50 / MTok             | $25 / MTok    |
| Claude Opus 4.6                                                                                                                                                        | $5 / MTok         | $6.25 / MTok    | $10 / MTok      | $0.50 / MTok             | $25 / MTok    |
| Claude Opus 4.5                                                                                                                                                        | $5 / MTok         | $6.25 / MTok    | $10 / MTok      | $0.50 / MTok             | $25 / 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)) | $15 / MTok        | $18.75 / MTok   | $30 / MTok      | $1.50 / MTok             | $75 / MTok    |
| Claude Opus 4 ([retired, except on Claude Models on Google Cloud (Google managed)](https://platform.claude.com/docs/ja/about-claude/model-deprecations))               | $15 / MTok        | $18.75 / MTok   | $30 / MTok      | $1.50 / MTok             | $75 / MTok    |
| Claude Sonnet 5.5                                                                                                                                                      | $2 / MTok         | $2.50 / MTok    | $4 / MTok       | $0.10 / MTok<sup>2</sup> | $10 / MTok    |
| Claude Sonnet 5                                                                                                                                                        | $2 / MTok         | $2.50 / MTok    | $4 / MTok       | $0.20 / MTok             | $10 / MTok    |
| Claude Sonnet 4.6                                                                                                                                                      | $3 / MTok         | $3.75 / MTok    | $6 / MTok       | $0.30 / MTok             | $15 / MTok    |
| Claude Sonnet 4.5                                                                                                                                                      | $3 / MTok         | $3.75 / MTok    | $6 / MTok       | $0.30 / MTok             | $15 / 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)) | $3 / MTok         | $3.75 / MTok    | $6 / MTok       | $0.30 / MTok             | $15 / MTok    |
| Claude Haiku 5.5 (for prompts up to 100,000 tokens)                                                                                                                    | $0.10 / MTok      | $0.125 / MTok   | $0.20 / MTok    | $0.01 / MTok             | $0.50 / MTok  |
| Claude Haiku 5.5 (for prompts over 100,000 tokens)                                                                                                                     | $0.50 / MTok      | $0.625 / MTok   | $1 / MTok       | $0.05 / MTok             | $2.50 / MTok  |
| Claude Haiku 4.5                                                                                                                                                       | $1 / MTok         | $1.25 / MTok    | $2 / MTok       | $0.10 / MTok             | $5 / MTok     |

*<sup>1 Cache hits and refreshes on Claude Fable 5.2, Claude Mythos 5.2, Claude Fable 5.1, and Claude Mythos 5.1 are priced at 0.025x the base input price.</sup>*

*<sup>2 Cache hits and refreshes on Claude Opus 5.5 and Claude Sonnet 5.5 are priced at 0.05x the base input price.</sup>*

*<sup>All other models use the standard 0.1x multiplier.</sup>*

<Note>
  上記の表は、プロンプトキャッシングに関する次の料金倍率を反映しています。

  * 5分のTTLを持つキャッシュ書き込みトークンは、基本入力トークン価格の1.25倍です。
  * 1時間のTTLを持つキャッシュ書き込みトークンは、基本入力トークン価格の2倍です。
  * キャッシュ読み取りトークンは、基本入力トークン価格の0.1倍です（モデルごとの例外については表の脚注を参照してください）。

  これらの倍率は、Batch API の割引、[ロングコンテキスト料金](https://platform.claude.com/docs/ja/about-claude/pricing#long-context-pricing)、データレジデンシーなど、他の料金調整と組み合わせて適用されます。プロンプトの長さに応じて料金が設定されるモデルでは、キャッシュ読み取りとキャッシュ書き込みはリクエストのプロンプト長にカウントされます。詳細については、[料金](https://platform.claude.com/docs/ja/about-claude/pricing)を参照してください。
</Note>

***

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

プロンプトキャッシング（自動および明示的の両方）は、すべての[アクティブな Claude モデル](https://platform.claude.com/docs/ja/models/overview)でサポートされています。

***

## 自動キャッシング

自動キャッシングは、プロンプトキャッシングを有効にする最も簡単な方法です。個々のコンテンツブロックに `cache_control` を配置する代わりに、リクエスト本文のトップレベルに単一の `cache_control` フィールドを追加します。システムは最後のキャッシュ可能なブロックに自動的にキャッシュブレークポイントを適用します。

<CodeGroup>
  ```bash cURL
  curl https://api.anthropic.com/v1/messages \
    -H "content-type: application/json" \
    -H "x-api-key: $ANTHROPIC_API_KEY" \
    -H "anthropic-version: 2026-10-21" \
    -d '{
      "model": "claude-opus-5-5",
      "max_tokens": 1024,
      "cache_control": {"type": "ephemeral"},
      "system": "You are a helpful assistant that remembers our conversation.",
      "messages": [
        {"role": "user", "content": "My name is Alex. I work on machine learning."},
        {"role": "assistant", "content": "Nice to meet you, Alex! How can I help with your ML work today?"},
        {"role": "user", "content": "What did I say I work on?"}
      ]
    }'
  ```

  ```bash CLI
  ant messages create <<'YAML'
  model: claude-opus-5-5
  max_tokens: 1024
  cache_control:
    type: ephemeral
  system: You are a helpful assistant that remembers our conversation.
  messages:
    - role: user
      content: My name is Alex. I work on machine learning.
    - role: assistant
      content: Nice to meet you, Alex! How can I help with your ML work today?
    - role: user
      content: What did I say I work on?
  YAML
  ```

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

  response = client.messages.create(
      model="claude-opus-5-5",
      max_tokens=1024,
      cache_control={"type": "ephemeral"},
      system="You are a helpful assistant that remembers our conversation.",
      messages=[
          {"role": "user", "content": "My name is Alex. I work on machine learning."},
          {
              "role": "assistant",
              "content": "Nice to meet you, Alex! How can I help with your ML work today?",
          },
          {"role": "user", "content": "What did I say I work on?"},
      ],
  )
  print(response.usage.model_dump_json())
  ```

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

  const response = await client.messages.create({
    model: "claude-opus-5-5",
    max_tokens: 1024,
    cache_control: { type: "ephemeral" },
    system: "You are a helpful assistant that remembers our conversation.",
    messages: [
      { role: "user", content: "My name is Alex. I work on machine learning." },
      {
        role: "assistant",
        content: "Nice to meet you, Alex! How can I help with your ML work today?"
      },
      { role: "user", content: "What did I say I work on?" }
    ]
  });
  console.log(response.usage);
  ```

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

  var parameters = new MessageCreateParams
  {
      Model = Model.ClaudeOpus5_5,
      MaxTokens = 1024,
      CacheControl = new CacheControlEphemeral(),
      System = "You are a helpful assistant that remembers our conversation.",
      Messages =
      [
          new UserMessageParam { Content = "My name is Alex. I work on machine learning." },
          new AssistantMessageParam
          {
              Content = "Nice to meet you, Alex! How can I help with your ML work today?"
          },
          new UserMessageParam { Content = "What did I say I work on?" }
      ]
  };

  var message = await client.Messages.Create(parameters);
  Console.WriteLine(message.Usage);
  ```

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

  response, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
  	Model:        anthropic.ModelClaudeOpus5_5,
  	MaxTokens:    1024,
  	CacheControl: anthropic.NewCacheControlEphemeralParam(),
  	System: []anthropic.TextBlockParam{
  		{Text: "You are a helpful assistant that remembers our conversation."},
  	},
  	Messages: []anthropic.MessageParam{
  		anthropic.NewUserMessage(anthropic.NewTextBlock("My name is Alex. I work on machine learning.")),
  		anthropic.NewAssistantMessage(anthropic.NewTextBlock("Nice to meet you, Alex! How can I help with your ML work today?")),
  		anthropic.NewUserMessage(anthropic.NewTextBlock("What did I say I work on?")),
  	},
  })
  if err != nil {
  	log.Fatal(err)
  }
  fmt.Println(response.Usage.RawJSON())
  ```

  ```java Java
  import com.anthropic.models.messages.CacheControlEphemeral;
  // ...
  void main() {
      AnthropicClient client = AnthropicOkHttpClient.fromEnv();

      MessageCreateParams params = MessageCreateParams.builder()
          .model(Model.CLAUDE_OPUS_5_5)
          .maxTokens(1024)
          .cacheControl(CacheControlEphemeral.builder().build())
          .system("You are a helpful assistant that remembers our conversation.")
          .addUserMessage("My name is Alex. I work on machine learning.")
          .addAssistantMessage("Nice to meet you, Alex! How can I help with your ML work today?")
          .addUserMessage("What did I say I work on?")
          .build();

      Message message = client.messages().create(params);
      IO.println(message.usage());
  }
  ```

  ```php PHP
  use Anthropic\Messages\CacheControlEphemeral;
  use Anthropic\Messages\Model;
  // ...
  $client = new Client();

  $response = $client->messages->create(
      maxTokens: 1024,
      messages: [
          ['role' => 'user', 'content' => 'My name is Alex. I work on machine learning.'],
          ['role' => 'assistant', 'content' => 'Nice to meet you, Alex! How can I help with your ML work today?'],
          ['role' => 'user', 'content' => 'What did I say I work on?'],
      ],
      model: Model::CLAUDE_OPUS_5_5,
      cacheControl: CacheControlEphemeral::with(),
      system: 'You are a helpful assistant that remembers our conversation.',
  );
  echo json_encode($response->usage);
  ```

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

  response = client.messages.create(
    model: Anthropic::Model::CLAUDE_OPUS_5_5,
    max_tokens: 1024,
    cache_control: {type: "ephemeral"},
    system_: "You are a helpful assistant that remembers our conversation.",
    messages: [
      {role: "user", content: "My name is Alex. I work on machine learning."},
      {role: "assistant", content: "Nice to meet you, Alex! How can I help with your ML work today?"},
      {role: "user", content: "What did I say I work on?"}
    ]
  )
  puts response.usage
  ```
</CodeGroup>

### マルチターン会話における自動キャッシングの仕組み

自動キャッシングでは、会話が長くなるにつれてキャッシュポイントが自動的に前方に移動します。新しいリクエストごとに最後のキャッシュ可能なブロックまでのすべてがキャッシュされ、以前のコンテンツはキャッシュから読み取られます。

| リクエスト  | コンテンツ                                                                                                        | キャッシュの動作                                                                 |
| ------ | ------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------ |
| リクエスト1 | System<br />+ User(1) + Asst(1)<br />+ **User(2)** ◀ キャッシュ                                                   | すべてがキャッシュに書き込まれる                                                         |
| リクエスト2 | System<br />+ User(1) + Asst(1)<br />+ User(2) + Asst(2)<br />+ **User(3)** ◀ キャッシュ                          | System から User(2) までがキャッシュから読み取られる。<br />Asst(2) + User(3) がキャッシュに書き込まれる |
| リクエスト3 | System<br />+ User(1) + Asst(1)<br />+ User(2) + Asst(2)<br />+ User(3) + Asst(3)<br />+ **User(4)** ◀ キャッシュ | System から User(3) までがキャッシュから読み取られる。<br />Asst(3) + User(4) がキャッシュに書き込まれる |

キャッシュブレークポイントは各リクエストの最後のキャッシュ可能なブロックに自動的に移動するため、会話が長くなっても `cache_control` マーカーを更新する必要はありません。

### TTL のサポート

デフォルトでは、自動キャッシングは5分のTTLを使用します。基本入力トークン価格の2倍で1時間のTTLを指定することもできます。

```json
{ "cache_control": { "type": "ephemeral", "ttl": "1h" } }
```

### ブロックレベルのキャッシングとの組み合わせ

自動キャッシングは[明示的なキャッシュブレークポイント](https://platform.claude.com/docs/ja/build-with-claude/prompt-caching#explicit-cache-breakpoints)と互換性があります。併用した場合、自動キャッシュブレークポイントは利用可能な4つのブレークポイントスロットのうち1つを使用します。

これにより、両方のアプローチを組み合わせることができます。たとえば、明示的なブレークポイントを使用してシステムプロンプトをキャッシュし、会話は自動キャッシングで処理できます。

```json
{
  "model": "claude-opus-5-5",
  "max_tokens": 1024,
  "cache_control": { "type": "ephemeral" },
  "system": [
    {
      "type": "text",
      "text": "You are a helpful assistant.",
      "cache_control": { "type": "ephemeral" }
    }
  ],
  "messages": [{ "role": "user", "content": "What are the key terms?" }]
}
```

### 変わらない点

自動キャッシングは同じ基盤となるキャッシングインフラストラクチャを使用します。料金、最小トークンしきい値、コンテキストの順序要件、20ブロックのルックバックウィンドウはすべて、明示的なブレークポイントの場合と同様に適用されます。

### エッジケース

* 最後のブロックにすでに同じTTLの明示的な `cache_control` がある場合、自動キャッシングは何も行いません。
* 最後のブロックに異なるTTLの明示的な `cache_control` がある場合、API は400エラーを返します。
* 明示的なブロックレベルのブレークポイントがすでに4つ存在する場合、API は400エラーを返します（自動キャッシングに使えるスロットが残っていないため）。
* 最後のブロックが自動キャッシュブレークポイントの対象として適格でない場合、システムは暗黙的に後方へたどり、最も近い適格なブロックを探します。見つからない場合、キャッシングはスキップされます。

<Note>
  自動キャッシングは、レガシーの [Amazon Bedrock（Opus 4.6 以前）](https://platform.claude.com/docs/ja/build-with-claude/claude-on-amazon-bedrock-legacy) 統合を除くすべてのプラットフォームで利用できます。この統合では、トップレベルの `cache_control` フィールドに対して API が400エラーを返すため、代わりに[明示的なキャッシュブレークポイント](https://platform.claude.com/docs/ja/build-with-claude/prompt-caching#explicit-cache-breakpoints)を使用してください。
</Note>

***

## 明示的なキャッシュブレークポイント

キャッシングをより細かく制御するには、個々のコンテンツブロックに直接 `cache_control` を配置できます。これは、異なる頻度で変更される異なるセクションをキャッシュする必要がある場合や、キャッシュする内容をきめ細かく制御する必要がある場合に便利です。

### プロンプトの構成

静的なコンテンツ（ツール定義、システム指示、コンテキスト、例）をプロンプトの先頭に配置します。`cache_control` パラメータを使用して、キャッシュ対象となる再利用可能なコンテンツの終わりをマークします。

キャッシュプレフィックスは、`tools`、`system`、`messages` の順序で作成されます。この順序は、各レベルが前のレベルの上に構築される階層を形成します。

#### 自動プレフィックスチェックの仕組み

静的コンテンツの末尾にキャッシュブレークポイントを1つだけ使用すれば、システムは以前のリクエストがすでにキャッシュに書き込んだ最長のプレフィックスを自動的に見つけます。この仕組みを理解すると、キャッシング戦略の最適化に役立ちます。

**3つの基本原則：**

1. **キャッシュ書き込みはブレークポイントでのみ発生します。** ブロックに `cache_control` をマークすると、ちょうど1つのキャッシュエントリ、つまりそのブロックで終わるプレフィックスのハッシュが書き込まれます。システムはそれより前の位置にはエントリを書き込みません。ハッシュは累積的で、ブレークポイントまで（ブレークポイントを含む）のすべてを対象とするため、ブレークポイント以前のいずれかのブロックを変更すると、次のリクエストでは異なるハッシュが生成されます。

2. **キャッシュ読み取りは、以前のリクエストが書き込んだエントリを後方に向かって探します。** 各リクエストで、システムはブレークポイントでのプレフィックスハッシュを計算し、一致するキャッシュエントリがあるかを確認します。存在しない場合は1ブロックずつ後方へたどり、それより前の各位置のプレフィックスハッシュがすでにキャッシュにあるものと一致するかを確認します。システムが探しているのは以前の書き込みであり、安定したコンテンツではありません。

3. **ルックバックウィンドウは20ブロックです。** システムは各ブレークポイントについて、ブレークポイント自体を最初の1つとして数え、最大20の位置を確認します。そのウィンドウ内で一致するエントリが見つからない場合、確認は停止します（または、次の明示的なブレークポイントがあればそこから再開します）。Claude API では、連続する `tool_use` ブロックの並びは1つの位置として数えられ、連続する `tool_result` ブロックの並びも同様です。そのため、多数の並列ツール呼び出しを含むターンがあっても、それだけで前のリクエストのエントリがウィンドウの外に押し出されることはありません。

**例：成長する会話でのルックバック**

ターンごとに新しいブロックを追加し、各リクエストの最後のブロックに `cache_control` を設定します。

* **ターン1：** 10ブロック、ブレークポイントはブロック10。以前のキャッシュエントリは存在しません。システムはブロック10にエントリを書き込みます。
* **ターン2：** 15ブロック、ブレークポイントはブロック15。ブロック15にはエントリがないため、システムはブロック10まで後方へたどり、ターン1のエントリを見つけます。ブロック10でキャッシュヒットします。システムはブロック11から15のみを新たに処理し、ブロック15に新しいエントリを書き込みます。
* **ターン3：** 35ブロック、ブレークポイントはブロック35。システムは20の位置（ブロック35から16）を確認しますが、何も見つかりません。ブロック15にあるターン2のエントリはウィンドウの1つ外側にあるため、キャッシュヒットしません。ブロック15に2つ目のブレークポイントを追加すると、そこから2つ目のルックバックウィンドウが始まり、ターン2のエントリが見つかります。

**よくある間違い：リクエストごとに変わるコンテンツへのブレークポイント設定**

プロンプトに大きな静的システムコンテキスト（ブロック1から5）があり、その後にタイムスタンプとユーザーメッセージを含むリクエストごとのブロック（ブロック6）が続くとします。ブロック6に `cache_control` を設定します。

* **リクエスト1：** ブロック6でキャッシュ書き込み。ハッシュにはタイムスタンプが含まれます。
* **リクエスト2：** タイムスタンプが異なるため、ブロック6のプレフィックスハッシュも異なります。ルックバックはブロック5、4、3、2、1をたどりますが、システムはそれらの位置に一度もエントリを書き込んでいません。キャッシュヒットはありません。毎回のリクエストで新たなキャッシュ書き込みの料金が発生し、読み取りは一度も得られません。

ルックバックは、ブレークポイントより前にある安定したコンテンツを見つけてキャッシュするわけではありません。以前のリクエストがすでに書き込んだエントリを見つけるものであり、書き込みはブレークポイントでのみ発生します。`cache_control` をリクエスト間で同じままである最後のブロックであるブロック5に移動すると、後続のすべてのリクエストがキャッシュされたプレフィックスを読み取ります。[自動キャッシング](https://platform.claude.com/docs/ja/build-with-claude/prompt-caching#automatic-caching)にも同じ問題があります。自動キャッシングは最後のキャッシュ可能なブロックにブレークポイントを配置しますが、この構成ではそれがリクエストごとに変わるブロックになるため、代わりにブロック5に明示的なブレークポイントを使用してください。

**重要なポイント：** キャッシュを共有したいリクエスト間でプレフィックスが同一である最後のブロックに `cache_control` を配置してください。成長する会話では、各ターンで追加されるブロックが20未満である限り、最後のブロックで問題ありません。以前のコンテンツは変化しないため、次のリクエストのルックバックが以前の書き込みを見つけます。末尾が変化するプロンプト（タイムスタンプ、リクエストごとのコンテキスト、受信メッセージ）の場合は、変化するブロックではなく、静的プレフィックスの末尾にブレークポイントを配置してください。

#### 複数のブレークポイントを使用するタイミング

次のような場合、最大4つのキャッシュブレークポイントを定義できます。

* 異なる頻度で変更される異なるセクションをキャッシュする（たとえば、ツールはめったに変更されないが、コンテキストは毎日更新される）
* キャッシュする内容をより細かく制御する
* 成長する会話によってブレークポイントが最後のキャッシュ書き込みから20ブロック以上先に押し出された場合でも、キャッシュヒットを確保する

<Note>
  **重要な制限：** ルックバックは、以前のリクエストがすでに書き込んだエントリしか見つけることができません。成長する会話によってブレークポイントが最後の書き込みから20ブロック以上先に押し出されると、ルックバックウィンドウはそれを見逃します。必要になる前にその位置に書き込みが蓄積されるよう、最初からその位置の近くに2つ目のブレークポイントを追加してください。
</Note>

### キャッシュブレークポイントのコストを理解する

**キャッシュブレークポイント自体にはコストはかかりません。** 料金が発生するのは次の項目のみです。

* **キャッシュ書き込み：** 新しいコンテンツがキャッシュに書き込まれるとき（5分のTTLの場合、基本入力トークンより25パーセント高い）
* **キャッシュ読み取り：** キャッシュされたコンテンツが使用されるとき（基本入力トークン価格の10パーセント、[モデルごとの例外](https://platform.claude.com/docs/ja/build-with-claude/prompt-caching#pricing)あり）
* **通常の入力トークン：** キャッシュされていないすべてのコンテンツ

`cache_control` ブレークポイントを追加してもコストは増加しません。実際にキャッシュされ読み取られたコンテンツに基づいて同じ金額を支払います。ブレークポイントは、どのセクションを独立してキャッシュできるかを制御する手段を提供します。

***

## キャッシング戦略と考慮事項

### キャッシュの制限

Claude API、[Claude Platform on AWS](https://platform.claude.com/docs/ja/build-with-claude/claude-platform-on-aws)、[Claude Models on Google Cloud (Google managed)](https://platform.claude.com/docs/ja/build-with-claude/claude-models-on-google-cloud/google-managed)、および [Microsoft Foundry](https://platform.claude.com/docs/ja/build-with-claude/claude-in-microsoft-foundry) では、キャッシュ可能な最小プロンプト長は次のとおりです。

* Claude Fable 5.2、[Claude Mythos 5.2](https://platform.claude.com/docs/ja/models/mythos-5-2/overview)、Claude Fable 5.1、[Claude Mythos 5.1](https://platform.claude.com/docs/ja/models/mythos-5-1/overview)、Claude Opus 5.5、Claude Opus 5、Claude Sonnet 5.5、Claude Fable 5、[Claude Mythos 5](https://platform.claude.com/docs/ja/models/mythos-5/overview)、Claude Haiku 5.5 では512トークン
* [Claude Mythos Preview](https://anthropic.com/glasswing) と Claude Opus 4.7 では2,048トークン
* Claude Opus 4.6 と Claude Opus 4.5 では4,096トークン
* Claude Opus 4.8、Claude Sonnet 5、Claude Sonnet 4.6、Claude Sonnet 4.5（[非推奨](https://platform.claude.com/docs/ja/about-claude/model-deprecations)）、Claude Opus 4.1（[廃止済み、ただし Claude Models on Google Cloud (Google managed) および Bedrock を除く](https://platform.claude.com/docs/ja/about-claude/model-deprecations)）、Claude Opus 4（[廃止済み、ただし Claude Models on Google Cloud (Google managed) を除く](https://platform.claude.com/docs/ja/about-claude/model-deprecations)）、Claude Sonnet 4（[廃止済み、ただし Claude Models on Google Cloud (Google managed) および Bedrock を除く](https://platform.claude.com/docs/ja/about-claude/model-deprecations)）では1,024トークン
* Claude Haiku 4.5 では4,096トークン

これらの最小値は、各モデルが利用可能なすべてのプラットフォームで適用されます。

これより短いプロンプトは、`cache_control` でマークされていてもキャッシュできません。このトークン数未満をキャッシュしようとするリクエストはキャッシングなしで処理され、エラーは返されません。プロンプトがキャッシュされたかどうかを確認するには、[レスポンスの usage フィールド](https://platform.claude.com/docs/ja/build-with-claude/prompt-caching#tracking-cache-performance)を確認してください。`cache_creation_input_tokens` と `cache_read_input_tokens` の両方が0の場合、プロンプトはキャッシュされていません（最小長の要件を満たしていなかった可能性が高いです）。

プロンプトがモデルとプラットフォームの最小値にわずかに届かない場合は、しきい値に達するまでキャッシュされるコンテンツを拡張する価値があることがよくあります。キャッシュ読み取りはキャッシュされていない入力トークンよりも大幅に安価なため、最小値に達することで、頻繁に再利用されるプロンプトのコストを削減できます。

<Note>
  [Bedrock](https://platform.claude.com/docs/ja/build-with-claude/claude-in-amazon-bedrock) は AWS が運営するプラットフォームです。Bedrock では、適用されるモデルごとの最小値、失敗時の動作、usage フィールド名について、[Bedrock のプロンプトキャッシングのドキュメント](https://docs.aws.amazon.com/bedrock/latest/userguide/prompt-caching.html)を参照してください。
</Note>

同時リクエストの場合、キャッシュエントリは最初のレスポンスが開始された後にのみ利用可能になることに注意してください。並列リクエストでキャッシュヒットが必要な場合は、最初のレスポンスを待ってから後続のリクエストを送信してください。

現在、サポートされているキャッシュタイプは `ephemeral` のみで、デフォルトの有効期間は5分です。

### キャッシュできるもの

リクエスト内のほとんどのブロックはキャッシュできます。これには次のものが含まれます。

* ツール：`tools` 配列内のツール定義
* システムメッセージ：`system` 配列内のコンテンツブロック
* テキストメッセージ：`messages.content` 配列内のコンテンツブロック（ユーザーターンとアシスタントターンの両方）
* 画像とドキュメント：`messages.content` 配列内のコンテンツブロック（ユーザーターン）
* ツール使用とツール結果：`messages.content` 配列内のコンテンツブロック（ユーザーターンとアシスタントターンの両方）

これらの各要素は、自動的に、または `cache_control` でマークすることでキャッシュできます。

### キャッシュできないもの

ほとんどのリクエストブロックはキャッシュできますが、いくつかの例外があります。

* 思考ブロックは `cache_control` で直接キャッシュすることはできません。ただし、思考ブロックが以前のアシスタントターンに含まれる場合は、他のコンテンツと一緒にキャッシュされる可能性があります。この方法でキャッシュされた場合、キャッシュから読み取られる際に入力トークンとしてカウントされます。

* サブコンテンツブロック（[引用](https://platform.claude.com/docs/ja/build-with-claude/citations)など）自体は直接キャッシュできません。代わりに、トップレベルのブロックをキャッシュしてください。

  引用の場合、引用のソース資料となるトップレベルのドキュメントコンテンツブロックはキャッシュできます。これにより、引用が参照するドキュメントをキャッシュすることで、引用とともにプロンプトキャッシングを効果的に使用できます。

* 空のテキストブロックはキャッシュできません。

### キャッシュを無効化する要因

キャッシュされたコンテンツを変更すると、キャッシュの一部またはすべてが無効化される可能性があります。

[プロンプトの構成](https://platform.claude.com/docs/ja/build-with-claude/prompt-caching#structuring-your-prompt)で説明したように、キャッシュは `tools` → `system` → `messages` という階層に従います。各レベルでの変更は、そのレベルとそれ以降のすべてのレベルを無効化します。

次の表は、さまざまな種類の変更によってキャッシュのどの部分が無効化されるかを示しています。✘ はキャッシュが無効化されることを、✓ はキャッシュが有効なままであることを示します。

| 変更内容                          | ツールキャッシュ | システムキャッシュ | メッセージキャッシュ | 影響                                                                                                                                                                                                                                                                                                                                                                                                                        |
| ----------------------------- | -------- | --------- | ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **ツール定義**                     | ✘        | ✘         | ✘          | ツール定義（名前、説明、パラメータ）を変更すると、キャッシュ全体が無効化されます                                                                                                                                                                                                                                                                                                                                                                                  |
| **Web検索の切り替え**                | ✓        | ✘         | ✘          | Web検索の有効化/無効化はシステムプロンプトを変更します                                                                                                                                                                                                                                                                                                                                                                                             |
| **引用の切り替え**                   | ✓        | ✘         | ✘          | 引用の有効化/無効化はシステムプロンプトを変更します                                                                                                                                                                                                                                                                                                                                                                                                |
| **速度設定**                      | ✓        | ✘         | ✘          | [`speed: "fast"` と標準速度](https://platform.claude.com/docs/ja/build-with-claude/fast-mode)を切り替えると、システムキャッシュとメッセージキャッシュが無効化されます                                                                                                                                                                                                                                                                                              |
| **ツール選択**                     | ✓        | ✓         | ✘          | `tool_choice` パラメータの変更はメッセージブロックにのみ影響します                                                                                                                                                                                                                                                                                                                                                                                  |
| **画像**                        | ✓        | ✓         | ✘          | プロンプト内のどこかで画像を追加/削除すると、メッセージブロックに影響します                                                                                                                                                                                                                                                                                                                                                                                    |
| **思考パラメータ**                   | モデル依存    | モデル依存     | ✘          | 思考の設定（モード、および拡張モードでの `budget_tokens`）はプロンプトにレンダリングされるため、これを変更すると常にメッセージブロックが無効化されます。設定をツールとシステムより前にレンダリングするモデルでは、ツールキャッシュとシステムキャッシュも無効化されます。[思考とプロンプトキャッシング](https://platform.claude.com/docs/ja/build-with-claude/thinking#thinking-and-prompt-caching)を参照してください。                                                                                                                                                        |
| **エフォート設定**                   | モデル依存    | モデル依存     | ✘          | [`output_config.effort`](https://platform.claude.com/docs/ja/build-with-claude/effort) の値を変更すると常にメッセージブロックが無効化され、ツールキャッシュとシステムキャッシュには思考パラメータと同じモデル依存の影響があります。エフォートをモデルのデフォルト値に明示的に設定することは省略と同等であり、無効化は発生しません。[メッセージごとのエフォート](https://platform.claude.com/docs/ja/build-with-claude/effort#change-effort-mid-conversation-beta)をサポートするモデルでは、`messages` 内の `role: "system"` メッセージで伝えられたエフォートの変更は、キャッシュされたプレフィックスをそのまま維持します。 |
| **思考を伴うリクエストに渡されるツール結果以外の内容** | ✓        | ✓         | モデル依存      | Opus 4.5+、Sonnet 4.6+、Haiku 5.5 では、思考ブロックはデフォルトで保持されるため、キャッシュは有効なままです（✓）。それ以前の Opus/Sonnet モデル、および Claude Haiku 4.5 までの Haiku モデルでは、以前にキャッシュされたすべての思考ブロックがコンテキストから取り除かれ、それらの思考ブロックに続くメッセージはキャッシュから削除されます（✘）。詳細については、[思考ブロックを使用したキャッシング](https://platform.claude.com/docs/ja/build-with-claude/prompt-caching#caching-with-thinking-blocks)を参照してください。                                                                      |
| **破棄された思考ブロック**               | ✓        | ✓         | ✘          | そのリクエストで[保持](https://platform.claude.com/docs/ja/build-with-claude/thinking#preserved-thinking)されない思考ブロックを API が破棄した場合、そのリクエストではそのブロックの位置以降でキャッシュされたプレフィックスが変化します。受信側のモデルが読み取ることができ、変更されずに返されたブロックは、キャッシュをそのまま維持します。                                                                                                                                                                                                      |

[会話途中でのツール変更](https://platform.claude.com/docs/ja/build-with-claude/mid-conversation-system-messages#mid-conversation-tool-changes)をサポートするモデルでは、`inline-tools-2026-09-15` ベータヘッダーを使用すると、`tools` を編集することなく、会話の途中でツールを追加したり、ツールの定義を変更したりできます。定義を会話途中のシステムメッセージ内の `tool_addition` ブロックで送信し、`tools` は最初に送信したとおりのままにしてください。キャッシュされたプレフィックスは引き続き一致するため、追加されたメッセージのみが新しい入力として処理されます。唯一の例外は、遅延されていないツールを含まない `tools` 配列の場合で、この方法で定義された最初のツールは、そのリクエストで1回の完全なキャッシュミスのコストが発生します。[メッセージ内でツールを定義する](https://platform.claude.com/docs/ja/build-with-claude/mid-conversation-system-messages#define-tools-in-a-message-beta)を参照してください。

<Note>
  Claude Fable 5.2、[Claude Mythos 5.2](https://platform.claude.com/docs/ja/models/mythos-5-2/overview)、Claude Fable 5.1、[Claude Mythos 5.1](https://platform.claude.com/docs/ja/models/mythos-5-1/overview)、Claude Fable 5、[Claude Mythos 5](https://platform.claude.com/docs/ja/models/mythos-5/overview)、Claude Opus 5.5、Claude Opus 4.8、Claude Opus 5、Claude Sonnet 5.5、Claude Haiku 5.5 では、システムキャッシュやメッセージキャッシュを無効化することなく、会話の途中で新しいシステム指示を追加できます。トップレベルの `system` フィールドを編集する代わりに、`{"role": "system"}` メッセージを `messages` に追加することで、キャッシュされたプレフィックスは変更されないままになります。この機能は Claude Sonnet 5 では利用できません。代わりにトップレベルの `system` フィールドを使用してください。[会話途中のシステムメッセージとツールの変更](https://platform.claude.com/docs/ja/build-with-claude/mid-conversation-system-messages)を参照してください。
</Note>

### キャッシュパフォーマンスの追跡

レスポンスの `usage` 内（[ストリーミング](https://platform.claude.com/docs/ja/build-with-claude/streaming)の場合は `message_start` イベント内）にある次の API レスポンスフィールドを使用して、キャッシュパフォーマンスを監視します。

* `cache_creation_input_tokens`：新しいエントリを作成する際にキャッシュに書き込まれたトークン数
* `cache_read_input_tokens`：このリクエストでキャッシュから取得されたトークン数
* `input_tokens`：キャッシュから読み取られず、キャッシュの作成にも使用されなかった入力トークン数（つまり、最後のキャッシュブレークポイントより後のトークン）

<Note>
  **トークンの内訳を理解する**

  `input_tokens` フィールドは、送信したすべての入力トークンではなく、リクエスト内の**最後のキャッシュブレークポイントより後**にあるトークンのみを表します。

  合計入力トークンを計算するには：

  ```text wrap
  total_input_tokens = cache_read_input_tokens + cache_creation_input_tokens + input_tokens
  ```

  **位置による説明：**

  * `cache_read_input_tokens` = ブレークポイントより前の、すでにキャッシュされているトークン（読み取り）
  * `cache_creation_input_tokens` = ブレークポイントより前の、今回キャッシュされるトークン（書き込み）
  * `input_tokens` = 最後のブレークポイントより後のトークン（キャッシュ対象外）

  **例：** キャッシュされたコンテンツ（キャッシュから読み取り）が100,000トークン、新たにキャッシュされるコンテンツが0トークン、ユーザーメッセージ（キャッシュブレークポイントの後）が50トークンのリクエストの場合：

  * `cache_read_input_tokens`：100,000
  * `cache_creation_input_tokens`：0
  * `input_tokens`：50
  * **処理された合計入力トークン：** 100,050トークン

  キャッシングを効果的に使用している場合、`input_tokens` は通常、合計入力よりもはるかに小さくなるため、これはコストとレート制限の両方を理解するうえで重要です。
</Note>

### 思考ブロックを使用したキャッシング

プロンプトキャッシングとともに[思考](https://platform.claude.com/docs/ja/build-with-claude/thinking)を使用する場合、思考ブロックには特別な動作があります。

**他のコンテンツとの自動キャッシング：** 思考ブロックは `cache_control` で明示的にマークすることはできませんが、ツール結果を含む後続の API 呼び出しを行う際に、リクエストコンテンツの一部としてキャッシュされます。これは、会話を続けるために思考ブロックを返すツール使用の際によく発生します。

**入力トークンのカウント：** 思考ブロックがキャッシュから読み取られると、使用量メトリクスでは入力トークンとしてカウントされます。これはコスト計算とトークン予算の管理において重要です。

**キャッシュ無効化のパターン：**

* ユーザーメッセージとしてツール結果のみが提供される場合、キャッシュは有効なままです。
* Opus 4.5+、Sonnet 4.6+、Haiku 5.5 では、ツール結果以外のユーザーコンテンツが追加された場合でも思考ブロックはデフォルトで保持されるため、キャッシュは有効なままです。
* それ以前の Opus/Sonnet モデル、および Claude Haiku 4.5 までの Haiku モデルでは、ツール結果以外のユーザーコンテンツが追加されるとキャッシュが無効化され、以前のすべての思考ブロックがコンテキストから取り除かれます。
* このキャッシング動作は、明示的な `cache_control` マーカーがなくても発生します。

キャッシュの無効化の詳細については、[キャッシュを無効化する要因](https://platform.claude.com/docs/ja/build-with-claude/prompt-caching#what-invalidates-the-cache)を参照してください。

**ツール使用の例：**

```text wrap
Request 1: User: "What's the weather in Paris?"
Response: [thinking_block_1] + [tool_use block 1]

Request 2:
User: ["What's the weather in Paris?"],
Assistant: [thinking_block_1] + [tool_use block 1],
User: [tool_result_1, cache=True]
Response: [thinking_block_2] + [text block 2]
# Request 2 caches its request content (not the response)
# The cache includes: user message, thinking_block_1, tool_use block 1, and tool_result_1

Request 3:
User: ["What's the weather in Paris?"],
Assistant: [thinking_block_1] + [tool_use block 1],
User: [tool_result_1, cache=True],
Assistant: [thinking_block_2] + [text block 2],
User: [Text response, cache=True]
# Depending on the model, this non-tool-result user block either keeps prior thinking blocks or strips them (see the next paragraph)
```

それ以前の Opus/Sonnet モデル、および Claude Haiku 4.5 までの Haiku モデルでは、この時点で以前のすべての思考ブロックがコンテキストから削除されます。Opus 4.5+、Sonnet 4.6+、Haiku 5.5 では、以前の思考ブロックはデフォルトで保持され、キャッシュされたプレフィックスの一部として残ります。

より詳細な情報については、[思考とプロンプトキャッシング](https://platform.claude.com/docs/ja/build-with-claude/thinking#thinking-and-prompt-caching)を参照してください。

### キャッシュの保存と共有

<Warning>
  プロンプトキャッシングは[ワークスペース](https://platform.claude.com/docs/ja/manage-claude/workspaces)レベルの分離を使用します。キャッシュはワークスペースごとに分離されており、同じ組織内のワークスペース間でデータの分離が確保されます。これは Claude API、Claude Platform on AWS、Microsoft Foundry に適用されます。Claude Models on Google Cloud (Google managed) と Bedrock は組織レベルのキャッシュ分離を維持します。複数のワークスペースを使用している場合は、この違いを考慮してキャッシング戦略を見直してください。
</Warning>

* **組織とワークスペースの分離：** キャッシュは組織間で分離されています。異なる組織は、同一のプロンプトを使用していても、キャッシュを共有することはありません。Claude API、Claude Platform on AWS、Microsoft Foundry では、キャッシュは組織内のワークスペースごとにも分離されます。Claude Models on Google Cloud (Google managed) と Bedrock は組織レベルの分離のみを使用します。

* **完全一致：** キャッシュヒットには、キャッシュコントロールでマークされたブロックまで（そのブロックを含む）のすべてのテキストと画像を含め、100%同一のプロンプトセグメントが必要です。

* **出力トークンの生成：** プロンプトキャッシングは出力トークンの生成には影響しません。受け取るレスポンスは、プロンプトキャッシングを使用しなかった場合とまったく同じです。

### 効果的なキャッシングのベストプラクティス

プロンプトキャッシングのパフォーマンスを最適化するには：

* マルチターンの会話では[自動キャッシング](https://platform.claude.com/docs/ja/build-with-claude/prompt-caching#automatic-caching)から始めてください。ブレークポイントの管理を自動的に処理します。
* 変更頻度が異なるセクションをキャッシュする必要がある場合は、[明示的なブロックレベルのブレークポイント](https://platform.claude.com/docs/ja/build-with-claude/prompt-caching#explicit-cache-breakpoints)を使用してください。
* システム指示、背景情報、大きなコンテキスト、頻繁に使用されるツール定義など、安定した再利用可能なコンテンツをキャッシュしてください。
* 最高のパフォーマンスを得るには、キャッシュするコンテンツをプロンプトの先頭に配置してください。
* キャッシュブレークポイントを戦略的に使用して、異なるキャッシュ可能なプレフィックスセクションを分離してください。
* リクエスト間で同一のままである最後のブロックにブレークポイントを配置してください。静的なプレフィックスと変化する末尾（タイムスタンプ、リクエストごとのコンテキスト、受信メッセージ）を持つプロンプトの場合、それは変化するブロックではなく、プレフィックスの末尾です。
* キャッシュヒット率を定期的に分析し、必要に応じて戦略を調整してください。

### さまざまなユースケースに合わせた最適化

シナリオに合わせてプロンプトキャッシング戦略を調整してください。

* 会話型エージェント：特に長い指示やアップロードされたドキュメントを含む長時間の会話において、コストとレイテンシを削減します。
* コーディングアシスタント：関連するセクションやコードベースの要約版をプロンプト内に保持することで、オートコンプリートやコードベースに関する Q\&A を改善します。
* 大規模なドキュメント処理：レスポンスのレイテンシを増やすことなく、画像を含む完全な長文資料をプロンプトに組み込みます。
* 詳細な指示セット：Claude のレスポンスを微調整するために、指示、手順、例の広範なリストを共有します。開発者はプロンプトに1つか2つの例を含めることが多いですが、プロンプトキャッシングを使用すれば、高品質な回答の多様な例を20個以上含めることで、さらに優れたパフォーマンスを得られます。
* エージェント的なツール使用：各ステップで通常新しい API 呼び出しが必要となる、複数のツール呼び出しや反復的なコード変更を伴うシナリオのパフォーマンスを向上させます。
* 書籍、論文、ドキュメント、ポッドキャストの文字起こし、その他の長文コンテンツ：ドキュメント全体をプロンプトに埋め込み、ユーザーが質問できるようにすることで、あらゆるナレッジベースをインタラクティブにします。

### よくある問題のトラブルシューティング

予期しない動作が発生した場合：

<Tip>
  [キャッシュ診断](https://platform.claude.com/docs/ja/build-with-claude/cache-diagnostics)を使用すると、API が連続するリクエストを比較し、プロンプトプレフィックスがどこで分岐したかを報告するため、このリストの多くの手順が自動的に処理されます。
</Tip>

* キャッシュされるセクションが呼び出し間で同一であることを確認してください。明示的なブレークポイントの場合は、`cache_control` マーカーが同じ位置にあることを確認してください。
* 呼び出しがキャッシュの有効期間（デフォルトでは5分）内に行われていることを確認してください。
* `tool_choice`、画像の使用、思考の設定、`output_config.effort` が呼び出し間で一貫していることを確認してください。
* モデルとプラットフォームの最小トークン数以上をキャッシュしていることを確認してください（[キャッシュの制限](https://platform.claude.com/docs/ja/build-with-claude/prompt-caching#cache-limitations)を参照）。
* ブレークポイントがリクエスト間で同一のままであるブロックにあることを確認してください。キャッシュ書き込みはブレークポイントでのみ発生し、そのブロックが変化する（タイムスタンプ、リクエストごとのコンテキスト、受信メッセージ）と、プレフィックスハッシュは決して一致しません。ルックバックはブレークポイントより前にある安定したコンテンツを見つけるわけではなく、以前のリクエストがそれぞれのブレークポイントで書き込んだエントリのみを見つけます。
* 一部の言語（たとえば Swift、Go）では JSON 変換時にキーの順序がランダム化され、キャッシュが壊れるため、`tool_use` コンテンツブロック内のキーの順序が安定していることを確認してください。
* [キャッシュ診断](https://platform.claude.com/docs/ja/build-with-claude/cache-diagnostics)を使用して、API に連続するリクエストを比較させ、プロンプトのどの部分が分岐したかを報告させてください。

<Note>
  `tool_choice` の変更や、プロンプト内のどこかにおける画像の有無の変更はキャッシュを無効化し、新しいキャッシュエントリの作成が必要になります。キャッシュの無効化の詳細については、[キャッシュを無効化する要因](https://platform.claude.com/docs/ja/build-with-claude/prompt-caching#what-invalidates-the-cache)を参照してください。
</Note>

***

## 1時間のキャッシュ期間

5分では短すぎる場合、Anthropic は[追加料金](https://platform.claude.com/docs/ja/build-with-claude/prompt-caching#pricing)で1時間のキャッシュ期間も提供しています。

<Note>
  1時間のキャッシュ期間は、Claude API、[Amazon Bedrock](https://platform.claude.com/docs/ja/build-with-claude/claude-in-amazon-bedrock)、[Amazon Bedrock（Opus 4.6 以前）](https://platform.claude.com/docs/ja/build-with-claude/claude-on-amazon-bedrock-legacy)、[Claude Platform on AWS](https://platform.claude.com/docs/ja/build-with-claude/claude-platform-on-aws)、[Claude Models on Google Cloud (Google managed)](https://platform.claude.com/docs/ja/build-with-claude/claude-models-on-google-cloud/google-managed)、および [Microsoft Foundry](https://platform.claude.com/docs/ja/build-with-claude/claude-in-microsoft-foundry) で利用できます。
</Note>

拡張キャッシュを使用するには、次のように `cache_control` の定義に `ttl` を含めます。

```json
"cache_control": {
  "type": "ephemeral",
  "ttl": "1h"
}
```

レスポンスには、次のような詳細なキャッシュ情報が含まれます。

```json Output
{
  "usage": {
    "input_tokens": 2048,
    "cache_read_input_tokens": 1800,
    "cache_creation_input_tokens": 248,
    "output_tokens": 503,

    "cache_creation": {
      "ephemeral_5m_input_tokens": 148,
      "ephemeral_1h_input_tokens": 100
    }
  }
}
```

`cache_creation_input_tokens` フィールドは、`cache_creation` オブジェクト内の値の合計と等しくなります。

Web検索などのサーバーツールを使用している際に、リクエストしていない `ephemeral_5m_input_tokens` の書き込みが表示される場合は、[サーバーツールの結果は自動的にキャッシュされます](https://platform.claude.com/docs/ja/agents-and-tools/tool-use/tool-use-with-prompt-caching#server-tool-results-are-cached-automatically)を参照してください。

### 1時間のキャッシュを使用するタイミング

プロンプトを定期的な間隔で使用する場合（たとえば、5分ごとよりも頻繁に送信するシステムプロンプト）は、追加料金なしで更新され続けるため、引き続き5分のキャッシュを使用してください。

1時間のキャッシュは、次のシナリオで最適に使用されます。

* 5分ごとよりも低い頻度で、かつ1時間ごとよりも高い頻度で使用される可能性が高いプロンプトがある場合。たとえば、エージェント的なサイドエージェントの処理に5分以上かかる場合や、ユーザーとの長いチャット会話を保存していて、そのユーザーが次の5分以内に応答しない可能性が一般的に高いと予想される場合です。
* レイテンシが重要で、後続のプロンプトが5分を超えて送信される可能性がある場合。
* キャッシュヒットはレート制限から差し引かれないため、レート制限の利用効率を改善したい場合。

<Note>
  5分のキャッシュと1時間のキャッシュは、レイテンシに関しては同じように動作します。長いドキュメントでは、一般的に最初のトークンまでの時間が改善されます。
</Note>

### 異なるTTLの混在

同じリクエスト内で1時間と5分のキャッシュ制御の両方を使用できますが、重要な制約があります。TTLが長いキャッシュエントリは、TTLが短いものより前に配置する必要があります（つまり、1時間のキャッシュエントリは、5分のキャッシュエントリより前に配置する必要があります）。

TTLを混在させる場合、Claude APIはプロンプト内の3つの課金位置を決定します。

1. 位置`A`：プロンプト内の最後のキャッシュヒットにおけるトークン数（ヒットがない場合は0）。

   * 5分のTTLでキャッシュされたエントリへのヒットは、それより後に位置する、TTLが1時間の`cache_control`ブロックがキャッシュミスである場合、ヒットとはみなされません。
   * 5分のTTLでキャッシュされたエントリを読み取るリクエストは、今回のリクエストで`"ttl": "1h"`を指定している場合でも、そのエントリの5分の有効期間を最初から開始し直します。

2. 位置`B`：`A`の後にある、TTLが1時間の最後の`cache_control`ブロックにおけるトークン数（存在しない場合は`A`と等しい）。

3. 位置`C`：最後の`cache_control`ブロックにおけるトークン数。

<Note>
  `B`または`C`が`A`より大きい場合、それは必然的にキャッシュミスとなります。
</Note>

以下の料金が課金されます。

1. `A`に対するキャッシュ読み取りトークン。
2. `(B - A)`に対する1時間キャッシュ書き込みトークン。
3. `(C - B)`に対する5分キャッシュ書き込みトークン。

以下に、それぞれキャッシュヒットとキャッシュミスが異なる3つのリクエストの例を示します。ボックスに示されているように、それぞれ異なる料金が計算されます。

<Frame>
  ![キャッシュヒットとミスが異なる3つのリクエスト：A、B、Cは、読み取り、1時間書き込み、5分書き込みがそれぞれ終了する位置を示します](https://platform.claude.com/docs/ja/images/prompt-cache-mixed-ttl.svg)
</Frame>

***

## キャッシュの事前ウォームアップ

キャッシュの事前ウォームアップ（pre-warming）を使用すると、ユーザーが実際のリクエストをトリガーする前に、システムプロンプトやツール定義をプロンプトキャッシュに読み込むことができます。これにより、最初のユーザーインタラクションにおけるキャッシュミスのレイテンシペナルティを軽減でき、レイテンシが重要なアプリケーションで「time-to-first-token」（最初のトークンまでの時間）、すなわちTTFTを短縮できます。

### 仕組み

リクエストで`max_tokens: 0`を設定します。APIはプロンプトをモデルに読み込み、すべての`cache_control`ブレークポイントでキャッシュを書き込んだ後、出力を生成せずに即座に返します。レスポンスには空の`content`配列、`stop_reason: "max_tokens"`、そして完全に値が設定された`usage`ブロックが含まれます。

`cache_control`ブレークポイントは、プレースホルダーのユーザーメッセージではなく、後続のリクエストと共有される最後のブロック（通常はシステムプロンプトまたはツール定義）に配置してください。そうしないと、キャッシュエントリはプレースホルダーをキーとして作成され、後続のリクエストはそれにヒットしません。また、思考の設定と`output_config.effort`も後続のリクエストと同じものを使用してください。これらの値はプロンプトにレンダリングされるため（[キャッシュを無効化する要因](https://platform.claude.com/docs/ja/build-with-claude/prompt-caching#what-invalidates-the-cache)を参照）、異なる設定で事前ウォームアップを行うと、実際のトラフィックが決してヒットしないエントリが書き込まれる可能性があります。つまり、[自動キャッシング](https://platform.claude.com/docs/ja/build-with-claude/prompt-caching#automatic-caching)ではなく[明示的なキャッシュブレークポイント](https://platform.claude.com/docs/ja/build-with-claude/prompt-caching#explicit-cache-breakpoints)を使用することになります。自動キャッシングはブレークポイントを最後のブロックに配置しますが、ここではそれがプレースホルダーになってしまうためです。プレースホルダーのユーザーメッセージには、空白以外の内容を含む任意の文字列を使用できます（ここでの例では`"warmup"`を使用しています）。その内容はモデルに読み込まれますが、応答されることはありません。

<Note>
  事前ウォームアップリクエストでは、プレフィックスがまだキャッシュされていない場合、他のリクエストと同様に**キャッシュ書き込み**料金が発生します。書き込みが発生したことを確認するには、レスポンスの`usage.cache_creation_input_tokens`を確認してください。出力トークンは0として課金されます。
</Note>

<CodeGroup>
  ```bash cURL
  curl https://api.anthropic.com/v1/messages \
    -H "content-type: application/json" \
    -H "x-api-key: $ANTHROPIC_API_KEY" \
    -H "anthropic-version: 2026-10-21" \
    -d '{
      "model": "claude-opus-5-5",
      "max_tokens": 0,
      "system": [
        {
          "type": "text",
          "text": "You are an expert software engineer with deep knowledge of distributed systems...",
          "cache_control": {"type": "ephemeral"}
        }
      ],
      "messages": [{"role": "user", "content": "warmup"}]
    }'
  ```

  ```bash CLI
  ant messages create <<'YAML'
  model: claude-opus-5-5
  max_tokens: 0
  system:
    - type: text
      text: >-
        You are an expert software engineer with deep knowledge of
        distributed systems...
      cache_control:
        type: ephemeral
  messages:
    - role: user
      content: warmup
  YAML
  ```

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

  # ユーザーが来る前にこれを実行し、共有のシステムプロンプトキャッシュをウォームアップします。
  prewarm = client.messages.create(
      model="claude-opus-5-5",
      max_tokens=0,
      system=[
          {
              "type": "text",
              "text": "You are an expert software engineer with deep knowledge of distributed systems...",
              "cache_control": {"type": "ephemeral"},
          }
      ],
      messages=[{"role": "user", "content": "warmup"}],
  )
  print(prewarm.stop_reason)  # "max_tokens"
  print(prewarm.content)  # []
  print(prewarm.usage)
  ```

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

  // ユーザーが来る前にこれを実行し、共有システムプロンプトのキャッシュをウォームアップします。
  const prewarm = await client.messages.create({
    model: "claude-opus-5-5",
    max_tokens: 0,
    system: [
      {
        type: "text",
        text: "You are an expert software engineer with deep knowledge of distributed systems...",
        cache_control: { type: "ephemeral" }
      }
    ],
    messages: [{ role: "user", content: "warmup" }]
  });
  console.log(prewarm.stop_reason); // "max_tokens"
  console.log(prewarm.content); // []
  console.log(prewarm.usage);
  ```

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

  var prewarm = await client.Messages.Create(
      new()
      {
          Model = Model.ClaudeOpus5_5,
          MaxTokens = 0,
          System = new(
              [
                  new TextBlockParam
                  {
                      Text = "You are an expert software engineer with deep knowledge of distributed systems...",
                      CacheControl = new(),
                  },
              ]
          ),
          Messages = [new UserMessageParam { Content = "warmup" }],
      }
  );

  Console.WriteLine(prewarm.StopReason?.Raw()); // "max_tokens"
  Console.WriteLine(prewarm.Content.Count); // 0
  Console.WriteLine(prewarm.Usage);
  ```

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

  prewarm, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
  	Model:     anthropic.ModelClaudeOpus5_5,
  	MaxTokens: 0,
  	System: []anthropic.TextBlockParam{
  		{
  			Text:         "You are an expert software engineer with deep knowledge of distributed systems...",
  			CacheControl: anthropic.NewCacheControlEphemeralParam(),
  		},
  	},
  	Messages: []anthropic.MessageParam{
  		anthropic.NewUserMessage(anthropic.NewTextBlock("warmup")),
  	},
  })
  if err != nil {
  	panic(err)
  }

  fmt.Println(prewarm.StopReason) // "max_tokens"
  fmt.Println(prewarm.Content)    // []
  fmt.Println(prewarm.Usage.RawJSON())
  ```

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

  Message prewarm = client.messages().create(MessageCreateParams.builder()
      .model(Model.CLAUDE_OPUS_5_5)
      .maxTokens(0)
      .systemOfTextBlockParams(List.of(TextBlockParam.builder()
          .text("You are an expert software engineer with deep knowledge of distributed systems...")
          .cacheControl(CacheControlEphemeral.builder().build())
          .build()))
      .addUserMessage("warmup")
      .build());

  IO.println(prewarm.stopReason()); // Optional[max_tokens]
  IO.println(prewarm.content());    // []
  IO.println(prewarm.usage());
  ```

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

  $prewarm = $client->messages->create(
      model: Model::CLAUDE_OPUS_5_5,
      maxTokens: 0,
      system: [
          [
              'type' => 'text',
              'text' => 'You are an expert software engineer with deep knowledge of distributed systems...',
              'cache_control' => ['type' => 'ephemeral'],
          ],
      ],
      messages: [['role' => 'user', 'content' => 'warmup']],
  );

  echo $prewarm->stopReason, PHP_EOL; // "max_tokens"
  echo json_encode($prewarm->content), PHP_EOL; // []
  echo json_encode($prewarm->usage), PHP_EOL;
  ```

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

  prewarm = client.messages.create(
    model: Anthropic::Model::CLAUDE_OPUS_5_5,
    max_tokens: 0,
    system_: [
      {
        type: "text",
        text: "You are an expert software engineer with deep knowledge of distributed systems...",
        cache_control: {type: "ephemeral"}
      }
    ],
    messages: [{role: "user", content: "warmup"}]
  )

  puts prewarm.stop_reason # :max_tokens
  puts prewarm.content # []
  puts prewarm.usage
  ```
</CodeGroup>

APIは空の`content`配列を返します。

```json Output
{
  "id": "msg_01XFDUDYJgAACzvnptvVoYEL",
  "type": "message",
  "role": "assistant",
  "content": [],
  "model": "claude-opus-5-5",
  "stop_reason": "max_tokens",
  "stop_sequence": null,
  "usage": {
    "input_tokens": 8,
    "cache_creation_input_tokens": 5120,
    "cache_read_input_tokens": 0,
    "cache_creation": {
      "ephemeral_5m_input_tokens": 5120,
      "ephemeral_1h_input_tokens": 0
    },
    "iterations": [
      {
        "input_tokens": 8,
        "output_tokens": 0,
        "cache_read_input_tokens": 0,
        "cache_creation_input_tokens": 5120,
        "cache_creation": {
          "ephemeral_5m_input_tokens": 5120,
          "ephemeral_1h_input_tokens": 0
        },
        "type": "message"
      }
    ],
    "output_tokens": 0,
    "service_tier": "standard",
    "inference_geo": "global"
  }
}
```

### 一般的な使用パターン

アプリケーションの起動時（または定期的な間隔で）事前ウォームアップリクエストを送信し、事前ウォームアップが完了した後に実際のユーザーリクエストを送信します。

<CodeGroup>
  ```bash cURL
  # アプリケーションの起動時、または定期的な間隔でキャッシュをウォームアップします。
  curl https://api.anthropic.com/v1/messages \
    -H "content-type: application/json" \
    -H "x-api-key: $ANTHROPIC_API_KEY" \
    -H "anthropic-version: 2026-10-21" \
    -d '{
      "model": "claude-opus-5-5",
      "max_tokens": 0,
      "system": [
        {
          "type": "text",
          "text": "You are an expert software engineer with deep knowledge of distributed systems...",
          "cache_control": {"type": "ephemeral"}
        }
      ],
      "messages": [{"role": "user", "content": "warmup"}]
    }'

  # 後でユーザーがメッセージを送信した時点で、システムプロンプトのプレフィックスはすでにキャッシュされています。
  curl https://api.anthropic.com/v1/messages \
    -H "content-type: application/json" \
    -H "x-api-key: $ANTHROPIC_API_KEY" \
    -H "anthropic-version: 2026-10-21" \
    -d '{
      "model": "claude-opus-5-5",
      "max_tokens": 1024,
      "system": [
        {
          "type": "text",
          "text": "You are an expert software engineer with deep knowledge of distributed systems...",
          "cache_control": {"type": "ephemeral"}
        }
      ],
      "messages": [{"role": "user", "content": "How do I implement a binary search tree?"}]
    }'
  ```

  ```bash CLI
  # アプリケーションの起動時または定期的な間隔でキャッシュをウォームアップします。
  ant messages create <<'YAML'
  model: claude-opus-5-5
  max_tokens: 0
  system:
    - type: text
      text: >-
        You are an expert software engineer with deep knowledge of
        distributed systems...
      cache_control:
        type: ephemeral
  messages:
    - role: user
      content: warmup
  YAML

  # 後でユーザーがメッセージを送信する時点では、システムプロンプトのプレフィックスはすでにキャッシュされています。
  ant messages create <<'YAML'
  model: claude-opus-5-5
  max_tokens: 1024
  system:
    - type: text
      text: >-
        You are an expert software engineer with deep knowledge of
        distributed systems...
      cache_control:
        type: ephemeral
  messages:
    - role: user
      content: How do I implement a binary search tree?
  YAML
  ```

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

  SYSTEM_PROMPT = [
      {
          "type": "text",
          "text": "You are an expert software engineer with deep knowledge of distributed systems...",
          "cache_control": {"type": "ephemeral"},
      }
  ]


  def prewarm_cache() -> None:
      """Call this at application startup or on a scheduled interval."""
      client.messages.create(
          model="claude-opus-5-5",
          max_tokens=0,
          system=SYSTEM_PROMPT,
          messages=[{"role": "user", "content": "warmup"}],
      )


  def respond(user_message: str) -> anthropic.types.Message:
      """The real user request; benefits from a warm cache."""
      return client.messages.create(
          model="claude-opus-5-5",
          max_tokens=1024,
          system=SYSTEM_PROMPT,
          messages=[{"role": "user", "content": user_message}],
      )


  # ユーザーのトラフィックが到着する前にキャッシュをウォームアップします。
  prewarm_cache()

  # 後でユーザーがメッセージを送信する時点では、システムプロンプトのプレフィックスはすでにキャッシュされています。
  response = respond("How do I implement a binary search tree?")
  for block in response.content:
      if block.type == "text":
          print(block.text)
  ```

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

  const SYSTEM_PROMPT: Anthropic.TextBlockParam[] = [
    {
      type: "text",
      text: "You are an expert software engineer with deep knowledge of distributed systems...",
      cache_control: { type: "ephemeral" }
    }
  ];

  // アプリケーションの起動時、または定期的なスケジュールで呼び出します。
  async function prewarmCache(): Promise<void> {
    await client.messages.create({
      model: "claude-opus-5-5",
      max_tokens: 0,
      system: SYSTEM_PROMPT,
      messages: [{ role: "user", content: "warmup" }]
    });
  }

  // 実際のユーザーリクエストです。ウォームなキャッシュの恩恵を受けます。
  async function respond(userMessage: string): Promise<Anthropic.Message> {
    return client.messages.create({
      model: "claude-opus-5-5",
      max_tokens: 1024,
      system: SYSTEM_PROMPT,
      messages: [{ role: "user", content: userMessage }]
    });
  }

  // ユーザーのトラフィックが届く前にキャッシュをウォームアップします。
  await prewarmCache();

  // 後でユーザーがメッセージを送信した時点で、システムプロンプトのプレフィックスはすでにキャッシュされています。
  const response = await respond("How do I implement a binary search tree?");
  const textBlock = response.content.find((block) => block.type === "text");
  console.log(textBlock?.text);
  ```

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

  List<TextBlockParam> systemPrompt =
  [
      new TextBlockParam
      {
          Text = "You are an expert software engineer with deep knowledge of distributed systems...",
          CacheControl = new(),
      },
  ];

  // アプリケーションの起動時、または定期的なスケジュールでこれを呼び出します。
  async Task PrewarmCache() =>
      await client.Messages.Create(
          new()
          {
              Model = Model.ClaudeOpus5_5,
              MaxTokens = 0,
              System = new(systemPrompt),
              Messages = [new UserMessageParam { Content = "warmup" }],
          }
      );

  // 実際のユーザーリクエストです。ウォームキャッシュの恩恵を受けます。
  async Task<Message> Respond(string userMessage) =>
      await client.Messages.Create(
          new()
          {
              Model = Model.ClaudeOpus5_5,
              MaxTokens = 1024,
              System = new(systemPrompt),
              Messages = [new UserMessageParam { Content = userMessage }],
          }
      );

  // ユーザートラフィックが到着する前にキャッシュをウォームアップします。
  await PrewarmCache();

  // 後でユーザーがメッセージを送信した時点で、システムプロンプトのプレフィックスはすでにキャッシュされています。
  var response = await Respond("How do I implement a binary search tree?");
  foreach (var block in response.Content)
  {
      if (block.TryPickText(out var textBlock))
      {
          Console.WriteLine(textBlock.Text);
      }
  }
  ```

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

  var systemPrompt = []anthropic.TextBlockParam{
  	{
  		Text:         "You are an expert software engineer with deep knowledge of distributed systems...",
  		CacheControl: anthropic.NewCacheControlEphemeralParam(),
  	},
  }

  // アプリケーションの起動時、または定期的なスケジュールで呼び出してください。
  func prewarmCache() error {
  	_, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
  		Model:     anthropic.ModelClaudeOpus5_5,
  		MaxTokens: 0,
  		System:    systemPrompt,
  		Messages: []anthropic.MessageParam{
  			anthropic.NewUserMessage(anthropic.NewTextBlock("warmup")),
  		},
  	})
  	return err
  }

  // 実際のユーザーリクエストです。ウォームキャッシュの恩恵を受けます。
  func respond(userMessage string) (*anthropic.Message, error) {
  	return client.Messages.New(context.TODO(), anthropic.MessageNewParams{
  		Model:     anthropic.ModelClaudeOpus5_5,
  		MaxTokens: 1024,
  		System:    systemPrompt,
  		Messages: []anthropic.MessageParam{
  			anthropic.NewUserMessage(anthropic.NewTextBlock(userMessage)),
  		},
  	})
  }

  func main() {
  	// ユーザートラフィックが到着する前にキャッシュをウォームアップします。
  	if err := prewarmCache(); err != nil {
  		log.Fatal(err)
  	}

  	// 後でユーザーがメッセージを送信する時点では、システムプロンプトのプレフィックスはすでにキャッシュされています。
  	response, err := respond("How do I implement a binary search tree?")
  	if err != nil {
  		log.Fatal(err)
  	}
  	for _, block := range response.Content {
  		if textBlock, ok := block.AsAny().(anthropic.TextBlock); ok {
  			fmt.Println(textBlock.Text)
  		}
  	}
  }
  ```

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

  List<TextBlockParam> systemPrompt = List.of(TextBlockParam.builder()
      .text("You are an expert software engineer with deep knowledge of distributed systems...")
      .cacheControl(CacheControlEphemeral.builder().build())
      .build());

  // アプリケーションの起動時、または定期的なスケジュールでこれを呼び出します。
  void prewarmCache() {
      client.messages().create(MessageCreateParams.builder()
          .model(Model.CLAUDE_OPUS_5_5)
          .maxTokens(0)
          .systemOfTextBlockParams(systemPrompt)
          .addUserMessage("warmup")
          .build());
  }

  // 実際のユーザーリクエストです。ウォームキャッシュの恩恵を受けます。
  Message respond(String userMessage) {
      return client.messages().create(MessageCreateParams.builder()
          .model(Model.CLAUDE_OPUS_5_5)
          .maxTokens(1024)
          .systemOfTextBlockParams(systemPrompt)
          .addUserMessage(userMessage)
          .build());
  }

  void main() {
      // ユーザートラフィックが到着する前にキャッシュをウォームアップします。
      prewarmCache();

      // 後でユーザーがメッセージを送信した時点で、システムプロンプトのプレフィックスはすでにキャッシュされています。
      Message response = respond("How do I implement a binary search tree?");
      response.content().stream()
          .flatMap(block -> block.text().stream())
          .forEach(textBlock -> IO.println(textBlock.text()));
  }
  ```

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

  $systemPrompt = [
      [
          'type' => 'text',
          'text' => 'You are an expert software engineer with deep knowledge of distributed systems...',
          'cache_control' => ['type' => 'ephemeral'],
      ],
  ];

  // アプリケーションの起動時、または定期的なスケジュールでこれを呼び出します。
  $prewarmCache = fn () => $client->messages->create(
      model: Model::CLAUDE_OPUS_5_5,
      maxTokens: 0,
      system: $systemPrompt,
      messages: [['role' => 'user', 'content' => 'warmup']],
  );

  // 実際のユーザーリクエストです。ウォームなキャッシュの恩恵を受けます。
  $respond = fn (string $userMessage) => $client->messages->create(
      model: Model::CLAUDE_OPUS_5_5,
      maxTokens: 1024,
      system: $systemPrompt,
      messages: [['role' => 'user', 'content' => $userMessage]],
  );

  // ユーザートラフィックが到着する前にキャッシュをウォームアップします。
  $prewarmCache();

  // その後、ユーザーがメッセージを送信する時点では、システムプロンプトのプレフィックスはすでにキャッシュされています。
  $response = $respond('How do I implement a binary search tree?');
  foreach ($response->content as $block) {
      if ($block instanceof \Anthropic\Messages\TextBlock) {
          echo $block->text, PHP_EOL;
      }
  }
  ```

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

  SYSTEM_PROMPT = [
    {
      type: "text",
      text: "You are an expert software engineer with deep knowledge of distributed systems...",
      cache_control: {type: "ephemeral"}
    }
  ]

  # アプリケーションの起動時、または定期的な間隔でこれを呼び出します。
  def prewarm_cache(client)
    client.messages.create(
      model: Anthropic::Model::CLAUDE_OPUS_5_5,
      max_tokens: 0,
      system_: SYSTEM_PROMPT,
      messages: [{role: "user", content: "warmup"}]
    )
  end

  # 実際のユーザーリクエストです。ウォームキャッシュの恩恵を受けます。
  def respond(client, user_message)
    client.messages.create(
      model: Anthropic::Model::CLAUDE_OPUS_5_5,
      max_tokens: 1024,
      system_: SYSTEM_PROMPT,
      messages: [{role: "user", content: user_message}]
    )
  end

  # ユーザーからのトラフィックが届く前にキャッシュをウォームアップします。
  prewarm_cache(client)

  # 後でユーザーがメッセージを送信する時点で、システムプロンプトのプレフィックスはすでにキャッシュされています。
  response = respond(client, "How do I implement a binary search tree?")
  response.content.each do |block|
    puts block.text if block.is_a?(Anthropic::Models::TextBlock)
  end
  ```
</CodeGroup>

キャッシュのTTLは引き続き適用されることに注意してください。デフォルトの5分キャッシュの場合、キャッシュをウォームな状態に保つには、少なくとも5分ごとに新しい事前ウォームアップリクエストを送信してください。ユーザーリクエスト間の間隔が長い場合は、代わりに[1時間のキャッシュ期間](https://platform.claude.com/docs/ja/build-with-claude/prompt-caching#1-hour-cache-duration)を使用してください。

### 制限事項

以下のいずれかが設定されている場合、`max_tokens: 0`リクエストは`invalid_request_error`で拒否されます。これらはいずれも、トークン予算がゼロでは生成できない出力を前提としているためです。

* `stream: true`
* [拡張思考](https://platform.claude.com/docs/ja/build-with-claude/extended-thinking)（`thinking.type: "enabled"`）
* [構造化出力](https://platform.claude.com/docs/ja/build-with-claude/structured-outputs)（`output_config.format`）
* `{"type": "tool", ...}`または`{"type": "any"}`の`tool_choice`

`max_tokens: 0`は[Message Batches](https://platform.claude.com/docs/ja/build-with-claude/batch-processing)リクエスト内でも拒否されます。事前ウォームアップは最初のトークンまでの時間を対象としていますが、これはバッチ処理には当てはまらず、また、バッチ処理中に書き込まれたキャッシュエントリは後続のリクエストが実行される前に期限切れになる可能性が高いためです。

### `max_tokens=1`による回避策の置き換え

一部のアプリケーションは、キャッシュをウォームアップするために`max_tokens: 1`のリクエストを送信しています。リクエストで許可される場合は`max_tokens: 0`を優先してください。出力が生成されないため、破棄すべき1トークンの応答がなく、出力トークンも課金されず、リクエストの意図が明確になります。

***

## プロンプトキャッシングの例

プロンプトキャッシングを始めるにあたり、Claude Cookbookの[プロンプトキャッシングのレシピ](https://platform.claude.com/cookbook/misc-prompt-caching)で詳細な例とベストプラクティスを確認できます。

以下のコードスニペットは、さまざまなプロンプトキャッシングのパターンを示しています。これらの例では、さまざまなシナリオでキャッシングを実装する方法を示しており、この機能の実際の応用を理解するのに役立ちます。

<AccordionGroup>
  <Accordion title="大規模コンテキストのキャッシングの例">
    <CodeGroup>
      ```bash cURL
      curl https://api.anthropic.com/v1/messages \
        -H "x-api-key: $ANTHROPIC_API_KEY" \
        -H "anthropic-version: 2026-10-21" \
        -H "content-type: application/json" \
        -d '{
          "model": "claude-opus-5-5",
          "max_tokens": 1024,
          "system": [
            {
              "type": "text",
              "text": "You are an AI assistant tasked with analyzing legal documents."
            },
            {
              "type": "text",
              "text": "Here is the full text of a complex legal agreement: [Insert full text of a 50-page legal agreement here]",
              "cache_control": {"type": "ephemeral"}
            }
          ],
          "messages": [
            {
              "role": "user",
              "content": "What are the key terms and conditions in this agreement?"
            }
          ]
        }'
      ```

      ```bash CLI
      ant messages create <<'YAML'
      model: claude-opus-5-5
      max_tokens: 1024
      system:
        - type: text
          text: You are an AI assistant tasked with analyzing legal documents.
        - type: text
          text: >-
            Here is the full text of a complex legal agreement:
            [Insert full text of a 50-page legal agreement here]
          cache_control:
            type: ephemeral
      messages:
        - role: user
          content: What are the key terms and conditions in this agreement?
      YAML
      ```

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

      response = client.messages.create(
          model="claude-opus-5-5",
          max_tokens=1024,
          system=[
              {
                  "type": "text",
                  "text": "You are an AI assistant tasked with analyzing legal documents.",
              },
              {
                  "type": "text",
                  "text": "Here is the full text of a complex legal agreement: [Insert full text of a 50-page legal agreement here]",
                  "cache_control": {"type": "ephemeral"},
              },
          ],
          messages=[
              {
                  "role": "user",
                  "content": "What are the key terms and conditions in this agreement?",
              }
          ],
      )
      print(response.usage.model_dump_json())
      ```

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

      const response = await client.messages.create({
        model: "claude-opus-5-5",
        max_tokens: 1024,
        system: [
          {
            type: "text",
            text: "You are an AI assistant tasked with analyzing legal documents."
          },
          {
            type: "text",
            text: "Here is the full text of a complex legal agreement: [Insert full text of a 50-page legal agreement here]",
            cache_control: { type: "ephemeral" }
          }
        ],
        messages: [
          {
            role: "user",
            content: "What are the key terms and conditions in this agreement?"
          }
        ]
      });
      console.log(response.usage);
      ```

      ```csharp C#
      AnthropicClient client = new()
      {
          ApiKey = Environment.GetEnvironmentVariable("ANTHROPIC_API_KEY")
      };

      var parameters = new MessageCreateParams
      {
          Model = Model.ClaudeOpus5_5,
          MaxTokens = 1024,
          System = new MessageCreateParamsSystem(new List<TextBlockParam>
          {
              new TextBlockParam()
              {
                  Text = "You are an AI assistant tasked with analyzing legal documents.",
              },
              new TextBlockParam()
              {
                  Text = "Here is the full text of a complex legal agreement: [Insert full text of a 50-page legal agreement here]",
                  CacheControl = new CacheControlEphemeral(),
              },
          }),
          Messages =
          [
              new UserMessageParam
              {
                  Content = "What are the key terms and conditions in this agreement?"
              }
          ]
      };

      var message = await client.Messages.Create(parameters);
      Console.WriteLine(message.Usage);
      ```

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

      response, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
      	Model:     anthropic.ModelClaudeOpus5_5,
      	MaxTokens: 1024,
      	System: []anthropic.TextBlockParam{
      		{
      			Text: "You are an AI assistant tasked with analyzing legal documents.",
      		},
      		{
      			Text:         "Here is the full text of a complex legal agreement: [Insert full text of a 50-page legal agreement here]",
      			CacheControl: anthropic.NewCacheControlEphemeralParam(),
      		},
      	},
      	Messages: []anthropic.MessageParam{
      		anthropic.NewUserMessage(anthropic.NewTextBlock("What are the key terms and conditions in this agreement?")),
      	},
      })
      if err != nil {
      	log.Fatal(err)
      }
      fmt.Println(response.Usage.RawJSON())
      ```

      ```java Java
      import com.anthropic.models.messages.CacheControlEphemeral;
      // ...
      void main() {
          AnthropicClient client = AnthropicOkHttpClient.fromEnv();

          MessageCreateParams params = MessageCreateParams.builder()
              .model(Model.CLAUDE_OPUS_5_5)
              .maxTokens(1024)
              .systemOfTextBlockParams(
                  List.of(
                      TextBlockParam.builder()
                          .text("You are an AI assistant tasked with analyzing legal documents.")
                          .build(),
                      TextBlockParam.builder()
                          .text(
                              "Here is the full text of a complex legal agreement: [Insert full text of a 50-page legal agreement here]"
                          )
                          .cacheControl(CacheControlEphemeral.builder().build())
                          .build()
                  )
              )
              .addUserMessage("What are the key terms and conditions in this agreement?")
              .build();

          Message message = client.messages().create(params);
          IO.println(message.usage());
      }
      ```

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

      $message = $client->messages->create(
          maxTokens: 1024,
          messages: [
              [
                  'role' => 'user',
                  'content' => 'What are the key terms and conditions in this agreement?'
              ]
          ],
          model: Model::CLAUDE_OPUS_5_5,
          system: [
              [
                  'type' => 'text',
                  'text' => 'You are an AI assistant tasked with analyzing legal documents.'
              ],
              [
                  'type' => 'text',
                  'text' => 'Here is the full text of a complex legal agreement: [Insert full text of a 50-page legal agreement here]',
                  'cache_control' => ['type' => 'ephemeral']
              ]
          ],
      );

      echo json_encode($message->usage), PHP_EOL;
      ```

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

      message = client.messages.create(
        model: Anthropic::Model::CLAUDE_OPUS_5_5,
        max_tokens: 1024,
        system_: [
          {
            type: "text",
            text: "You are an AI assistant tasked with analyzing legal documents."
          },
          {
            type: "text",
            text: "Here is the full text of a complex legal agreement: [Insert full text of a 50-page legal agreement here]",
            cache_control: { type: "ephemeral" }
          }
        ],
        messages: [
          {
            role: "user",
            content: "What are the key terms and conditions in this agreement?"
          }
        ]
      )
      puts message.usage
      ```
    </CodeGroup>

    この例では、プロンプトキャッシングの基本的な使い方を示しています。法的契約書の全文をプレフィックスとしてキャッシュし、ユーザーの指示はキャッシュしないままにしています。

    最初のリクエストの場合：

    * `input_tokens`：ユーザーメッセージのみのトークン数
    * `cache_creation_input_tokens`：法的文書を含むシステムメッセージ全体のトークン数
    * `cache_read_input_tokens`：0（最初のリクエストではキャッシュヒットなし）

    キャッシュの有効期間内の後続リクエストの場合：

    * `input_tokens`：ユーザーメッセージのみのトークン数
    * `cache_creation_input_tokens`：0（新しいキャッシュ作成なし）
    * `cache_read_input_tokens`：キャッシュされたシステムメッセージ全体のトークン数
  </Accordion>

  <Accordion title="ツール定義のキャッシング">
    ツール定義は、`tools`配列の最後のツールに`cache_control`を配置することでキャッシュできます。そのツールまでに定義されたすべてのツール（そのツールを含む）が単一のプレフィックスとしてキャッシュされます。

    ```json
    {
      "model": "claude-opus-5-5",
      "max_tokens": 1024,
      "tools": [
        {
          "name": "get_weather",
          "description": "Get the current weather in a given location",
          "input_schema": {
            "type": "object",
            "properties": { "location": { "type": "string" } },
            "required": ["location"]
          }
        },
        {
          "name": "get_time",
          "description": "Get the current time in a given time zone",
          "input_schema": {
            "type": "object",
            "properties": { "timezone": { "type": "string" } },
            "required": ["timezone"]
          },
          "cache_control": { "type": "ephemeral" }
        }
      ],
      "messages": [{ "role": "user", "content": "What is the weather and time in New York?" }]
    }
    ```

    最初のリクエストでは、`cache_creation_input_tokens`にすべてのツール定義のトークン数が反映されます。キャッシュの有効期間内の後続リクエストでは、それらのトークンは代わりに`cache_read_input_tokens`に表示されます。

    ツール定義、`defer_loading`、キャッシュ無効化の間の詳細な相互作用については、[プロンプトキャッシングを使用したツール使用](https://platform.claude.com/docs/ja/agents-and-tools/tool-use/tool-use-with-prompt-caching)を参照してください。
  </Accordion>

  <Accordion title="マルチターン会話の継続">
    <CodeGroup>
      ```bash cURL
      curl https://api.anthropic.com/v1/messages \
        -H "x-api-key: $ANTHROPIC_API_KEY" \
        -H "anthropic-version: 2026-10-21" \
        -H "content-type: application/json" \
        -d '{
          "model": "claude-opus-5-5",
          "max_tokens": 1024,
          "system": [
            {
              "type": "text",
              "text": "...long system prompt",
              "cache_control": {"type": "ephemeral"}
            }
          ],
          "messages": [
            {
              "role": "user",
              "content": [
                {
                  "type": "text",
                  "text": "Hello, can you tell me more about the solar system?"
                }
              ]
            },
            {
              "role": "assistant",
              "content": "Certainly! The solar system is the collection of celestial bodies that orbit our Sun. It consists of eight planets, numerous moons, asteroids, comets, and other objects. The planets, in order from closest to farthest from the Sun, are: Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, and Neptune. Each planet has its own unique characteristics and features. Is there a specific aspect of the solar system you would like to know more about?"
            },
            {
              "role": "user",
              "content": [
                {
                  "type": "text",
                  "text": "Good to know."
                },
                {
                  "type": "text",
                  "text": "Tell me more about Mars.",
                  "cache_control": {"type": "ephemeral"}
                }
              ]
            }
          ]
        }'
      ```

      ```bash CLI
      ant messages create <<'YAML'
      model: claude-opus-5-5
      max_tokens: 1024
      system:
        - type: text
          text: "...long system prompt"
          cache_control:
            type: ephemeral
      messages:
        - role: user
          content:
            - type: text
              text: Hello, can you tell me more about the solar system?
        - role: assistant
          content: >-
            Certainly! The solar system is the collection of celestial bodies that
            orbit our Sun. It consists of eight planets, numerous moons, asteroids,
            comets, and other objects. The planets, in order from closest to farthest
            from the Sun, are: Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus,
            and Neptune. Each planet has its own unique characteristics and features.
            Is there a specific aspect of the solar system you would like to know
            more about?
        - role: user
          content:
            - type: text
              text: Good to know.
            - type: text
              text: Tell me more about Mars.
              cache_control:
                type: ephemeral
      YAML
      ```

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

      response = client.messages.create(
          model="claude-opus-5-5",
          max_tokens=1024,
          system=[
              {
                  "type": "text",
                  "text": "...long system prompt",
                  "cache_control": {"type": "ephemeral"},
              }
          ],
          messages=[
              # ...これまでの長い会話
              {
                  "role": "user",
                  "content": [
                      {
                          "type": "text",
                          "text": "Hello, can you tell me more about the solar system?",
                      }
                  ],
              },
              {
                  "role": "assistant",
                  "content": "Certainly! The solar system is the collection of celestial bodies that orbit our Sun. It consists of eight planets, numerous moons, asteroids, comets, and other objects. The planets, in order from closest to farthest from the Sun, are: Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, and Neptune. Each planet has its own unique characteristics and features. Is there a specific aspect of the solar system you'd like to know more about?",
              },
              {
                  "role": "user",
                  "content": [
                      {"type": "text", "text": "Good to know."},
                      {
                          "type": "text",
                          "text": "Tell me more about Mars.",
                          "cache_control": {"type": "ephemeral"},
                      },
                  ],
              },
          ],
      )
      print(response.usage.model_dump_json())
      ```

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

      const response = await client.messages.create({
        model: "claude-opus-5-5",
        max_tokens: 1024,
        system: [
          {
            type: "text",
            text: "...long system prompt",
            cache_control: { type: "ephemeral" }
          }
        ],
        messages: [
          // ...これまでの長い会話
          {
            role: "user",
            content: [
              {
                type: "text",
                text: "Hello, can you tell me more about the solar system?"
              }
            ]
          },
          {
            role: "assistant",
            content:
              "Certainly! The solar system is the collection of celestial bodies that orbit our Sun. It consists of eight planets, numerous moons, asteroids, comets, and other objects. The planets, in order from closest to farthest from the Sun, are: Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, and Neptune. Each planet has its own unique characteristics and features. Is there a specific aspect of the solar system you'd like to know more about?"
          },
          {
            role: "user",
            content: [
              {
                type: "text",
                text: "Good to know."
              },
              {
                type: "text",
                text: "Tell me more about Mars.",
                cache_control: { type: "ephemeral" }
              }
            ]
          }
        ]
      });
      console.log(response.usage);
      ```

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

      var parameters = new MessageCreateParams
      {
          Model = Model.ClaudeOpus5_5,
          MaxTokens = 1024,
          System = new MessageCreateParamsSystem(new List<TextBlockParam>
          {
              new TextBlockParam()
              {
                  Text = "...long system prompt",
                  CacheControl = new CacheControlEphemeral(),
              },
          }),
          Messages =
          [
              new UserMessageParam
              {
                  Content = new List<ContentBlockParam>
                  {
                      new ContentBlockParam(new TextBlockParam("Hello, can you tell me more about the solar system?")),
                  },
              },
              new AssistantMessageParam
              {
                  Content = "Certainly! The solar system is the collection of celestial bodies that orbit our Sun. It consists of eight planets, numerous moons, asteroids, comets, and other objects. The planets, in order from closest to farthest from the Sun, are: Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, and Neptune. Each planet has its own unique characteristics and features. Is there a specific aspect of the solar system you would like to know more about?"
              },
              new UserMessageParam
              {
                  Content = new List<ContentBlockParam>
                  {
                      new ContentBlockParam(new TextBlockParam("Good to know.")),
                      new ContentBlockParam(new TextBlockParam()
                      {
                          Text = "Tell me more about Mars.",
                          CacheControl = new CacheControlEphemeral(),
                      }),
                  }
              }
          ]
      };

      var message = await client.Messages.Create(parameters);
      Console.WriteLine(message.Usage);
      ```

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

      response, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
      	Model:     anthropic.ModelClaudeOpus5_5,
      	MaxTokens: 1024,
      	System: []anthropic.TextBlockParam{
      		{
      			Text:         "...long system prompt",
      			CacheControl: anthropic.NewCacheControlEphemeralParam(),
      		},
      	},
      	Messages: []anthropic.MessageParam{
      		anthropic.NewUserMessage(anthropic.NewTextBlock("Hello, can you tell me more about the solar system?")),
      		anthropic.NewAssistantMessage(anthropic.NewTextBlock("Certainly! The solar system is the collection of celestial bodies that orbit our Sun. It consists of eight planets, numerous moons, asteroids, comets, and other objects. The planets, in order from closest to farthest from the Sun, are: Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, and Neptune. Each planet has its own unique characteristics and features. Is there a specific aspect of the solar system you would like to know more about?")),
      		anthropic.NewUserMessage(
      			anthropic.NewTextBlock("Good to know."),
      			anthropic.ContentBlockParamUnion{OfText: &anthropic.TextBlockParam{
      				Text:         "Tell me more about Mars.",
      				CacheControl: anthropic.NewCacheControlEphemeralParam(),
      			}},
      		),
      	},
      })
      if err != nil {
      	log.Fatal(err)
      }
      fmt.Println(response.Usage.RawJSON())
      ```

      ```java Java
      import com.anthropic.models.messages.CacheControlEphemeral;
      // ...
      void main() {
          AnthropicClient client = AnthropicOkHttpClient.fromEnv();

          // 一時的なシステムプロンプトを作成
          TextBlockParam systemPrompt = TextBlockParam.builder()
              .text("...long system prompt")
              .cacheControl(CacheControlEphemeral.builder().build())
              .build();

          // メッセージパラメータを作成
          MessageCreateParams params = MessageCreateParams.builder()
              .model(Model.CLAUDE_OPUS_5_5)
              .maxTokens(1024)
              .systemOfTextBlockParams(List.of(systemPrompt))
              // 最初のユーザーメッセージ（キャッシュ制御なし）
              .addUserMessage("Hello, can you tell me more about the solar system?")
              // アシスタントの応答
              .addAssistantMessage(
                  "Certainly! The solar system is the collection of celestial bodies that orbit our Sun. It consists of eight planets, numerous moons, asteroids, comets, and other objects. The planets, in order from closest to farthest from the Sun, are: Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, and Neptune. Each planet has its own unique characteristics and features. Is there a specific aspect of the solar system you would like to know more about?"
              )
              // 2番目のユーザーメッセージ（キャッシュ制御あり）
              .addUserMessageOfContentBlockParams(
                  List.of(
                      ContentBlockParam.ofText(TextBlockParam.builder()
                          .text("Good to know.")
                          .build()),
                      ContentBlockParam.ofText(
                          TextBlockParam.builder()
                              .text("Tell me more about Mars.")
                              .cacheControl(CacheControlEphemeral.builder().build())
                              .build()
                      )
                  )
              )
              .build();

          Message message = client.messages().create(params);
          IO.println(message.usage());
      }
      ```

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

      $message = $client->messages->create(
          maxTokens: 1024,
          messages: [
              [
                  'role' => 'user',
                  'content' => [
                      [
                          'type' => 'text',
                          'text' => 'Hello, can you tell me more about the solar system?'
                      ]
                  ]
              ],
              [
                  'role' => 'assistant',
                  'content' => 'Certainly! The solar system is the collection of celestial bodies that orbit our Sun. It consists of eight planets, numerous moons, asteroids, comets, and other objects. The planets, in order from closest to farthest from the Sun, are: Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, and Neptune. Each planet has its own unique characteristics and features. Is there a specific aspect of the solar system you would like to know more about?'
              ],
              [
                  'role' => 'user',
                  'content' => [
                      ['type' => 'text', 'text' => 'Good to know.'],
                      [
                          'type' => 'text',
                          'text' => 'Tell me more about Mars.',
                          'cache_control' => ['type' => 'ephemeral']
                      ]
                  ]
              ]
          ],
          model: Model::CLAUDE_OPUS_5_5,
          system: [
              [
                  'type' => 'text',
                  'text' => '...long system prompt',
                  'cache_control' => ['type' => 'ephemeral']
              ]
          ],
      );

      echo json_encode($message->usage), PHP_EOL;
      ```

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

      message = client.messages.create(
        model: Anthropic::Model::CLAUDE_OPUS_5_5,
        max_tokens: 1024,
        system_: [
          {
            type: "text",
            text: "...long system prompt",
            cache_control: { type: "ephemeral" }
          }
        ],
        messages: [
          {
            role: "user",
            content: [
              {
                type: "text",
                text: "Hello, can you tell me more about the solar system?"
              }
            ]
          },
          {
            role: "assistant",
            content: "Certainly! The solar system is the collection of celestial bodies that orbit our Sun. It consists of eight planets, numerous moons, asteroids, comets, and other objects. The planets, in order from closest to farthest from the Sun, are: Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, and Neptune. Each planet has its own unique characteristics and features. Is there a specific aspect of the solar system you would like to know more about?"
          },
          {
            role: "user",
            content: [
              { type: "text", text: "Good to know." },
              {
                type: "text",
                text: "Tell me more about Mars.",
                cache_control: { type: "ephemeral" }
              }
            ]
          }
        ]
      )
      puts message.usage
      ```
    </CodeGroup>

    この例では、マルチターン会話でプロンプトキャッシングを使用する方法を示しています。

    各ターンで、最後のメッセージの最後のブロックに`cache_control`をマークすることで、会話を段階的にキャッシュできます。システムは、後続のメッセージに対して、以前にキャッシュされたブロックの最長のシーケンスを自動的に検索して使用します。以前のターンで`cache_control`がマークされたブロックは再度マークされませんが、5分以内のリクエストは引き続きそれらをキャッシュから読み取り、その有効期間をリフレッシュします。

    `cache_control`パラメータはシステムメッセージにも配置されています。システムメッセージが5分以上使用されずにキャッシュから削除された場合、次のリクエストで再びキャッシュに追加されます。

    このアプローチは、同じ情報を繰り返し処理することなく、進行中の会話でコンテキストを維持するのに役立ちます。

    これが正しく設定されていれば、各リクエストのusageレスポンスに以下が表示されるはずです。

    * `input_tokens`：新しいユーザーメッセージのトークン数（最小限）
    * `cache_creation_input_tokens`：新しいアシスタントターンとユーザーターンのトークン数
    * `cache_read_input_tokens`：前のターンまでの会話のトークン数
  </Accordion>

  <Accordion title="すべてを組み合わせる：複数のキャッシュブレークポイント">
    <CodeGroup>
      ```bash cURL
      curl https://api.anthropic.com/v1/messages \
        -H "x-api-key: $ANTHROPIC_API_KEY" \
        -H "anthropic-version: 2026-10-21" \
        -H "content-type: application/json" \
        -d '{
          "model": "claude-opus-5-5",
          "max_tokens": 1024,
          "tools": [
            {
              "name": "search_documents",
              "description": "Search through the knowledge base",
              "input_schema": {
                "type": "object",
                "properties": {
                  "query": {
                    "type": "string",
                    "description": "Search query"
                  }
                },
                "required": ["query"]
              }
            },
            {
              "name": "get_document",
              "description": "Retrieve a specific document by ID",
              "input_schema": {
                "type": "object",
                "properties": {
                  "doc_id": {
                    "type": "string",
                    "description": "Document ID"
                  }
                },
                "required": ["doc_id"]
              },
              "cache_control": {"type": "ephemeral"}
            }
          ],
          "system": [
            {
              "type": "text",
              "text": "You are a helpful research assistant with access to a document knowledge base.\n\n# Instructions\n- Always search for relevant documents before answering\n- Provide citations for your sources\n- Be objective and accurate in your responses\n- If multiple documents contain relevant information, synthesize them\n- Acknowledge when information is not available in the knowledge base",
              "cache_control": {"type": "ephemeral"}
            },
            {
              "type": "text",
              "text": "# Knowledge Base Context\n\nHere are the relevant documents for this conversation:\n\n## Document 1: Solar System Overview\nThe solar system consists of the Sun and all objects that orbit it...\n\n## Document 2: Planetary Characteristics\nEach planet has unique features. Mercury is the smallest planet...\n\n## Document 3: Mars Exploration\nMars has been a target of exploration for decades...\n\n[Additional documents...]",
              "cache_control": {"type": "ephemeral"}
            }
          ],
          "messages": [
            {
              "role": "user",
              "content": "Can you search for information about Mars rovers?"
            },
            {
              "role": "assistant",
              "content": [
                {
                  "type": "tool_use",
                  "id": "tool_1",
                  "name": "search_documents",
                  "input": {"query": "Mars rovers"}
                }
              ]
            },
            {
              "role": "user",
              "content": [
                {
                  "type": "tool_result",
                  "tool_use_id": "tool_1",
                  "content": "Found 3 relevant documents: Document 3 (Mars Exploration), Document 7 (Rover Technology), Document 9 (Mission History)"
                }
              ]
            },
            {
              "role": "assistant",
              "content": [
                {
                  "type": "text",
                  "text": "I found 3 relevant documents about Mars rovers. Let me get more details from the Mars Exploration document."
                }
              ]
            },
            {
              "role": "user",
              "content": [
                {
                  "type": "text",
                  "text": "Yes, please tell me about the Perseverance rover specifically.",
                  "cache_control": {"type": "ephemeral"}
                }
              ]
            }
          ]
        }'
      ```

      ```bash CLI
      ant messages create <<'YAML'
      model: claude-opus-5-5
      max_tokens: 1024
      tools:
        - name: search_documents
          description: Search through the knowledge base
          input_schema:
            type: object
            properties:
              query:
                type: string
                description: Search query
            required: [query]
        - name: get_document
          description: Retrieve a specific document by ID
          input_schema:
            type: object
            properties:
              doc_id:
                type: string
                description: Document ID
            required: [doc_id]
          cache_control:
            type: ephemeral
      system:
        - type: text
          text: |-
            You are a helpful research assistant with access to a document knowledge base.

            # Instructions
            - Always search for relevant documents before answering
            - Provide citations for your sources
            - Be objective and accurate in your responses
            - If multiple documents contain relevant information, synthesize them
            - Acknowledge when information is not available in the knowledge base
          cache_control:
            type: ephemeral
        - type: text
          text: |-
            # Knowledge Base Context

            Here are the relevant documents for this conversation:

            ## Document 1: Solar System Overview
            The solar system consists of the Sun and all objects that orbit it...

            ## Document 2: Planetary Characteristics
            Each planet has unique features. Mercury is the smallest planet...

            ## Document 3: Mars Exploration
            Mars has been a target of exploration for decades...

            [Additional documents...]
          cache_control:
            type: ephemeral
      messages:
        - role: user
          content: Can you search for information about Mars rovers?
        - role: assistant
          content:
            - type: tool_use
              id: tool_1
              name: search_documents
              input:
                query: Mars rovers
        - role: user
          content:
            - type: tool_result
              tool_use_id: tool_1
              content: >-
                Found 3 relevant documents: Document 3 (Mars Exploration),
                Document 7 (Rover Technology), Document 9 (Mission History)
        - role: assistant
          content:
            - type: text
              text: >-
                I found 3 relevant documents about Mars rovers. Let me get more
                details from the Mars Exploration document.
        - role: user
          content:
            - type: text
              text: Yes, please tell me about the Perseverance rover specifically.
              cache_control:
                type: ephemeral
      YAML
      ```

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

      response = client.messages.create(
          model="claude-opus-5-5",
          max_tokens=1024,
          tools=[
              {
                  "name": "search_documents",
                  "description": "Search through the knowledge base",
                  "input_schema": {
                      "type": "object",
                      "properties": {
                          "query": {"type": "string", "description": "Search query"}
                      },
                      "required": ["query"],
                  },
              },
              {
                  "name": "get_document",
                  "description": "Retrieve a specific document by ID",
                  "input_schema": {
                      "type": "object",
                      "properties": {
                          "doc_id": {"type": "string", "description": "Document ID"}
                      },
                      "required": ["doc_id"],
                  },
                  "cache_control": {"type": "ephemeral"},
              },
          ],
          system=[
              {
                  "type": "text",
                  "text": "You are a helpful research assistant with access to a document knowledge base.\n\n# Instructions\n- Always search for relevant documents before answering\n- Provide citations for your sources\n- Be objective and accurate in your responses\n- If multiple documents contain relevant information, synthesize them\n- Acknowledge when information is not available in the knowledge base",
                  "cache_control": {"type": "ephemeral"},
              },
              {
                  "type": "text",
                  "text": "# Knowledge Base Context\n\nHere are the relevant documents for this conversation:\n\n## Document 1: Solar System Overview\nThe solar system consists of the Sun and all objects that orbit it...\n\n## Document 2: Planetary Characteristics\nEach planet has unique features. Mercury is the smallest planet...\n\n## Document 3: Mars Exploration\nMars has been a target of exploration for decades...\n\n[Additional documents...]",
                  "cache_control": {"type": "ephemeral"},
              },
          ],
          messages=[
              {
                  "role": "user",
                  "content": "Can you search for information about Mars rovers?",
              },
              {
                  "role": "assistant",
                  "content": [
                      {
                          "type": "tool_use",
                          "id": "tool_1",
                          "name": "search_documents",
                          "input": {"query": "Mars rovers"},
                      }
                  ],
              },
              {
                  "role": "user",
                  "content": [
                      {
                          "type": "tool_result",
                          "tool_use_id": "tool_1",
                          "content": "Found 3 relevant documents: Document 3 (Mars Exploration), Document 7 (Rover Technology), Document 9 (Mission History)",
                      }
                  ],
              },
              {
                  "role": "assistant",
                  "content": [
                      {
                          "type": "text",
                          "text": "I found 3 relevant documents about Mars rovers. Let me get more details from the Mars Exploration document.",
                      }
                  ],
              },
              {
                  "role": "user",
                  "content": [
                      {
                          "type": "text",
                          "text": "Yes, please tell me about the Perseverance rover specifically.",
                          "cache_control": {"type": "ephemeral"},
                      }
                  ],
              },
          ],
      )
      print(response.usage.model_dump_json())
      ```

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

      const response = await client.messages.create({
        model: "claude-opus-5-5",
        max_tokens: 1024,
        tools: [
          {
            name: "search_documents",
            description: "Search through the knowledge base",
            input_schema: {
              type: "object",
              properties: {
                query: {
                  type: "string",
                  description: "Search query"
                }
              },
              required: ["query"]
            }
          },
          {
            name: "get_document",
            description: "Retrieve a specific document by ID",
            input_schema: {
              type: "object",
              properties: {
                doc_id: {
                  type: "string",
                  description: "Document ID"
                }
              },
              required: ["doc_id"]
            },
            cache_control: { type: "ephemeral" }
          }
        ],
        system: [
          {
            type: "text",
            text: "You are a helpful research assistant with access to a document knowledge base.\n\n# Instructions\n- Always search for relevant documents before answering\n- Provide citations for your sources\n- Be objective and accurate in your responses\n- If multiple documents contain relevant information, synthesize them\n- Acknowledge when information is not available in the knowledge base",
            cache_control: { type: "ephemeral" }
          },
          {
            type: "text",
            text: "# Knowledge Base Context\n\nHere are the relevant documents for this conversation:\n\n## Document 1: Solar System Overview\nThe solar system consists of the Sun and all objects that orbit it...\n\n## Document 2: Planetary Characteristics\nEach planet has unique features. Mercury is the smallest planet...\n\n## Document 3: Mars Exploration\nMars has been a target of exploration for decades...\n\n[Additional documents...]",
            cache_control: { type: "ephemeral" }
          }
        ],
        messages: [
          {
            role: "user",
            content: "Can you search for information about Mars rovers?"
          },
          {
            role: "assistant",
            content: [
              {
                type: "tool_use",
                id: "tool_1",
                name: "search_documents",
                input: { query: "Mars rovers" }
              }
            ]
          },
          {
            role: "user",
            content: [
              {
                type: "tool_result",
                tool_use_id: "tool_1",
                content:
                  "Found 3 relevant documents: Document 3 (Mars Exploration), Document 7 (Rover Technology), Document 9 (Mission History)"
              }
            ]
          },
          {
            role: "assistant",
            content: [
              {
                type: "text",
                text: "I found 3 relevant documents about Mars rovers. Let me get more details from the Mars Exploration document."
              }
            ]
          },
          {
            role: "user",
            content: [
              {
                type: "text",
                text: "Yes, please tell me about the Perseverance rover specifically.",
                cache_control: { type: "ephemeral" }
              }
            ]
          }
        ]
      });
      console.log(response.usage);
      ```

      ```csharp C#
      AnthropicClient client = new()
      {
          ApiKey = Environment.GetEnvironmentVariable("ANTHROPIC_API_KEY")
      };

      var parameters = new MessageCreateParams
      {
          Model = Model.ClaudeOpus5_5,
          MaxTokens = 1024,
          Tools =
          [
              new ToolUnion(new Tool()
              {
                  Name = "search_documents",
                  Description = "Search through the knowledge base",
                  InputSchema = new InputSchema()
                  {
                      Properties = new Dictionary<string, JsonElement>
                      {
                          ["query"] = JsonSerializer.SerializeToElement(new { type = "string", description = "Search query" }),
                      },
                      Required = ["query"],
                  },
              }),
              new ToolUnion(new Tool()
              {
                  Name = "get_document",
                  Description = "Retrieve a specific document by ID",
                  InputSchema = new InputSchema()
                  {
                      Properties = new Dictionary<string, JsonElement>
                      {
                          ["doc_id"] = JsonSerializer.SerializeToElement(new { type = "string", description = "Document ID" }),
                      },
                      Required = ["doc_id"],
                  },
                  CacheControl = new CacheControlEphemeral(),
              }),
          ],
          System = new MessageCreateParamsSystem(new List<TextBlockParam>
          {
              new TextBlockParam()
              {
                  Text = "You are a helpful research assistant with access to a document knowledge base.\n\n# Instructions\n- Always search for relevant documents before answering\n- Provide citations for your sources\n- Be objective and accurate in your responses\n- If multiple documents contain relevant information, synthesize them\n- Acknowledge when information is not available in the knowledge base",
                  CacheControl = new CacheControlEphemeral(),
              },
              new TextBlockParam()
              {
                  Text = "# Knowledge Base Context\n\nHere are the relevant documents for this conversation:\n\n## Document 1: Solar System Overview\nThe solar system consists of the Sun and all objects that orbit it...\n\n## Document 2: Planetary Characteristics\nEach planet has unique features. Mercury is the smallest planet...\n\n## Document 3: Mars Exploration\nMars has been a target of exploration for decades...\n\n[Additional documents...]",
                  CacheControl = new CacheControlEphemeral(),
              },
          }),
          Messages =
          [
              new UserMessageParam { Content = "Can you search for information about Mars rovers?" },
              new AssistantMessageParam
              {
                  Content = new List<ContentBlockParam>
                  {
                      new ContentBlockParam(new ToolUseBlockParam()
                      {
                          ID = "tool_1",
                          Name = "search_documents",
                          Input = new Dictionary<string, JsonElement>
                          {
                              ["query"] = JsonSerializer.SerializeToElement("Mars rovers"),
                          },
                      }),
                  },
              },
              new UserMessageParam
              {
                  Content = new List<ContentBlockParam>
                  {
                      new ContentBlockParam(new ToolResultBlockParam()
                      {
                          ToolUseID = "tool_1",
                          Content = "Found 3 relevant documents: Document 3 (Mars Exploration), Document 7 (Rover Technology), Document 9 (Mission History)",
                      }),
                  },
              },
              new AssistantMessageParam
              {
                  Content = "I found 3 relevant documents about Mars rovers. Let me get more details from the Mars Exploration document.",
              },
              new UserMessageParam
              {
                  Content = new List<ContentBlockParam>
                  {
                      new ContentBlockParam(new TextBlockParam()
                      {
                          Text = "Yes, please tell me about the Perseverance rover specifically.",
                          CacheControl = new CacheControlEphemeral(),
                      }),
                  },
              },
          ]
      };

      var message = await client.Messages.Create(parameters);
      Console.WriteLine(message.Usage);
      ```

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

      response, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
      	Model:     anthropic.ModelClaudeOpus5_5,
      	MaxTokens: 1024,
      	Tools: []anthropic.ToolUnionParam{
      		{OfTool: &anthropic.ToolParam{
      			Name:        "search_documents",
      			Description: anthropic.String("Search through the knowledge base"),
      			InputSchema: anthropic.ToolInputSchemaParam{
      				Properties: map[string]any{
      					"query": map[string]any{
      						"type":        "string",
      						"description": "Search query",
      					},
      				},
      				Required: []string{"query"},
      			},
      		}},
      		{OfTool: &anthropic.ToolParam{
      			Name:        "get_document",
      			Description: anthropic.String("Retrieve a specific document by ID"),
      			InputSchema: anthropic.ToolInputSchemaParam{
      				Properties: map[string]any{
      					"doc_id": map[string]any{
      						"type":        "string",
      						"description": "Document ID",
      					},
      				},
      				Required: []string{"doc_id"},
      			},
      			CacheControl: anthropic.NewCacheControlEphemeralParam(),
      		}},
      	},
      	System: []anthropic.TextBlockParam{
      		{
      			Text:         "You are a helpful research assistant with access to a document knowledge base.\n\n# Instructions\n- Always search for relevant documents before answering\n- Provide citations for your sources\n- Be objective and accurate in your responses\n- If multiple documents contain relevant information, synthesize them\n- Acknowledge when information is not available in the knowledge base",
      			CacheControl: anthropic.NewCacheControlEphemeralParam(),
      		},
      		{
      			Text:         "# Knowledge Base Context\n\nHere are the relevant documents for this conversation:\n\n## Document 1: Solar System Overview\nThe solar system consists of the Sun and all objects that orbit it...\n\n## Document 2: Planetary Characteristics\nEach planet has unique features. Mercury is the smallest planet...\n\n## Document 3: Mars Exploration\nMars has been a target of exploration for decades...\n\n[Additional documents...]",
      			CacheControl: anthropic.NewCacheControlEphemeralParam(),
      		},
      	},
      	Messages: []anthropic.MessageParam{
      		anthropic.NewUserMessage(anthropic.NewTextBlock("Can you search for information about Mars rovers?")),
      		anthropic.NewAssistantMessage(anthropic.NewToolUseBlock(
      			"tool_1",
      			map[string]any{"query": "Mars rovers"},
      			"search_documents",
      		)),
      		anthropic.NewUserMessage(anthropic.NewToolResultBlock(
      			"tool_1",
      			"Found 3 relevant documents: Document 3 (Mars Exploration), Document 7 (Rover Technology), Document 9 (Mission History)",
      			false,
      		)),
      		anthropic.NewAssistantMessage(anthropic.NewTextBlock("I found 3 relevant documents about Mars rovers. Let me get more details from the Mars Exploration document.")),
      		anthropic.NewUserMessage(anthropic.ContentBlockParamUnion{OfText: &anthropic.TextBlockParam{
      			Text:         "Yes, please tell me about the Perseverance rover specifically.",
      			CacheControl: anthropic.NewCacheControlEphemeralParam(),
      		}}),
      	},
      })
      if err != nil {
      	log.Fatal(err)
      }
      fmt.Println(response.Usage.RawJSON())
      ```

      ```java Java
      import com.anthropic.models.messages.CacheControlEphemeral;
      // ...
      void main() {
          AnthropicClient client = AnthropicOkHttpClient.fromEnv();

          // 検索ツールのスキーマ
          InputSchema searchSchema = InputSchema.builder()
              .properties(
                  JsonValue.from(
                      Map.of("query", Map.of("type", "string", "description", "Search query"))
                  )
              )
              .putAdditionalProperty("required", JsonValue.from(List.of("query")))
              .build();

          // ドキュメント取得ツールのスキーマ
          InputSchema getDocSchema = InputSchema.builder()
              .properties(
                  JsonValue.from(
                      Map.of("doc_id", Map.of("type", "string", "description", "Document ID"))
                  )
              )
              .putAdditionalProperty("required", JsonValue.from(List.of("doc_id")))
              .build();

          MessageCreateParams params = MessageCreateParams.builder()
              .model(Model.CLAUDE_OPUS_5_5)
              .maxTokens(1024)
              // 最後のツールにキャッシュ制御を設定したツール
              .addTool(
                  Tool.builder()
                      .name("search_documents")
                      .description("Search through the knowledge base")
                      .inputSchema(searchSchema)
                      .build()
              )
              .addTool(
                  Tool.builder()
                      .name("get_document")
                      .description("Retrieve a specific document by ID")
                      .inputSchema(getDocSchema)
                      .cacheControl(CacheControlEphemeral.builder().build())
                      .build()
              )
              // 指示とコンテキストに個別にキャッシュ制御を設定したシステムプロンプト
              .systemOfTextBlockParams(
                  List.of(
                      TextBlockParam.builder()
                          .text(
                              "You are a helpful research assistant with access to a document knowledge base.\n\n# Instructions\n- Always search for relevant documents before answering\n- Provide citations for your sources\n- Be objective and accurate in your responses\n- If multiple documents contain relevant information, synthesize them\n- Acknowledge when information is not available in the knowledge base"
                          )
                          .cacheControl(CacheControlEphemeral.builder().build())
                          .build(),
                      TextBlockParam.builder()
                          .text(
                              "# Knowledge Base Context\n\nHere are the relevant documents for this conversation:\n\n## Document 1: Solar System Overview\nThe solar system consists of the Sun and all objects that orbit it...\n\n## Document 2: Planetary Characteristics\nEach planet has unique features. Mercury is the smallest planet...\n\n## Document 3: Mars Exploration\nMars has been a target of exploration for decades...\n\n[Additional documents...]"
                          )
                          .cacheControl(CacheControlEphemeral.builder().build())
                          .build()
                  )
              )
              // 会話履歴
              .addUserMessage("Can you search for information about Mars rovers?")
              .addAssistantMessageOfContentBlockParams(
                  List.of(
                      ContentBlockParam.ofToolUse(
                          ToolUseBlockParam.builder()
                              .id("tool_1")
                              .name("search_documents")
                              .input(JsonValue.from(Map.of("query", "Mars rovers")))
                              .build()
                      )
                  )
              )
              .addUserMessageOfContentBlockParams(
                  List.of(
                      ContentBlockParam.ofToolResult(
                          ToolResultBlockParam.builder()
                              .toolUseId("tool_1")
                              .content(
                                  "Found 3 relevant documents: Document 3 (Mars Exploration), Document 7 (Rover Technology), Document 9 (Mission History)"
                              )
                              .build()
                      )
                  )
              )
              .addAssistantMessageOfContentBlockParams(
                  List.of(
                      ContentBlockParam.ofText(
                          TextBlockParam.builder()
                              .text(
                                  "I found 3 relevant documents about Mars rovers. Let me get more details from the Mars Exploration document."
                              )
                              .build()
                      )
                  )
              )
              .addUserMessageOfContentBlockParams(
                  List.of(
                      ContentBlockParam.ofText(
                          TextBlockParam.builder()
                              .text("Yes, please tell me about the Perseverance rover specifically.")
                              .cacheControl(CacheControlEphemeral.builder().build())
                              .build()
                      )
                  )
              )
              .build();

          Message message = client.messages().create(params);
          IO.println(message.usage());
      }
      ```

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

      $message = $client->messages->create(
          maxTokens: 1024,
          messages: [
              [
                  'role' => 'user',
                  'content' => 'Can you search for information about Mars rovers?'
              ],
              [
                  'role' => 'assistant',
                  'content' => [
                      [
                          'type' => 'tool_use',
                          'id' => 'tool_1',
                          'name' => 'search_documents',
                          'input' => ['query' => 'Mars rovers']
                      ]
                  ]
              ],
              [
                  'role' => 'user',
                  'content' => [
                      [
                          'type' => 'tool_result',
                          'tool_use_id' => 'tool_1',
                          'content' => 'Found 3 relevant documents: Document 3 (Mars Exploration), Document 7 (Rover Technology), Document 9 (Mission History)'
                      ]
                  ]
              ],
              [
                  'role' => 'assistant',
                  'content' => [
                      [
                          'type' => 'text',
                          'text' => 'I found 3 relevant documents about Mars rovers. Let me get more details from the Mars Exploration document.'
                      ]
                  ]
              ],
              [
                  'role' => 'user',
                  'content' => [
                      [
                          'type' => 'text',
                          'text' => 'Yes, please tell me about the Perseverance rover specifically.',
                          'cache_control' => ['type' => 'ephemeral']
                      ]
                  ]
              ]
          ],
          model: Model::CLAUDE_OPUS_5_5,
          system: [
              [
                  'type' => 'text',
                  'text' => "You are a helpful research assistant with access to a document knowledge base.\n\n# Instructions\n- Always search for relevant documents before answering\n- Provide citations for your sources\n- Be objective and accurate in your responses\n- If multiple documents contain relevant information, synthesize them\n- Acknowledge when information is not available in the knowledge base",
                  'cache_control' => ['type' => 'ephemeral']
              ],
              [
                  'type' => 'text',
                  'text' => "# Knowledge Base Context\n\nHere are the relevant documents for this conversation:\n\n## Document 1: Solar System Overview\nThe solar system consists of the Sun and all objects that orbit it...\n\n## Document 2: Planetary Characteristics\nEach planet has unique features. Mercury is the smallest planet...\n\n## Document 3: Mars Exploration\nMars has been a target of exploration for decades...\n\n[Additional documents...]",
                  'cache_control' => ['type' => 'ephemeral']
              ]
          ],
          tools: [
              [
                  'name' => 'search_documents',
                  'description' => 'Search through the knowledge base',
                  'input_schema' => [
                      'type' => 'object',
                      'properties' => [
                          'query' => [
                              'type' => 'string',
                              'description' => 'Search query'
                          ]
                      ],
                      'required' => ['query']
                  ]
              ],
              [
                  'name' => 'get_document',
                  'description' => 'Retrieve a specific document by ID',
                  'input_schema' => [
                      'type' => 'object',
                      'properties' => [
                          'doc_id' => [
                              'type' => 'string',
                              'description' => 'Document ID'
                          ]
                      ],
                      'required' => ['doc_id']
                  ],
                  'cache_control' => ['type' => 'ephemeral']
              ]
          ],
      );

      echo json_encode($message->usage), PHP_EOL;
      ```

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

      message = client.messages.create(
        model: Anthropic::Model::CLAUDE_OPUS_5_5,
        max_tokens: 1024,
        tools: [
          {
            name: "search_documents",
            description: "Search through the knowledge base",
            input_schema: {
              type: "object",
              properties: {
                query: {
                  type: "string",
                  description: "Search query"
                }
              },
              required: ["query"]
            }
          },
          {
            name: "get_document",
            description: "Retrieve a specific document by ID",
            input_schema: {
              type: "object",
              properties: {
                doc_id: {
                  type: "string",
                  description: "Document ID"
                }
              },
              required: ["doc_id"]
            },
            cache_control: { type: "ephemeral" }
          }
        ],
        system_: [
          {
            type: "text",
            text: "You are a helpful research assistant with access to a document knowledge base.\n\n# Instructions\n- Always search for relevant documents before answering\n- Provide citations for your sources\n- Be objective and accurate in your responses\n- If multiple documents contain relevant information, synthesize them\n- Acknowledge when information is not available in the knowledge base",
            cache_control: { type: "ephemeral" }
          },
          {
            type: "text",
            text: "# Knowledge Base Context\n\nHere are the relevant documents for this conversation:\n\n## Document 1: Solar System Overview\nThe solar system consists of the Sun and all objects that orbit it...\n\n## Document 2: Planetary Characteristics\nEach planet has unique features. Mercury is the smallest planet...\n\n## Document 3: Mars Exploration\nMars has been a target of exploration for decades...\n\n[Additional documents...]",
            cache_control: { type: "ephemeral" }
          }
        ],
        messages: [
          {
            role: "user",
            content: "Can you search for information about Mars rovers?"
          },
          {
            role: "assistant",
            content: [
              {
                type: "tool_use",
                id: "tool_1",
                name: "search_documents",
                input: { query: "Mars rovers" }
              }
            ]
          },
          {
            role: "user",
            content: [
              {
                type: "tool_result",
                tool_use_id: "tool_1",
                content: "Found 3 relevant documents: Document 3 (Mars Exploration), Document 7 (Rover Technology), Document 9 (Mission History)"
              }
            ]
          },
          {
            role: "assistant",
            content: [
              {
                type: "text",
                text: "I found 3 relevant documents about Mars rovers. Let me get more details from the Mars Exploration document."
              }
            ]
          },
          {
            role: "user",
            content: [
              {
                type: "text",
                text: "Yes, please tell me about the Perseverance rover specifically.",
                cache_control: { type: "ephemeral" }
              }
            ]
          }
        ]
      )
      puts message.usage
      ```
    </CodeGroup>

    この包括的な例では、利用可能な4つのキャッシュブレークポイントすべてを使用して、プロンプトのさまざまな部分を最適化する方法を示しています。

    1. **ツールキャッシュ**（キャッシュブレークポイント1）：最後のツール定義にある`cache_control`パラメータによって、すべてのツール定義がキャッシュされます。

    2. **再利用可能な指示のキャッシュ**（キャッシュブレークポイント2）：システムプロンプト内の静的な指示は個別にキャッシュされます。これらの指示はリクエスト間でほとんど変更されません。

    3. **RAGコンテキストのキャッシュ**（キャッシュブレークポイント3）：ナレッジベースのドキュメントは独立してキャッシュされるため、ツールや指示のキャッシュを無効化することなくRAGドキュメントを更新できます。

    4. **会話履歴のキャッシュ**（キャッシュブレークポイント4）：最後のユーザーメッセージに`cache_control`がマークされており、会話の進行に合わせて段階的にキャッシュできます。

    このアプローチにより、最大限の柔軟性が得られます。

    * 以前の内容を変更せずに会話に新しいターンを追加した場合、4つのキャッシュセグメントすべてが再利用されます。
    * ツールと指示を変えずにRAGドキュメントを更新した場合、最初の2つのキャッシュセグメントが再利用されます。
    * ツール、指示、ドキュメントを変えずに会話を変更した場合、最初の3つのセグメントが再利用されます。
    * いずれかのブレークポイントで変更があると、そのセグメントとそれ以降のすべてが無効化されますが、それより前にキャッシュされたセグメントは有効なままです。

    最初のリクエストの場合：

    * `input_tokens`：最小限（最後のキャッシュブレークポイント以降のトークン。この例ではほぼ0）
    * `cache_creation_input_tokens`：キャッシュされたすべてのセグメントのトークン（ツール + 指示 + RAGドキュメント + 会話履歴）
    * `cache_read_input_tokens`：0（キャッシュヒットなし）

    新しいユーザーメッセージのみを含む後続リクエストの場合（例のように、4番目のブレークポイントをその新しい最後のメッセージに移動した場合）：

    * `input_tokens`：最小限（最後のキャッシュブレークポイント以降のトークン。この例ではほぼ0）
    * `cache_creation_input_tokens`：新しいユーザーメッセージと前のアシスタントターンのトークン（キャッシュされる新しい会話セグメント）
    * `cache_read_input_tokens`：以前にキャッシュされたすべてのトークン（ツール + 指示 + RAGドキュメント + 以前の会話）

    このパターンは特に以下の場合に効果的です。

    * 大規模なドキュメントコンテキストを持つRAGアプリケーション
    * 複数のツールを使用するエージェントシステム
    * コンテキストを維持する必要がある長時間の会話
    * プロンプトのさまざまな部分を独立して最適化する必要があるアプリケーション
  </Accordion>
</AccordionGroup>

## データ保持

プロンプトキャッシング（自動と明示的の両方）は「zero data retention」（ゼロデータ保持）、すなわちZDRの対象です。Anthropicは、プロンプトやClaudeの応答の生のテキストを保存しません。

キャッシュされたコンテンツのKV（キーバリュー）キャッシュ表現と暗号学的ハッシュはメモリ内にのみ保持され、保存状態（at rest）では保持されません。キャッシュエントリの最小有効期間は5分（標準）または1時間（拡張）で、その後は即時ではないものの速やかに削除されます。キャッシュエントリは組織間で分離されており、Claude API、Claude Platform on AWS、Microsoft Foundryでは、組織内のワークスペース間でも分離されています。

***

## よくある質問

<AccordionGroup>
  <Accordion title="複数のキャッシュブレークポイントが必要ですか？それとも最後に1つあれば十分ですか？">
    **ほとんどの場合、静的コンテンツの最後に1つのキャッシュブレークポイントを置けば十分です。** キャッシュの書き込みは、マークしたブロックでのみ発生します。リクエスト間で同一のままである最後のブロックにブレークポイントを配置すれば、後続のすべてのリクエストが同じエントリを読み取ります。後続のブロックがリクエストごとに変化する場合（タイムスタンプ、受信メッセージなど）は、ブレークポイントをその前、つまり最後の安定したブロックに置いてください。

    複数のブレークポイントが必要になるのは、以下の場合のみです。

    * 会話が長くなり、ブレークポイントが最後のキャッシュ書き込みから20ブロック以上先に進んで、以前のエントリがルックバックウィンドウの外に出てしまう場合
    * 更新頻度の異なるセクションを独立してキャッシュしたい場合
    * コスト最適化のために、キャッシュする内容を明示的に制御する必要がある場合

    例：システム指示（ほとんど変更されない）とRAGコンテキスト（毎日変更される）がある場合、2つのブレークポイントを使用してそれらを個別にキャッシュすることができます。
  </Accordion>

  <Accordion title="キャッシュブレークポイントによって追加のコストは発生しますか？">
    いいえ、キャッシュブレークポイント自体は無料です。支払いが発生するのは以下のみです。

    * キャッシュへのコンテンツの書き込み（5分TTLの場合、基本入力トークンより25パーセント高い）
    * キャッシュからの読み取り（[基本入力トークン価格の一部](https://platform.claude.com/docs/ja/build-with-claude/prompt-caching#pricing)）
    * キャッシュされていないコンテンツの通常の入力トークン

    ブレークポイントの数は料金に影響しません。重要なのは、キャッシュされ読み取られるコンテンツの量のみです。
  </Accordion>

  <Accordion title="usageフィールドから合計入力トークンを計算するにはどうすればよいですか？">
    usageレスポンスには3つの個別の入力トークンフィールドが含まれており、それらを合わせたものが合計入力を表します。

    ```text wrap
    total_input_tokens = cache_read_input_tokens + cache_creation_input_tokens + input_tokens
    ```

    * `cache_read_input_tokens`：キャッシュから取得されたトークン（キャッシュブレークポイントより前でキャッシュされていたすべて）
    * `cache_creation_input_tokens`：キャッシュに書き込まれる新しいトークン（キャッシュブレークポイントにおいて）
    * `input_tokens`：**最後のキャッシュブレークポイント以降**のキャッシュされていないトークン

    **重要：** `input_tokens`はすべての入力トークンを表すわけではなく、最後のキャッシュブレークポイント以降の部分のみを表します。キャッシュされたコンテンツがある場合、`input_tokens`は通常、合計入力よりもはるかに小さくなります。

    **例：** 200kトークンのドキュメントがキャッシュされ、50トークンのユーザーの質問がある場合：

    * `cache_read_input_tokens`：200,000
    * `cache_creation_input_tokens`：0
    * `input_tokens`：50
    * **合計：** 200,050トークン

    この内訳は、コストと「rate limit」（レート制限）の使用状況の両方を理解するために不可欠です。詳細については、[キャッシュパフォーマンスの追跡](https://platform.claude.com/docs/ja/build-with-claude/prompt-caching#tracking-cache-performance)を参照してください。
  </Accordion>

  <Accordion title="キャッシュの有効期間はどのくらいですか？">
    キャッシュのデフォルトの最小有効期間（TTL）は5分です。この有効期間は、キャッシュされたコンテンツが使用されるたびにリフレッシュされます。

    5分では短すぎる場合、Anthropicは[1時間のキャッシュTTL](https://platform.claude.com/docs/ja/build-with-claude/prompt-caching#1-hour-cache-duration)も提供しています。
  </Accordion>

  <Accordion title="キャッシュの有効期間はいつ開始されますか？">
    有効期間は、キャッシュエントリを書き込むまたは読み取るリクエストの開始時点から計測され、そのレスポンスの終了時点からではありません。レスポンスの生成に費やされた時間も有効期間に含まれるため、後続のリクエストがキャッシュを再利用できる時間枠は、有効期間から生成時間を差し引いたものになります。

    リクエストが長いレスポンスを生成し、次のリクエストが有効期間の経過後まで開始されない可能性がある場合は、[1時間のキャッシュTTL](https://platform.claude.com/docs/ja/build-with-claude/prompt-caching#1-hour-cache-duration)を使用してください。
  </Accordion>

  <Accordion title="キャッシュブレークポイントはいくつ使用できますか？">
    プロンプト内で最大4つのキャッシュブレークポイント（`cache_control`パラメータを使用）を定義できます。
  </Accordion>

  <Accordion title="プロンプトキャッシングはすべてのモデルで利用できますか？">
    プロンプトキャッシングは、すべての[アクティブなClaudeモデル](https://platform.claude.com/docs/ja/models/overview)でサポートされています。
  </Accordion>

  <Accordion title="プロンプトキャッシングは思考とどのように連携しますか？">
    思考パラメータを変更すると（モードの切り替え、または拡張モードでの予算の変更）、キャッシュされたメッセージプレフィックスが無効化され、思考の設定がプロンプトにレンダリングされるため、キャッシュされたシステムプロンプトやツールも無効化される可能性があります。[`output_config.effort`](https://platform.claude.com/docs/ja/build-with-claude/effort)の値も同じように動作します。

    キャッシュの無効化の詳細については、[キャッシュを無効化する要因](https://platform.claude.com/docs/ja/build-with-claude/prompt-caching#what-invalidates-the-cache)を参照してください。

    ツール使用やプロンプトキャッシングとの相互作用を含む思考の詳細については、[思考とプロンプトキャッシング](https://platform.claude.com/docs/ja/build-with-claude/thinking#thinking-and-prompt-caching)を参照してください。
  </Accordion>

  <Accordion title="プロンプトキャッシングを有効にするにはどうすればよいですか？">
    最も簡単な方法は、リクエストボディのトップレベルに`"cache_control": {"type": "ephemeral"}`を追加することです（[自動キャッシング](https://platform.claude.com/docs/ja/build-with-claude/prompt-caching#automatic-caching)）。あるいは、個々のコンテンツブロックに少なくとも1つの`cache_control`ブレークポイントを含めることもできます（[明示的なキャッシュブレークポイント](https://platform.claude.com/docs/ja/build-with-claude/prompt-caching#explicit-cache-breakpoints)）。
  </Accordion>

  <Accordion title="プロンプトキャッシングを他のAPI機能と併用できますか？">
    はい、プロンプトキャッシングはツール使用やビジョン機能など、他のAPI機能と併用できます。ただし、プロンプト内の画像の有無を変更したり、ツール使用の設定を変更したりすると、キャッシュが破棄されます。

    キャッシュの無効化の詳細については、[キャッシュを無効化する要因](https://platform.claude.com/docs/ja/build-with-claude/prompt-caching#what-invalidates-the-cache)を参照してください。
  </Accordion>

  <Accordion title="プロンプトキャッシングは料金にどのような影響を与えますか？">
    プロンプトキャッシングには独自の料金体系があります。5分のキャッシュ書き込みは基本入力トークンより25パーセント高く、1時間のキャッシュ書き込みは基本入力トークンの2倍、キャッシュヒットは[基本入力トークン価格の一部](https://platform.claude.com/docs/ja/build-with-claude/prompt-caching#pricing)の料金となり、倍率はモデルごとに設定されています。
  </Accordion>

  <Accordion title="キャッシュを手動でクリアできますか？">
    現在、キャッシュを手動でクリアする方法はありません。キャッシュされたプレフィックスは、最低5分間使用されないと自動的に期限切れになります。
  </Accordion>

  <Accordion title="キャッシング戦略の効果を追跡するにはどうすればよいですか？">
    APIレスポンスの`cache_creation_input_tokens`フィールドと`cache_read_input_tokens`フィールドを使用して、キャッシュのパフォーマンスを監視できます。
  </Accordion>

  <Accordion title="何がキャッシュを破棄する可能性がありますか？">
    新しいキャッシュエントリの作成が必要となる変更の一覧を含む、キャッシュの無効化の詳細については、[キャッシュを無効化する要因](https://platform.claude.com/docs/ja/build-with-claude/prompt-caching#what-invalidates-the-cache)を参照してください。
  </Accordion>

  <Accordion title="プロンプトキャッシングはプライバシーとデータの分離をどのように扱いますか？">
    プロンプトキャッシングは、強力なプライバシーとデータ分離の対策を備えて設計されています。

    1. キャッシュキーは、キャッシュ制御ポイントまでのプロンプトの暗号学的ハッシュを使用して生成されます。つまり、同一のプロンプトを持つリクエストのみが特定のキャッシュにアクセスできます。

    2. Claude API、Claude Platform on AWS、Microsoft Foundryでは、キャッシュは組織内のワークスペースごとに分離されます。Claude Models on Google Cloud (Google managed)とBedrockでは、キャッシュは組織ごとに分離されます。いずれの場合も、同一のプロンプトであっても、キャッシュが組織間で共有されることはありません。詳細については、[キャッシュの保存と共有](https://platform.claude.com/docs/ja/build-with-claude/prompt-caching#cache-storage-and-sharing)を参照してください。

    3. キャッシングの仕組みは、それぞれの固有の会話やコンテキストの完全性とプライバシーを維持するように設計されています。

    4. プロンプト内のどこで`cache_control`を使用しても安全です。キャッシングで読み取りを発生させるには、安定したプレフィックスの最後にブレークポイントを配置してください。リクエストごとに変化するブロック（タイムスタンプやユーザーの任意の入力など）に配置すると、毎回新しいエントリが書き込まれ、ヒットすることはありません。

    これらの対策により、プロンプトキャッシングはパフォーマンス上の利点を提供しながら、データのプライバシーとセキュリティを維持します。
  </Accordion>

  <Accordion title="Message Batches APIでプロンプトキャッシングを使用できますか？">
    はい、[Message Batches API](https://platform.claude.com/docs/ja/build-with-claude/batch-processing)リクエストでプロンプトキャッシングを使用できます。ただし、非同期のバッチリクエストは並行して任意の順序で処理される可能性があるため、キャッシュヒットはベストエフォートで提供されます。

    [1時間キャッシュ](https://platform.claude.com/docs/ja/build-with-claude/prompt-caching#1-hour-cache-duration)はキャッシュヒットの改善に役立ちます。最もコスト効率の高い使用方法は次のとおりです。

    * 共通のプレフィックスを持つメッセージリクエストのセットを収集します。
    * この共通プレフィックスと1時間のキャッシュブロックを持つ単一のリクエストでバッチリクエストを送信します。これにより、プレフィックスが1時間キャッシュに書き込まれます。
    * これが完了したらすぐに、残りのリクエストを送信します。完了したことを知るには、ジョブを監視する必要があります。

    バッチリクエストの完了には5分から1時間かかることが一般的であるため、通常は5分キャッシュを使用するよりもこの方法の方が適しています。
  </Accordion>

  <Accordion title="Pythonで`AttributeError: 'Beta' object has no attribute 'prompt_caching'`というエラーが表示されるのはなぜですか？">
    このエラーは通常、SDKをアップグレードした場合や、古いコード例を使用している場合に表示されます。プロンプトキャッシングは、ベータプレフィックスなしで`client.messages`で利用できます。以下の代わりに：

    <CodeGroup exclude="shell:cURL, shell:CLI, typescript, csharp, go, java, php, ruby">
      ```python Python
      client.beta.prompt_caching.messages.create(**params)
      ```
    </CodeGroup>

    以下を使用してください：

    <CodeGroup exclude="shell:cURL, shell:CLI, typescript, csharp, go, java, php, ruby">
      ```python Python
      client.messages.create(**params)
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="‘TypeError: Cannot read properties of undefined (reading ‘messages’)’というエラーが表示されるのはなぜですか？">
    このエラーは通常、SDKをアップグレードした場合や、古いコード例を使用している場合に表示されます。プロンプトキャッシングは、ベータプレフィックスなしで`client.messages`で利用できます。以下の代わりに：

    ```typescript TypeScript
    client.beta.promptCaching.messages.create(/* ... */);
    ```

    以下を使用してください：

    ```typescript
    client.messages.create(/* ... */);
    ```
  </Accordion>
</AccordionGroup>

## 利用可能状況

プロンプトキャッシングはAPIに応じて利用可能またはベータ版であり、ゼロデータ保持とHIPAAレディネスの対象です。

### APIサポート

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

* 利用可能状況：利用可能
* 使用方法：トップレベルまたはブロックで`cache_control`を指定して有効にします。

| ステータス | クラウドプラットフォーム          | モデル                                                            |
| ----- | --------------------- | -------------------------------------------------------------- |
| 利用可能  | サポートされているすべてのプラットフォーム | [すべてのモデル](https://platform.claude.com/docs/ja/models/overview) |

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

* 利用可能状況：常時有効
* 使用方法：キャッシュエントリの有効期間はデフォルトで5分で、キャッシュの読み取りと書き込みはセッションの使用量に表示されます。

| ステータス | クラウドプラットフォーム          | モデル                                                            |
| ----- | --------------------- | -------------------------------------------------------------- |
| ベータ   | サポートされているすべてのプラットフォーム | [すべてのモデル](https://platform.claude.com/docs/ja/models/overview) |

### データの取り扱い

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

| 項目    | ゼロデータ保持                                                                                                                                                                        | HIPAA |
| ----- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----- |
| ステータス | 対象（[対象モデル](https://platform.claude.com/docs/ja/manage-claude/api-and-data-retention#model-specific-data-retention-requirements)を除く）                                            | 対象    |
| 詳細    | プロンプトとClaudeの出力は保存されません。KVキャッシュ表現と暗号学的ハッシュはキャッシュのTTLの間メモリに保持され、期限切れ後すみやかに削除されます。 [詳細はこちら](https://platform.claude.com/docs/ja/build-with-claude/prompt-caching#data-retention) | —     |

対象エンドポイント：

* `/v1/messages`
