---
title: 프롬프트 캐싱
url: https://platform.claude.com/docs/ko/build-with-claude/prompt-caching
description: "`cache_control`로 프롬프트 접두사를 캐시하여 비용과 지연 시간을 줄이세요. 자동 캐싱을 사용하거나 5분 또는 1시간 TTL의 명시적 중단점을 사용할 수 있습니다."
---

"Prompt caching"(프롬프트 캐싱)은 프롬프트의 특정 접두사(prefix)부터 처리를 재개할 수 있게 하여 API 사용을 최적화합니다. 반복적인 작업이나 일관된 요소가 포함된 프롬프트의 처리 시간과 비용을 크게 줄여 줍니다.

<Note>
  "zero data retention"(제로 데이터 보존), 즉 ZDR이 이 기능에 어떻게 적용되는지 알아보려면 [API 및 데이터 보존](https://platform.claude.com/docs/ko/manage-claude/api-and-data-retention)을 참조하세요.
</Note>

프롬프트 캐싱을 활성화하는 방법은 두 가지입니다.

* **[자동 캐싱](https://platform.claude.com/docs/ko/build-with-claude/prompt-caching#automatic-caching)**: 요청의 최상위 수준에 `cache_control` 필드 하나를 추가합니다. 시스템이 마지막 캐시 가능 블록에 "cache breakpoint"(캐시 중단점)를 자동으로 적용하고, 대화가 길어지면 중단점을 앞으로 옮깁니다. 늘어나는 메시지 기록을 자동으로 캐시해야 하는 멀티턴 대화에 가장 적합합니다.
* **[명시적 캐시 중단점](https://platform.claude.com/docs/ko/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/ko/build-with-claude/prompt-caching#pricing)으로 제공하는 1시간 캐시 지속 시간을 사용할 수 있습니다.

  자세한 내용은 [1시간 캐시 지속 시간](https://platform.claude.com/docs/ko/build-with-claude/prompt-caching#1-hour-cache-duration)을 참조하세요.
</Note>

<Tip>
  **프롬프트 캐싱은 전체 접두사를 캐시합니다**

  프롬프트 캐싱은 `cache_control`로 지정된 블록까지(해당 블록 포함)의 전체 프롬프트, 즉 `tools`, `system`, `messages`를 이 순서대로 참조합니다.
</Tip>

***

## 가격

프롬프트 캐싱에는 새로운 가격 체계가 적용됩니다. 다음 표는 지원되는 각 모델의 백만 토큰당 가격입니다.

| 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/ko/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/ko/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/ko/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/ko/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/ko/about-claude/pricing#long-context-pricing), 데이터 레지던시 등 다른 가격 조정 요소와 중첩 적용됩니다. 프롬프트 길이에 따라 가격이 책정되는 모델에서는 캐시 읽기와 캐시 쓰기가 요청의 프롬프트 길이에 포함됩니다. 자세한 내용은 [가격](https://platform.claude.com/docs/ko/about-claude/pricing)을 참조하세요.
</Note>

***

## 지원 모델

프롬프트 캐싱(자동 및 명시적 방식 모두)은 모든 [활성 Claude 모델](https://platform.claude.com/docs/ko/models/overview)에서 지원됩니다.

***

## 자동 캐싱

자동 캐싱은 프롬프트 캐싱을 활성화하는 가장 간단한 방법입니다. 개별 콘텐츠 블록에 `cache_control`을 배치하는 대신, 요청 본문의 최상위 수준에 `cache_control` 필드 하나를 추가하면 됩니다. 시스템이 마지막 캐시 가능 블록에 캐시 중단점을 자동으로 적용합니다.

<CodeGroup>
  ```bash cURL
  curl https://api.anthropic.com/v1/messages \
    -H "content-type: application/json" \
    -H "x-api-key: $ANTHROPIC_API_KEY" \
    -H "anthropic-version: 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분 TTL을 사용합니다. 기본 입력 토큰 가격의 2배로 1시간 TTL을 지정할 수도 있습니다.

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

### 블록 수준 캐싱과 함께 사용하기

자동 캐싱은 [명시적 캐시 중단점](https://platform.claude.com/docs/ko/build-with-claude/prompt-caching#explicit-cache-breakpoints)과 함께 사용할 수 있습니다. 함께 사용하면 자동 캐시 중단점이 사용 가능한 중단점 슬롯 4개 중 하나를 차지합니다.

따라서 두 방식을 조합할 수 있습니다. 예를 들어 명시적 중단점으로 시스템 프롬프트를 캐시하고, 대화는 자동 캐싱이 처리하도록 할 수 있습니다.

```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/ko/build-with-claude/claude-on-amazon-bedrock-legacy) 통합을 제외한 모든 플랫폼에서 사용할 수 있습니다. 해당 통합에서는 최상위 `cache_control` 필드에 대해 API가 400 오류를 반환하므로, 대신 [명시적 캐시 중단점](https://platform.claude.com/docs/ko/build-with-claude/prompt-caching#explicit-cache-breakpoints)을 사용하세요.
</Note>

***

## 명시적 캐시 중단점

캐싱을 더 세밀하게 제어하려면 개별 콘텐츠 블록에 `cache_control`을 직접 배치할 수 있습니다. 변경 빈도가 서로 다른 섹션을 각각 캐시해야 하거나, 캐시할 내용을 정확하게 제어해야 할 때 유용합니다.

### 프롬프트 구성하기

정적 콘텐츠(도구 정의, 시스템 지침, 컨텍스트, 예시)는 프롬프트의 앞부분에 배치하세요. 캐싱할 재사용 가능 콘텐츠의 끝은 `cache_control` 매개변수로 표시합니다.

캐시 접두사는 `tools`, `system`, `messages` 순서로 생성됩니다. 이 순서는 각 수준이 이전 수준 위에 쌓이는 계층 구조를 이룹니다.

#### 자동 접두사 확인의 작동 방식

정적 콘텐츠의 끝에 캐시 중단점을 하나만 두어도, 시스템이 이전 요청에서 이미 캐시에 기록된 가장 긴 접두사를 자동으로 찾습니다. 이 작동 방식을 이해하면 캐싱 전략을 최적화하는 데 도움이 됩니다.

**세 가지 핵심 원칙:**

1. **캐시 쓰기는 중단점에서만 발생합니다.** 블록에 `cache_control`을 표시하면 캐시 항목이 정확히 하나 기록됩니다. 이 항목은 해당 블록에서 끝나는 접두사의 해시입니다. 시스템은 그보다 앞선 위치에는 항목을 기록하지 않습니다. 해시는 중단점까지(중단점 포함)의 모든 내용을 포괄하는 누적 값이므로, 중단점 또는 그 이전의 블록을 하나라도 변경하면 다음 요청에서 다른 해시가 생성됩니다.

2. **캐시 읽기는 이전 요청이 기록한 항목을 찾아 뒤쪽으로 탐색합니다.** 시스템은 요청마다 중단점의 접두사 해시를 계산하고 일치하는 캐시 항목이 있는지 확인합니다. 일치하는 항목이 없으면 한 번에 한 블록씩 뒤로 이동하며, 각 이전 위치의 접두사 해시가 이미 캐시에 있는 항목과 일치하는지 확인합니다. 이때 시스템이 찾는 것은 안정적인 콘텐츠가 아니라 이전에 기록된 항목입니다.

3. **룩백 윈도우는 20개 블록입니다.** 시스템은 중단점 자체를 첫 번째 위치로 세어, 중단점당 최대 20개 위치를 확인합니다. 이 윈도우 안에서 일치하는 항목을 찾지 못하면 확인을 중단합니다(다음 명시적 중단점이 있으면 그 위치에서 다시 확인합니다). Claude API에서는 연속된 `tool_use` 블록 묶음을 하나의 위치로 계산하며, 연속된 `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의 항목은 윈도우에서 한 위치 벗어나 있으므로 캐시 적중이 발생하지 않습니다. 블록 15에 두 번째 중단점을 추가하면 그 위치에서 두 번째 룩백 윈도우가 시작되어 턴 2의 항목을 찾을 수 있습니다.

**흔한 실수: 요청마다 변경되는 콘텐츠에 중단점 설정**

프롬프트가 대규모 정적 시스템 컨텍스트(블록 1\~5)와 그 뒤에 오는 요청별 블록(타임스탬프와 사용자 메시지가 포함된 블록 6)으로 구성되어 있고, 블록 6에 `cache_control`을 설정했다고 가정합니다.

* **요청 1:** 블록 6에서 캐시 쓰기가 발생합니다. 해시에는 타임스탬프가 포함됩니다.
* **요청 2:** 타임스탬프가 다르므로 블록 6의 접두사 해시도 달라집니다. 룩백이 블록 5, 4, 3, 2, 1을 차례로 확인하지만, 시스템은 이 위치들에 항목을 기록한 적이 없습니다. 캐시 적중이 발생하지 않습니다. 결국 요청마다 새 캐시 쓰기 비용만 지불하고 읽기는 한 번도 일어나지 않습니다.

룩백은 중단점 뒤쪽의 안정적인 콘텐츠를 찾아 캐시하지 않습니다. 이전 요청이 이미 기록한 항목을 찾을 뿐이며, 쓰기는 중단점에서만 발생합니다. 요청 간에 동일하게 유지되는 마지막 블록인 블록 5로 `cache_control`을 옮기면, 이후의 모든 요청이 캐시된 접두사를 읽습니다. [자동 캐싱](https://platform.claude.com/docs/ko/build-with-claude/prompt-caching#automatic-caching)도 같은 함정에 빠집니다. 자동 캐싱은 마지막 캐시 가능 블록에 중단점을 두는데, 이 구조에서는 그 블록이 요청마다 변경되는 블록이기 때문입니다. 따라서 이 경우에는 블록 5에 명시적 중단점을 사용하세요.

**핵심 요점:** 캐시를 공유하려는 요청들 사이에서 접두사가 동일한 마지막 블록에 `cache_control`을 배치하세요. 길어지는 대화에서는 각 턴에 추가되는 블록이 20개 미만이라면 마지막 블록에 두어도 됩니다. 이전 콘텐츠는 변경되지 않으므로 다음 요청의 룩백이 이전 쓰기를 찾을 수 있기 때문입니다. 접미사가 변하는 프롬프트(타임스탬프, 요청별 컨텍스트, 새로 들어오는 메시지)라면 변하는 블록이 아니라 정적 접두사의 끝에 중단점을 배치하세요.

#### 여러 중단점을 사용해야 하는 경우

다음과 같은 경우 캐시 중단점을 최대 4개까지 정의할 수 있습니다.

* 변경 빈도가 서로 다른 섹션을 각각 캐시하려는 경우(예: 도구는 거의 변경되지 않지만 컨텍스트는 매일 업데이트됨)
* 캐시할 내용을 더 정확하게 제어하려는 경우
* 길어지는 대화로 인해 중단점이 마지막 캐시 쓰기 위치보다 20개 블록 이상 뒤로 밀려나도 캐시 적중을 보장하려는 경우

<Note>
  **중요한 제한 사항:** 룩백은 이전 요청이 이미 기록한 항목만 찾을 수 있습니다. 길어지는 대화로 인해 중단점이 마지막 쓰기 위치보다 20개 블록 이상 뒤로 밀려나면 룩백 윈도우가 그 항목을 찾지 못합니다. 처음부터 해당 위치에 더 가까운 곳에 두 번째 중단점을 추가하여, 필요해지기 전에 그 위치에 쓰기가 쌓이도록 하세요.
</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/ko/build-with-claude/claude-platform-on-aws), [Google Cloud](https://platform.claude.com/docs/ko/build-with-claude/claude-on-vertex-ai), [Microsoft Foundry](https://platform.claude.com/docs/ko/build-with-claude/claude-in-microsoft-foundry)에서 캐싱 가능한 최소 프롬프트 길이는 다음과 같습니다:

* 512 토큰: Claude Fable 5.1, [Claude Mythos 5.1](https://platform.claude.com/docs/ko/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/ko/models/mythos-5/overview) 및 Claude Haiku 5.5
* 2,048 토큰: [Claude Mythos Preview](https://anthropic.com/glasswing) 및 Claude Opus 4.7
* 4,096 토큰: Claude Opus 4.6 및 Claude Opus 4.5
* 1,024 토큰: Claude Opus 4.8, Claude Sonnet 5, Claude Sonnet 4.6, Claude Sonnet 4.5([지원 중단](https://platform.claude.com/docs/ko/about-claude/model-deprecations)), Claude Opus 4.1([Bedrock 및 Google Cloud를 제외하고 종료](https://platform.claude.com/docs/ko/about-claude/model-deprecations)), Claude Opus 4([Google Cloud를 제외하고 종료](https://platform.claude.com/docs/ko/about-claude/model-deprecations)), Claude Sonnet 4([Bedrock 및 Google Cloud를 제외하고 종료](https://platform.claude.com/docs/ko/about-claude/model-deprecations))
* 4,096 토큰: Claude Haiku 4.5
* 2,048 토큰: Claude Haiku 3.5([Google Cloud를 제외하고 종료](https://platform.claude.com/docs/ko/about-claude/model-deprecations))

이러한 최솟값은 각 모델을 사용할 수 있는 모든 플랫폼에 적용됩니다.

더 짧은 프롬프트는 `cache_control`로 표시되어 있더라도 캐싱할 수 없습니다. 이 토큰 수보다 적은 양을 캐싱하려는 요청은 캐싱 없이 처리되며, 오류는 반환되지 않습니다. 프롬프트가 캐싱되었는지 확인하려면 [응답 usage 필드](https://platform.claude.com/docs/ko/build-with-claude/prompt-caching#tracking-cache-performance)를 확인하세요. `cache_creation_input_tokens`와 `cache_read_input_tokens`가 모두 0이면 프롬프트가 캐싱되지 않은 것입니다(최소 길이 요구 사항을 충족하지 못했을 가능성이 높습니다).

프롬프트가 모델 및 플랫폼의 최솟값에 약간 못 미치는 경우, 임계값에 도달하도록 캐싱되는 콘텐츠를 확장하는 것이 가치 있는 경우가 많습니다. 캐시 읽기는 캐싱되지 않은 입력 토큰보다 비용이 훨씬 적으므로, 최솟값에 도달하면 자주 재사용되는 프롬프트의 비용을 줄일 수 있습니다.

<Note>
  [Bedrock](https://platform.claude.com/docs/ko/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`로 표시하여 캐시할 수 있습니다.

### 캐시할 수 없는 항목

대부분의 요청 블록은 캐시할 수 있지만 몇 가지 예외가 있습니다.

* thinking 블록은 `cache_control`로 직접 캐시할 수 없습니다. 하지만 이전 어시스턴트 턴에 포함된 thinking 블록은 다른 콘텐츠와 함께 캐시될 수 있습니다. 이렇게 캐시된 thinking 블록은 캐시에서 읽을 때 입력 토큰으로 계산됩니다.

* 하위 콘텐츠 블록(예: [인용](https://platform.claude.com/docs/ko/build-with-claude/citations)) 자체는 직접 캐시할 수 없습니다. 대신 최상위 블록을 캐시하세요.

  인용의 경우, 인용의 원본 자료 역할을 하는 최상위 문서 콘텐츠 블록은 캐시할 수 있습니다. 인용이 참조할 문서를 캐시하면 인용과 함께 프롬프트 캐싱을 효과적으로 사용할 수 있습니다.

* 빈 텍스트 블록은 캐시할 수 없습니다.

### 캐시를 무효화하는 요인

캐싱된 콘텐츠를 수정하면 캐시의 일부 또는 전체가 무효화될 수 있습니다.

[프롬프트 구성하기](https://platform.claude.com/docs/ko/build-with-claude/prompt-caching#structuring-your-prompt)에서 설명한 것처럼, 캐시는 `tools` → `system` → `messages` 계층 구조를 따릅니다. 각 수준에서의 변경은 해당 수준과 그 이후의 모든 수준을 무효화합니다.

다음 표는 다양한 유형의 변경으로 인해 캐시의 어느 부분이 무효화되는지 보여줍니다. ✘는 캐시가 무효화됨을, ✓는 캐시가 유효하게 유지됨을 나타냅니다.

| 변경 사항                             | 도구 캐시  | 시스템 캐시 | 메시지 캐시 | 영향                                                                                                                                                                                                                                                                                                                                                                                                                         |
| --------------------------------- | ------ | ------ | ------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **도구 정의**                         | ✘      | ✘      | ✘      | 도구 정의(이름, 설명, 매개변수)를 수정하면 전체 캐시가 무효화됩니다                                                                                                                                                                                                                                                                                                                                                                                    |
| **웹 검색 토글**                       | ✓      | ✘      | ✘      | 웹 검색을 활성화/비활성화하면 시스템 프롬프트가 수정됩니다                                                                                                                                                                                                                                                                                                                                                                                           |
| **인용 토글**                         | ✓      | ✘      | ✘      | 인용을 활성화/비활성화하면 시스템 프롬프트가 수정됩니다                                                                                                                                                                                                                                                                                                                                                                                             |
| **속도 설정**                         | ✓      | ✘      | ✘      | [`speed: "fast"`와 표준 속도](https://platform.claude.com/docs/ko/build-with-claude/fast-mode) 간에 전환하면 시스템 및 메시지 캐시가 무효화됩니다                                                                                                                                                                                                                                                                                                     |
| **도구 선택**                         | ✓      | ✓      | ✘      | `tool_choice` 매개변수 변경은 메시지 블록에만 영향을 미칩니다                                                                                                                                                                                                                                                                                                                                                                                   |
| **이미지**                           | ✓      | ✓      | ✘      | 프롬프트의 어느 위치에서든 이미지를 추가/제거하면 메시지 블록에 영향을 미칩니다                                                                                                                                                                                                                                                                                                                                                                               |
| **사고 매개변수**                       | 모델별 상이 | 모델별 상이 | ✘      | 사고 구성(모드, 그리고 확장 모드의 `budget_tokens`)은 프롬프트에 렌더링되므로, 이를 변경하면 항상 메시지 블록이 무효화됩니다. 구성을 도구 및 시스템보다 앞에 렌더링하는 모델에서는 도구 및 시스템 캐시도 무효화됩니다. [사고와 프롬프트 캐싱](https://platform.claude.com/docs/ko/build-with-claude/thinking#thinking-and-prompt-caching)을 참조하세요.                                                                                                                                                                       |
| **Effort 설정**                     | 모델별 상이 | 모델별 상이 | ✘      | [`output_config.effort`](https://platform.claude.com/docs/ko/build-with-claude/effort) 값을 변경하면 항상 메시지 블록이 무효화되며, 도구 및 시스템 캐시에는 사고 매개변수와 동일한 모델별 영향이 있습니다. effort를 모델의 기본값으로 명시적으로 설정하는 것은 생략하는 것과 동일하며 캐시를 무효화하지 않습니다. [메시지별 effort](https://platform.claude.com/docs/ko/build-with-claude/effort#change-effort-mid-conversation-beta)를 지원하는 모델에서는 `messages` 내부의 `role: "system"` 메시지로 전달된 effort 변경이 캐싱된 접두사를 그대로 유지합니다. |
| **사고가 포함된 요청에 전달된 도구 결과가 아닌 콘텐츠** | ✓      | ✓      | 모델별 상이 | Opus 4.5+, Sonnet 4.6+, Haiku 5.5에서는 사고 블록이 기본적으로 보존되므로 캐시가 유효하게 유지됩니다(✓). 이전 Opus/Sonnet 모델 및 Claude Haiku 4.5까지의 Haiku 모델에서는 이전에 캐싱된 모든 사고 블록이 컨텍스트에서 제거되고, 해당 사고 블록 뒤에 오는 모든 메시지가 캐시에서 제거됩니다(✘). 자세한 내용은 [사고 블록과 함께 캐싱하기](https://platform.claude.com/docs/ko/build-with-claude/prompt-caching#caching-with-thinking-blocks)를 참조하세요.                                                                                    |
| **삭제된 사고 블록**                     | ✓      | ✓      | ✘      | API가 해당 요청에서 [보존](https://platform.claude.com/docs/ko/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/ko/build-with-claude/mid-conversation-system-messages#mid-conversation-tool-changes)을 지원하는 모델에서는 `inline-tools-2026-09-15` 베타 헤더를 사용하여 `tools`를 편집하지 않고도 대화 도중에 도구를 추가하거나 도구의 정의를 변경할 수 있습니다. 대화 중 시스템 메시지의 `tool_addition` 블록에 정의를 담아 보내고, `tools`는 처음 보낸 그대로 유지하세요. 캐싱된 접두사가 여전히 일치하므로, 추가된 메시지만 새 입력으로 처리됩니다. 유일한 예외는 지연되지 않은(non-deferred) 도구가 없는 `tools` 배열로, 이 경우 이 방식으로 정의된 첫 번째 도구는 해당 요청에서 한 번의 전체 캐시 미스 비용이 발생합니다. [메시지에서 도구 정의하기](https://platform.claude.com/docs/ko/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/ko/models/mythos-5-1/overview), Claude Fable 5, [Claude Mythos 5](https://platform.claude.com/docs/ko/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/ko/build-with-claude/mid-conversation-system-messages)를 참조하세요.
</Note>

### 캐시 성능 추적하기

응답의 `usage`(또는 [스트리밍](https://platform.claude.com/docs/ko/build-with-claude/streaming) 시 `message_start` 이벤트)에 포함된 다음 API 응답 필드로 캐시 성능을 모니터링하세요.

* `cache_creation_input_tokens`: 새 항목을 생성할 때 캐시에 기록된 토큰 수입니다.
* `cache_read_input_tokens`: 이 요청에서 캐시로부터 가져온 토큰 수입니다.
* `input_tokens`: 캐시에서 읽지도 않았고 캐시 생성에도 사용되지 않은 입력 토큰 수입니다(즉, 마지막 캐시 중단점 이후의 토큰).

<Note>
  **토큰 구성 이해하기**

  `input_tokens` 필드는 보낸 입력 토큰 전체가 아니라, 요청에서 **마지막 캐시 중단점 이후**에 오는 토큰만 나타냅니다.

  총 입력 토큰을 계산하는 방법은 다음과 같습니다.

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

  **위치 기준 설명:**

  * `cache_read_input_tokens` = 중단점 이전에 이미 캐시된 토큰(읽기)
  * `cache_creation_input_tokens` = 중단점 이전에 지금 캐시되는 토큰(쓰기)
  * `input_tokens` = 마지막 중단점 이후의 토큰(캐시 대상 아님)

  **예시:** 캐시된 콘텐츠(캐시에서 읽음) 100,000 토큰, 새로 캐시되는 콘텐츠 0 토큰, 사용자 메시지(캐시 중단점 이후) 50 토큰으로 구성된 요청의 경우:

  * `cache_read_input_tokens`: 100,000
  * `cache_creation_input_tokens`: 0
  * `input_tokens`: 50
  * **처리된 총 입력 토큰:** 100,050 토큰

  캐싱을 효과적으로 사용하면 `input_tokens`가 일반적으로 총 입력보다 훨씬 작아지므로, 비용과 속도 제한을 이해하려면 이 점을 알아 두어야 합니다.
</Note>

### 사고 블록과 함께 캐싱하기

프롬프트 캐싱과 함께 [사고](https://platform.claude.com/docs/ko/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/ko/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/ko/build-with-claude/thinking#thinking-and-prompt-caching)을 참조하세요.

### 캐시 저장 및 공유

<Warning>
  프롬프트 캐싱은 [워크스페이스](https://platform.claude.com/docs/ko/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/ko/build-with-claude/prompt-caching#automatic-caching)으로 시작하세요. 중단점 관리를 자동으로 처리해 줍니다.
* 변경 빈도가 서로 다른 섹션을 각각 캐시해야 한다면 [명시적 블록 수준 중단점](https://platform.claude.com/docs/ko/build-with-claude/prompt-caching#explicit-cache-breakpoints)을 사용하세요.
* 시스템 지침, 배경 정보, 대규모 컨텍스트, 자주 사용하는 도구 정의처럼 안정적이고 재사용 가능한 콘텐츠를 캐시하세요.
* 최상의 성능을 위해 캐시할 콘텐츠를 프롬프트의 앞부분에 배치하세요.
* 캐시 중단점을 전략적으로 사용하여 캐시 가능한 접두사 섹션을 구분하세요.
* 요청 간에 동일하게 유지되는 마지막 블록에 중단점을 배치하세요. 정적 접두사와 변하는 접미사(타임스탬프, 요청별 컨텍스트, 새로 들어오는 메시지)로 구성된 프롬프트라면, 변하는 블록이 아니라 접두사의 끝이 그 위치입니다.
* 캐시 적중률을 정기적으로 분석하고 필요에 따라 전략을 조정하세요.

### 사용 사례별 최적화

시나리오에 맞게 프롬프트 캐싱 전략을 조정하세요.

* 대화형 에이전트: 긴 대화, 특히 긴 지침이나 업로드된 문서가 포함된 대화의 비용과 "latency"(지연 시간)를 줄입니다.
* 코딩 어시스턴트: 관련 섹션이나 코드베이스의 요약본을 프롬프트에 유지하여 자동 완성과 코드베이스 Q\&A를 개선합니다.
* 대용량 문서 처리: 응답 지연 시간을 늘리지 않고 이미지를 포함한 긴 자료 전체를 프롬프트에 포함합니다.
* 상세한 지침 세트: 방대한 지침, 절차, 예시 목록을 공유하여 Claude의 응답을 세밀하게 조정합니다. 개발자는 보통 프롬프트에 예시를 한두 개 포함하지만, 프롬프트 캐싱을 사용하면 고품질 답변의 다양한 예시를 20개 이상 포함하여 더 나은 성능을 얻을 수 있습니다.
* 에이전트형 도구 사용: 각 단계마다 일반적으로 새 API 호출이 필요한, 여러 번의 도구 호출과 반복적인 코드 변경이 포함된 시나리오의 성능을 향상합니다.
* 책, 논문, 문서, 팟캐스트 대본 및 기타 장문 콘텐츠와 대화하기: 문서 전체를 프롬프트에 포함하고 사용자가 질문할 수 있게 하여 모든 지식 베이스를 생생하게 활용할 수 있습니다.

### 일반적인 문제 해결

예상치 못한 동작이 발생하면 다음을 확인하세요.

<Tip>
  [캐시 진단](https://platform.claude.com/docs/ko/build-with-claude/cache-diagnostics)을 사용하면 API가 연속된 요청을 비교하여 프롬프트 접두사가 어디서 달라졌는지 보고하므로, 이 목록의 여러 단계를 자동으로 처리할 수 있습니다.
</Tip>

* 캐시된 섹션이 호출 간에 동일한지 확인하세요. 명시적 중단점을 사용한다면 `cache_control` 마커가 같은 위치에 있는지 확인하세요
* 호출이 캐시 수명(기본 5분) 내에 이루어지는지 확인하세요
* `tool_choice`, 이미지 사용 여부, thinking 구성, `output_config.effort`가 호출 간에 일관되게 유지되는지 확인하세요
* 사용 중인 모델과 플랫폼의 최소 토큰 수 이상을 캐시하고 있는지 확인하세요([캐시 제한 사항](https://platform.claude.com/docs/ko/build-with-claude/prompt-caching#cache-limitations) 참조)
* 중단점이 요청 간에 동일하게 유지되는 블록에 있는지 확인하세요. 캐시 쓰기는 중단점에서만 발생하므로, 해당 블록이 변경되면(타임스탬프, 요청별 컨텍스트, 새로 들어오는 메시지) 접두사 해시가 절대 일치하지 않습니다. 룩백은 중단점 뒤쪽의 안정적인 콘텐츠를 찾지 않으며, 이전 요청이 각자의 중단점에 기록한 항목만 찾습니다
* `tool_use` 콘텐츠 블록의 키 순서가 안정적인지 확인하세요. 일부 언어(예: Swift, Go)는 JSON 변환 시 키 순서를 무작위로 바꾸어 캐시를 깨뜨립니다
* [캐시 진단](https://platform.claude.com/docs/ko/build-with-claude/cache-diagnostics)을 사용하여 API가 연속된 요청을 비교하고 프롬프트의 어느 부분이 달라졌는지 보고하도록 하세요

<Note>
  `tool_choice`를 변경하거나 프롬프트의 어느 위치에서든 이미지 유무가 바뀌면 캐시가 무효화되어 새 캐시 항목을 생성해야 합니다. 캐시 무효화에 대한 자세한 내용은 [캐시를 무효화하는 요인](https://platform.claude.com/docs/ko/build-with-claude/prompt-caching#what-invalidates-the-cache)을 참조하세요.
</Note>

***

## 1시간 캐시 지속 시간

5분이 너무 짧다면 Anthropic이 [추가 비용](https://platform.claude.com/docs/ko/build-with-claude/prompt-caching#pricing)으로 제공하는 1시간 캐시 지속 시간을 사용할 수 있습니다.

<Note>
  1시간 캐시 지속 시간은 Claude API, [Amazon Bedrock](https://platform.claude.com/docs/ko/build-with-claude/claude-in-amazon-bedrock), [Amazon Bedrock(Opus 4.6 이하)](https://platform.claude.com/docs/ko/build-with-claude/claude-on-amazon-bedrock-legacy), [Claude Platform on AWS](https://platform.claude.com/docs/ko/build-with-claude/claude-platform-on-aws), [Google Cloud](https://platform.claude.com/docs/ko/build-with-claude/claude-on-vertex-ai), [Microsoft Foundry](https://platform.claude.com/docs/ko/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` 객체에 있는 값들의 합계와 같습니다.

웹 검색 같은 서버 도구를 사용하는 중에 요청하지 않은 `ephemeral_5m_input_tokens` 쓰기가 보인다면 [프롬프트 캐싱과 도구 사용](https://platform.claude.com/docs/ko/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시간 캐시는 지연 시간 측면에서 동일하게 동작합니다. 일반적으로 긴 문서에서 첫 토큰까지의 시간(time-to-first-token)이 개선됩니다.
</Note>

### 서로 다른 TTL 혼합하기

동일한 요청에서 1시간 캐시 제어와 5분 캐시 제어를 모두 사용할 수 있지만, 중요한 제약이 있습니다: TTL이 더 긴 캐시 항목은 더 짧은 TTL보다 앞에 나타나야 합니다(즉, 1시간 캐시 항목은 모든 5분 캐시 항목보다 앞에 나타나야 합니다).

TTL을 혼합할 때, API는 프롬프트에서 세 가지 청구 위치를 결정합니다:

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개 요청의 입력 토큰을 보여줍니다. 그 결과 각 요청은 색상 상자에 표시된 것처럼 서로 다르게 계산된 가격을 갖습니다.

<Frame>
  ![서로 다른 캐시 적중과 미스를 가진 세 개의 요청: A, B, C는 캐시 읽기, 1시간 쓰기, 5분 쓰기가 끝나는 지점을 표시합니다](https://platform.claude.com/docs/ko/images/prompt-cache-mixed-ttl.svg)
</Frame>

***

## 캐시 사전 워밍

"Cache pre-warming"(캐시 사전 워밍)을 사용하면 사용자가 실제 요청을 트리거하기 전에 시스템 프롬프트나 도구 정의를 프롬프트 캐시에 미리 로드할 수 있습니다. 이를 통해 첫 번째 사용자 상호작용에서 발생하는 캐시 미스로 인한 "latency"(지연 시간) 불이익이 제거되어, 지연 시간에 민감한 애플리케이션의 "time-to-first-token"(첫 토큰까지의 시간), 즉 TTFT가 줄어듭니다.

### 작동 방식

요청에서 `max_tokens: 0`을 설정하세요. API는 프롬프트를 모델에 읽어 들이고 모든 `cache_control` "breakpoint"(중단점)에서 캐시를 쓴 다음, 출력을 생성하지 않고 즉시 반환합니다. 응답에는 빈 `content` 배열, `stop_reason: "max_tokens"`, 그리고 완전히 채워진 `usage` 블록이 포함됩니다.

`cache_control` 중단점은 자리 표시자 사용자 메시지가 아니라, 후속 요청과 공유되는 마지막 블록(일반적으로 시스템 프롬프트 또는 도구 정의)에 배치하세요. 그렇지 않으면 캐시 항목이 자리 표시자를 키로 하여 생성되므로 후속 요청이 이를 적중하지 못합니다. 또한 후속 요청과 동일한 사고 구성 및 `output_config.effort`를 사용하세요. 이러한 값은 프롬프트에 렌더링되므로([캐시를 무효화하는 요소](https://platform.claude.com/docs/ko/build-with-claude/prompt-caching#what-invalidates-the-cache) 참조), 다른 구성으로 사전 워밍을 하면 실제 트래픽이 절대 적중하지 않는 항목이 쓰일 수 있습니다. 이는 [자동 캐싱](https://platform.claude.com/docs/ko/build-with-claude/prompt-caching#automatic-caching)이 아닌 [명시적 캐시 중단점](https://platform.claude.com/docs/ko/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" }]
    });
  }

  // 실제 사용자 요청이며, 미리 준비된(warm) 캐시의 이점을 얻습니다.
  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 }]
    });
  }

  // 사용자 트래픽이 들어오기 전에 캐시를 미리 준비(warm)하세요.
  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" }],
          }
      );

  // 실제 사용자 요청이며, 미리 준비된 캐시(warm cache)의 이점을 얻습니다.
  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 }],
          }
      );

  // 사용자 트래픽이 들어오기 전에 캐시를 미리 준비(warm)하세요.
  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
  }

  // 실제 사용자 요청이며, 미리 준비된(warm) 캐시의 이점을 얻습니다.
  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() {
  	// 사용자 트래픽이 들어오기 전에 캐시를 미리 준비(warm)하세요.
  	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());
  }

  // 실제 사용자 요청이며, 미리 준비된(warm) 캐시의 이점을 얻습니다.
  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() {
      // 사용자 트래픽이 들어오기 전에 캐시를 미리 준비(warm)하세요.
      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']],
  );

  // 실제 사용자 요청이며, 미리 준비된(warm) 캐시의 이점을 얻습니다.
  $respond = fn (string $userMessage) => $client->messages->create(
      model: Model::CLAUDE_OPUS_5_5,
      maxTokens: 1024,
      system: $systemPrompt,
      messages: [['role' => 'user', 'content' => $userMessage]],
  );

  // 사용자 트래픽이 들어오기 전에 캐시를 미리 준비(warm)하세요.
  $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

  # 실제 사용자 요청이며, 미리 준비된(warm) 캐시의 이점을 얻습니다.
  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

  # 사용자 트래픽이 들어오기 전에 캐시를 미리 준비(warm)하세요.
  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/ko/build-with-claude/prompt-caching#1-hour-cache-duration)을 사용하세요.

### 제한 사항

`max_tokens: 0` 요청은 다음 중 하나라도 설정되어 있으면 `invalid_request_error`와 함께 거부됩니다. 각각은 토큰 예산이 0인 상태에서는 생성할 수 없는 출력을 전제로 하기 때문입니다:

* `stream: true`
* [확장 사고](https://platform.claude.com/docs/ko/build-with-claude/extended-thinking) (`thinking.type: "enabled"`)
* [구조화된 출력](https://platform.claude.com/docs/ko/build-with-claude/structured-outputs) (`output_config.format`)
* `{"type": "tool", ...}` 또는 `{"type": "any"}`의 `tool_choice`

`max_tokens: 0`은 [Message Batches](https://platform.claude.com/docs/ko/build-with-claude/batch-processing) 요청 내에서도 거부됩니다. 사전 워밍은 첫 토큰까지의 시간을 목표로 하는데, 이는 배치 처리에는 적용되지 않으며, 배치 처리 중에 쓰인 캐시 항목은 후속 요청이 실행되기 전에 만료될 가능성이 높습니다.

### max\_tokens=1 우회 방법 대체하기

`max_tokens: 0`을 사용할 수 있기 전에는 일부 애플리케이션이 동일한 효과를 얻기 위해 `max_tokens: 1` 워밍업 호출을 사용했습니다. `max_tokens: 0` 방식이 권장됩니다. 출력이 생성되지 않으므로 버려야 할 단일 토큰 응답이 없고, 출력 토큰이 청구되지 않으며, 요청의 의도가 명확합니다.

***

## 프롬프트 캐싱 예시

프롬프트 캐싱을 시작하는 데 도움이 되도록 [프롬프트 캐싱 쿡북](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/ko/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))
            // 첫 번째 사용자 메시지(캐시 제어 없음)
            .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?"
            )
            // 두 번째 사용자 메시지(캐시 제어 포함)
            .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`로 표시되어 대화가 진행됨에 따라 점진적으로 캐싱될 수 있습니다.

    이 접근 방식은 최대한의 유연성을 제공합니다:

    * 이전 내용을 변경하지 않고 대화에 새 턴을 추가하면 네 개의 캐시 세그먼트가 모두 재사용됩니다
    * 도구와 지시는 그대로 두고 RAG 문서를 업데이트하면 처음 두 개의 캐시 세그먼트가 재사용됩니다
    * 도구, 지시, 문서는 그대로 두고 대화를 변경하면 처음 세 개의 세그먼트가 재사용됩니다
    * 어느 중단점에서든 변경이 발생하면 해당 세그먼트와 그 이후의 모든 것이 무효화되지만, 그 이전에 캐시된 세그먼트는 유효하게 유지됩니다

    첫 번째 요청의 경우:

    * `input_tokens`: 최소한(마지막 캐시 중단점 이후의 토큰, 이 예시에서는 0에 가까움)
    * `cache_creation_input_tokens`: 캐시된 모든 세그먼트의 토큰(도구 + 지시 + RAG 문서 + 대화 기록)
    * `cache_read_input_tokens`: 0 (캐시 적중 없음)

    새 사용자 메시지만 있는 후속 요청의 경우(예시에서처럼 네 번째 중단점이 새로운 마지막 메시지로 이동한 경우):

    * `input_tokens`: 최소한(마지막 캐시 중단점 이후의 토큰, 이 예시에서는 0에 가까움)
    * `cache_creation_input_tokens`: 새 사용자 메시지와 이전 어시스턴트 턴의 토큰(캐싱되는 새 대화 세그먼트)
    * `cache_read_input_tokens`: 이전에 캐시된 모든 토큰(도구 + 지시 + RAG 문서 + 이전 대화)

    이 패턴은 특히 다음과 같은 경우에 강력합니다:

    * 대규모 문서 컨텍스트를 가진 RAG 애플리케이션
    * 여러 도구를 사용하는 에이전트 시스템
    * 컨텍스트를 유지해야 하는 장기 실행 대화
    * 프롬프트의 여러 부분을 독립적으로 최적화해야 하는 애플리케이션
  </Accordion>
</AccordionGroup>

## 데이터 보존

프롬프트 캐싱(자동 및 명시적 모두)은 ZDR 적용 대상입니다. Anthropic은 프롬프트나 Claude 응답의 원시 텍스트를 저장하지 않습니다.

캐시된 콘텐츠의 KV(키-값) 캐시 표현과 암호화 해시는 메모리에만 보관되며 저장 매체에 저장되지 않습니다. 캐시된 항목의 최소 수명은 5분(표준) 또는 1시간(확장)이며, 그 이후에는 즉시는 아니지만 신속하게 삭제됩니다. 캐시 항목은 조직 간에 격리되며, Claude API, Claude Platform on AWS, Microsoft Foundry에서는 조직 내 워크스페이스 간에도 격리됩니다.

모든 기능에 대한 ZDR 적용 여부는 [API 및 데이터 보존](https://platform.claude.com/docs/ko/manage-claude/api-and-data-retention)을 참조하세요.

***

## FAQ

<AccordionGroup>
  <Accordion title="여러 개의 캐시 중단점이 필요한가요, 아니면 끝에 하나만 있으면 충분한가요?">
    **대부분의 경우 정적 콘텐츠의 끝에 캐시 중단점 하나만 있으면 충분합니다.** 캐시 쓰기는 표시한 블록에서만 발생합니다. 요청 간에 동일하게 유지되는 마지막 블록에 중단점을 배치하면, 이후의 모든 요청이 동일한 항목을 읽습니다. 이후 블록이 요청마다 달라지는 경우(타임스탬프, 수신 메시지 등), 중단점을 그 앞의 마지막 안정적인 블록에 두세요.

    다음과 같은 경우에만 여러 중단점이 필요합니다:

    * 대화가 길어지면서 중단점이 마지막 캐시 쓰기 지점보다 20개 이상의 블록 뒤로 밀려나, 이전 항목이 lookback 윈도우 밖에 놓이게 되는 경우
    * 서로 다른 빈도로 업데이트되는 섹션을 독립적으로 캐싱하려는 경우
    * 비용 최적화를 위해 캐싱되는 내용을 명시적으로 제어해야 하는 경우

    예시: 시스템 지시(거의 변경되지 않음)와 RAG 컨텍스트(매일 변경됨)가 있는 경우, 두 개의 중단점을 사용하여 이들을 별도로 캐싱할 수 있습니다.
  </Accordion>

  <Accordion title="캐시 중단점에 추가 비용이 발생하나요?">
    아니요, 캐시 중단점 자체는 무료입니다. 다음 항목에 대해서만 비용을 지불합니다:

    * 캐시에 콘텐츠 쓰기(5분 TTL의 경우 기본 입력 토큰보다 25% 더 비쌈)
    * 캐시에서 읽기(기본 입력 토큰 가격의 일부, [가격](https://platform.claude.com/docs/ko/build-with-claude/prompt-caching#pricing) 참조)
    * 캐시되지 않은 콘텐츠에 대한 일반 입력 토큰

    중단점의 수는 가격에 영향을 주지 않으며, 캐시되고 읽히는 콘텐츠의 양만 중요합니다.
  </Accordion>

  <Accordion title="usage 필드에서 총 입력 토큰을 어떻게 계산하나요?">
    usage 응답에는 함께 총 입력을 나타내는 세 개의 별도 입력 토큰 필드가 포함됩니다:

    ```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/ko/build-with-claude/prompt-caching#tracking-cache-performance)을 참조하세요.
  </Accordion>

  <Accordion title="캐시 수명은 얼마인가요?">
    캐시의 기본 최소 수명(TTL)은 5분입니다. 이 수명은 캐시된 콘텐츠가 사용될 때마다 갱신됩니다.

    5분이 너무 짧다고 생각되면, Anthropic은 [1시간 캐시 TTL](https://platform.claude.com/docs/ko/build-with-claude/prompt-caching#1-hour-cache-duration)도 제공합니다.
  </Accordion>

  <Accordion title="캐시 수명은 언제부터 시작되나요?">
    수명은 캐시 항목을 쓰거나 읽는 요청의 응답이 끝난 시점이 아니라, 해당 요청이 시작된 시점부터 측정됩니다. 응답을 생성하는 데 소요된 시간도 수명에 포함되므로, 후속 요청이 캐시를 재사용할 수 있는 시간 범위는 수명에서 생성 시간을 뺀 값입니다.

    요청이 긴 응답을 생성하고 다음 요청이 수명이 경과한 후에야 시작될 수 있는 경우, [1시간 캐시 TTL](https://platform.claude.com/docs/ko/build-with-claude/prompt-caching#1-hour-cache-duration)을 사용하세요.
  </Accordion>

  <Accordion title="캐시 중단점은 몇 개까지 사용할 수 있나요?">
    프롬프트에서 최대 4개의 캐시 중단점(`cache_control` 매개변수 사용)을 정의할 수 있습니다.
  </Accordion>

  <Accordion title="프롬프트 캐싱은 모든 모델에서 사용할 수 있나요?">
    프롬프트 캐싱은 모든 [활성 Claude 모델](https://platform.claude.com/docs/ko/models/overview)에서 지원됩니다.
  </Accordion>

  <Accordion title="프롬프트 캐싱은 사고 기능과 어떻게 작동하나요?">
    사고 매개변수를 변경하면(모드 전환 또는 확장 모드에서 예산 변경) 캐시된 메시지 접두사가 무효화되며, 사고 구성이 프롬프트에 렌더링되기 때문에 캐시된 시스템 프롬프트와 도구도 무효화될 수 있습니다. [`output_config.effort`](https://platform.claude.com/docs/ko/build-with-claude/effort) 값도 동일하게 동작합니다.

    캐시 무효화에 대한 자세한 내용은 [캐시를 무효화하는 요소](https://platform.claude.com/docs/ko/build-with-claude/prompt-caching#what-invalidates-the-cache)를 참조하세요.

    도구 사용 및 프롬프트 캐싱과의 상호작용을 포함하여 사고 기능에 대한 자세한 내용은 [사고와 프롬프트 캐싱](https://platform.claude.com/docs/ko/build-with-claude/thinking#thinking-and-prompt-caching)을 참조하세요.
  </Accordion>

  <Accordion title="프롬프트 캐싱을 어떻게 활성화하나요?">
    가장 쉬운 방법은 요청 본문의 최상위 수준에 `"cache_control": {"type": "ephemeral"}`을 추가하는 것입니다([자동 캐싱](https://platform.claude.com/docs/ko/build-with-claude/prompt-caching#automatic-caching)). 또는 개별 콘텐츠 블록에 최소 하나의 `cache_control` 중단점을 포함할 수 있습니다([명시적 캐시 중단점](https://platform.claude.com/docs/ko/build-with-claude/prompt-caching#explicit-cache-breakpoints)).
  </Accordion>

  <Accordion title="다른 API 기능과 함께 프롬프트 캐싱을 사용할 수 있나요?">
    예, 프롬프트 캐싱은 도구 사용 및 비전 기능과 같은 다른 API 기능과 함께 사용할 수 있습니다. 그러나 프롬프트에 이미지가 있는지 여부를 변경하거나 도구 사용 설정을 수정하면 캐시가 깨집니다.

    캐시 무효화에 대한 자세한 내용은 [캐시를 무효화하는 요소](https://platform.claude.com/docs/ko/build-with-claude/prompt-caching#what-invalidates-the-cache)를 참조하세요.
  </Accordion>

  <Accordion title="프롬프트 캐싱은 가격에 어떤 영향을 미치나요?">
    프롬프트 캐싱은 새로운 가격 구조를 도입합니다. 5분 캐시 쓰기는 기본 입력 토큰보다 25% 더 비싸고, 1시간 캐시 쓰기는 기본 입력 토큰의 2배이며, 캐시 적중은 기본 입력 토큰 가격의 일부입니다(모델별 배수는 [가격](https://platform.claude.com/docs/ko/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/ko/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/ko/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/ko/build-with-claude/batch-processing) 요청에서 프롬프트 캐싱을 사용할 수 있습니다. 그러나 비동기 배치 요청은 동시에 임의의 순서로 처리될 수 있으므로, 캐시 적중은 최선의 노력(best-effort) 기준으로 제공됩니다.

    [1시간 캐시](https://platform.claude.com/docs/ko/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>
