---
title: プロンプトキャッシング
url: https://platform.claude.com/docs/ja/build-with-claude/prompt-caching
description: "`cache_control`でプロンプトのプレフィックスをキャッシュし、自動キャッシングまたは5分間・1時間のTTLを持つ明示的なブレークポイントを使用して、コストとレイテンシを削減します。"
---

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

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

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

* **[自動キャッシング](https://platform.claude.com/docs/ja/build-with-claude/prompt-caching#automatic-caching)**：リクエストのトップレベルに`cache_control`フィールドを1つ追加します。システムは「cache breakpoint」（キャッシュブレークポイント）を最後のキャッシュ可能なブロックに自動的に適用し、会話が長くなるにつれてそれを前方に移動させます。増え続けるメッセージ履歴を自動的にキャッシュしたいマルチターン会話に最適です。
* **[明示的なキャッシュブレークポイント](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: 2023-06-01" \
    -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 --transform usage <<'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()
          {
              Role = Role.User,
              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;
  // ...
  public class PromptCachingExample {

    public static void main(String[] args) {
      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);
      System.out.println(message.usage());
    }
  }
  ```

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

  $response = $client->messages->create(
      maxTokens: 1024,
      messages: [
          ['role' => 'user', 'content' => "Analyze the major themes in 'Pride and Prejudice'."]
      ],
      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: "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.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 Bedrock and Google Cloud](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 Google Cloud](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 Bedrock and Google Cloud](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     |
| Claude Haiku 3.5 ([retired, except on Google Cloud](https://platform.claude.com/docs/ja/about-claude/model-deprecations))            | $0.80 / MTok      | $1 / MTok       | $1.60 / MTok    | $0.08 / MTok             | $4 / MTok     |

*<sup>1 Cache hits and refreshes on 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分間のキャッシュ書き込みトークンは、基本入力トークン価格の1.25倍です
  * 1時間のキャッシュ書き込みトークンは、基本入力トークン価格の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`フィールドを1つ追加します。システムはキャッシュブレークポイントを最後のキャッシュ可能なブロックに自動的に適用します。

<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: 2023-06-01" \
    -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 --transform usage <<'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()
          {
              Role = Role.User,
              Content = "My name is Alex. I work on machine learning."
          },
          new()
          {
              Role = Role.Assistant,
              Content = "Nice to meet you, Alex! How can I help with your ML work today?"
          },
          new()
          {
              Role = Role.User,
              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;
  // ...
  public class AutomaticCachingExample {

      public static void main(String[] args) {
          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);
          System.out.println(message.usage());
      }
  }
  ```

  ```php PHP
  use Anthropic\Messages\CacheControlEphemeral;
  // ...
  $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: '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: "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)** ◀ cache                                                   | すべてがキャッシュに書き込まれる                                                     |
| リクエスト2 | System<br />+ User(1) + Asst(1)<br />+ User(2) + Asst(2)<br />+ **User(3)** ◀ cache                          | 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)** ◀ cache | SystemからUser(3)まではキャッシュから読み取られる。<br />Asst(3) + User(4)はキャッシュに書き込まれる |

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

### TTLのサポート

デフォルトでは、自動キャッシングは5分間の「time to live」（有効期間）、すなわち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ブロックです。** システムはブレークポイントごとに最大20の位置を確認し、ブレークポイント自体を1つ目として数えます。そのウィンドウ内で一致するエントリが見つからない場合、確認は停止します（次の明示的なブレークポイントがあれば、そこから再開します）。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%、Claude Fable 5.1およびClaude Mythos 5.1では2.5%、Claude Opus 5.5およびClaude Sonnet 5.5では5%）
* **通常の入力トークン：** キャッシュされていないコンテンツ

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

***

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

### キャッシュの制限

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

* 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（[BedrockおよびGoogle Cloudを除き廃止済み](https://platform.claude.com/docs/ja/about-claude/model-deprecations)）、Claude Opus 4（[Google Cloudを除き廃止済み](https://platform.claude.com/docs/ja/about-claude/model-deprecations)）、およびClaude Sonnet 4（[BedrockおよびGoogle Cloudを除き廃止済み](https://platform.claude.com/docs/ja/about-claude/model-deprecations)）では1,024トークン
* Claude Haiku 4.5では4,096トークン
* Claude Haiku 3.5（[Google Cloudを除き廃止済み](https://platform.claude.com/docs/ja/about-claude/model-deprecations)）では2,048トークン

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

これより短いプロンプトは、`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)を参照してください。                                                                          |
| **破棄された思考ブロック**                  | ✓        | ✓         | ✘          | APIが、そのリクエストで[保持](https://platform.claude.com/docs/ja/build-with-claude/thinking#preserved-thinking)されないClaude Fable 5.1、Claude Mythos 5.1、Claude Opus 5.5、Claude Sonnet 5.5、またはClaude Haiku 5.5の思考ブロック（たとえば、それを読み取れないモデルに再送したもの）を破棄した場合、そのリクエストでは、キャッシュされたプレフィックスがそのブロックの位置以降で変化します。受信側のモデルが読み取れるブロックを変更せずに渡し返した場合、キャッシュはそのまま維持されます。                                                                                     |

[会話途中のツール変更](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.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`フィールドを編集する代わりに、`messages`に`{"role": "system"}`メッセージを追加することで、キャッシュされたプレフィックスは変更されないままになります。この機能は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`は通常、合計入力よりもはるかに小さくなるため、これはコストと「rate limit」（レート制限）の両方を理解するうえで重要です。
</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に適用されます。BedrockとGoogle Cloudは組織レベルのキャッシュ分離を維持しています。複数のワークスペースを使用している場合は、この違いを考慮してキャッシング戦略を見直してください。
</Warning>

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

* **完全一致：** キャッシュヒットには、cache controlでマークされたブロックまで（そのブロックを含む）のすべてのテキストと画像を含め、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)を使用してください。
* システム指示、背景情報、大きなコンテキスト、頻繁に使用するツール定義など、安定した再利用可能なコンテンツをキャッシュしてください。
* 最高のパフォーマンスを得るために、キャッシュするコンテンツはプロンプトの先頭に配置してください。
* キャッシュブレークポイントを戦略的に使用して、キャッシュ可能な異なるプレフィックスセクションを分離してください。
* リクエスト間で同一のままである最後のブロックにブレークポイントを配置してください。静的なプレフィックスと変化するサフィックス（タイムスタンプ、リクエストごとのコンテキスト、受信メッセージ）を持つプロンプトでは、それは変化するブロックではなく、プレフィックスの末尾です。
* キャッシュヒット率を定期的に分析し、必要に応じて戦略を調整してください。

### さまざまなユースケースに向けた最適化

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

* 会話型エージェント：長い会話、特に長い指示やアップロードされたドキュメントを含む会話のコストと「latency」（レイテンシ）を削減します。
* コーディングアシスタント：関連するセクションやコードベースの要約版をプロンプトに保持することで、オートコンプリートやコードベースに関する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)、[Google Cloud](https://platform.claude.com/docs/ja/build-with-claude/claude-on-vertex-ai)、[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分間のキャッシュを使用してください。5分間のキャッシュは追加料金なしで更新され続けるためです。

1時間のキャッシュは、次のようなシナリオで使用するのが最適です。

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

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

### 異なるTTLの混在

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

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

1. 位置`A`：最も後方のキャッシュヒット位置でのトークン数（ヒットがない場合は0）。
2. 位置`B`：`A`より後にある最も後方の1時間`cache_control`ブロックでのトークン数（存在しない場合は`A`と等しい）。
3. 位置`C`：最後の`cache_control`ブロックでのトークン数。

<Note>
  `B`または`C`が`A`より大きい場合、`A`が最も後方のキャッシュヒットであるため、それは必然的にキャッシュミスとなります。
</Note>

次の料金が請求されます。

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

以下に3つの例を示します。この図は3つのリクエストの入力トークンを表しており、それぞれ異なるキャッシュヒットとキャッシュミスがあります。その結果、それぞれ異なる料金が計算され、色付きのボックスに示されています。

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

***

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

「cache 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: 2023-06-01" \
    -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 \
    --transform '{stop_reason,content,usage}' --format yaml <<'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() { Role = Role.User, 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: 2023-06-01" \
    -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: 2023-06-01" \
    -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 --transform usage <<'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 --transform 'content.#(type=="text").text' --raw-output <<'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 is Anthropic.TextBlock => 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() { Role = Role.User, Content = "warmup" }],
          }
      );

  // 実際のユーザーリクエストです。ウォームキャッシュの恩恵を受けます。
  async Task<Message> Respond(string userMessage) =>
      await client.Messages.Create(
          new()
          {
              Model = Model.ClaudeOpus5_5,
              MaxTokens = 1024,
              System = new(systemPrompt),
              Messages = [new() { Role = Role.User, 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->type === 'text') {
          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.type == :text
  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` で拒否されます。これらはいずれも、トークン数0の予算では生成できない出力を前提としているためです。

* `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: 0` が利用可能になる前は、一部のアプリケーションで同じ効果を得るために `max_tokens: 1` のウォームアップ呼び出しが使用されていました。`max_tokens: 0` のアプローチが推奨されます。出力が生成されないため、破棄すべき1トークンの応答がなく、出力トークンも課金されず、リクエストの意図も明確です。

***

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

プロンプトキャッシングを始めるにあたって、[プロンプトキャッシングのクックブック](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: 2023-06-01" \
        -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 --transform usage <<'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()
              {
                  Role = Role.User,
                  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;
      // ...
      public class LegalDocumentAnalysisExample {

        public static void main(String[] args) {
          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);
          System.out.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: '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: "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: 2023-06-01" \
        -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 --transform usage <<'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()
              {
                  Role = Role.User,
                  Content = new MessageParamContent(new List<ContentBlockParam>
                  {
                      new ContentBlockParam(new TextBlockParam("Hello, can you tell me more about the solar system?")),
                  }),
              },
              new()
              {
                  Role = 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?"
              },
              new()
              {
                  Role = Role.User,
                  Content = new MessageParamContent(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?")),
      		{
      			Role: anthropic.MessageParamRoleUser,
      			Content: []anthropic.ContentBlockParamUnion{
      				anthropic.NewTextBlock("Good to know."),
      				{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;
      // ...
      public class ConversationWithCacheControlExample {

        public static void main(String[] args) {
          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))
            // 最初のユーザーメッセージ（cache control なし）
            .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 番目のユーザーメッセージ（cache control あり）
            .addUserMessageOfBlockParams(
              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);
          System.out.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: '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: "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: 2023-06-01" \
        -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 --transform usage <<'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() { Role = Role.User, Content = "Can you search for information about Mars rovers?" },
              new()
              {
                  Role = Role.Assistant,
                  Content = new MessageParamContent(new List<ContentBlockParam>
                  {
                      new ContentBlockParam(new ToolUseBlockParam()
                      {
                          ID = "tool_1",
                          Name = "search_documents",
                          Input = new Dictionary<string, JsonElement>
                          {
                              ["query"] = JsonSerializer.SerializeToElement("Mars rovers"),
                          },
                      }),
                  }),
              },
              new()
              {
                  Role = Role.User,
                  Content = new MessageParamContent(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()
              {
                  Role = Role.Assistant,
                  Content = "I found 3 relevant documents about Mars rovers. Let me get more details from the Mars Exploration document.",
              },
              new()
              {
                  Role = Role.User,
                  Content = new MessageParamContent(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.")),
      		{
      			Role: anthropic.MessageParamRoleUser,
      			Content: []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;
      // ...
      public class MultipleCacheBreakpointsExample {

        public static void main(String[] args) {
          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)
            // 最後のツールに cache control を設定したツール群
            .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()
            )
            // 指示とコンテキストにそれぞれ cache control を設定したシステムプロンプト
            .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?")
            .addAssistantMessageOfBlockParams(
              List.of(
                ContentBlockParam.ofToolUse(
                  ToolUseBlockParam.builder()
                    .id("tool_1")
                    .name("search_documents")
                    .input(JsonValue.from(Map.of("query", "Mars rovers")))
                    .build()
                )
              )
            )
            .addUserMessageOfBlockParams(
              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()
                )
              )
            )
            .addAssistantMessageOfBlockParams(
              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()
                )
              )
            )
            .addUserMessageOfBlockParams(
              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);
          System.out.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: '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: "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（key-value）キャッシュ表現と暗号学的ハッシュはメモリ内にのみ保持され、永続的に保存されることはありません。キャッシュエントリの最小有効期間は5分（標準）または1時間（拡張）で、その後、即時ではないものの速やかに削除されます。キャッシュエントリは組織間で分離されており、Claude API、Claude Platform on AWS、Microsoft Foundryでは、組織内のワークスペース間でも分離されています。

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

***

## よくある質問

<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トークン

    この内訳は、コストとレート制限の使用状況の両方を理解するうえで非常に重要です。詳細については、[キャッシュパフォーマンスの追跡](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では、キャッシュは組織内のワークスペースごとに分離されています。BedrockとGoogle Cloudでは、キャッシュは組織ごとに分離されています。いずれの場合も、同一のプロンプトであっても、キャッシュが組織間で共有されることはありません。詳細については、[キャッシュの保存と共有](https://platform.claude.com/docs/ja/build-with-claude/prompt-caching#cache-storage-and-sharing)を参照してください。

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

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

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

  <Accordion title="プロンプトキャッシングをBatches APIと併用できますか？">
    はい、[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をアップグレードした場合や、古いコード例を使用している場合に表示されます。プロンプトキャッシングでは、betaプレフィックスは不要になりました。次のコードの代わりに：

    <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をアップグレードした場合や、古いコード例を使用している場合に表示されます。プロンプトキャッシングでは、betaプレフィックスは不要になりました。次のコードの代わりに：

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

    次のコードを使用してください：

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