> ## Documentation Index
> Fetch the complete documentation index at: https://docs.aihubmix.com/llms.txt
> Use this file to discover all available pages before exploring further.

# 프롬프트 캐싱

Prompt Caching은 모델 추론 비용을 줄이는 데 사용되는 중요한 메커니즘입니다. 이전에 처리된 프롬프트 콘텐츠를 캐싱함으로써, 후속 요청에서 재사용할 수 있어, 중복 계산을 줄이고, 비용을 절감하며, 응답 효율성을 향상시킬 수 있습니다.

## 원리

prompt caching이 활성화된 요청을 보내면, 시스템은 최근 쿼리에서 프롬프트 접두사가 캐시되었는지 확인합니다. 발견되면 캐시를 사용하여 처리 시간과 비용을 줄입니다; 그렇지 않으면 전체 프롬프트를 처리하고 응답이 시작된 후 접두사를 캐시합니다. 이는 다음 시나리오에서 특히 유용합니다:

* 많은 예시를 포함하는 프롬프트
* 광범위한 컨텍스트 또는 배경 정보
* 일관된 지시가 있는 반복 작업
* 긴 다중 턴 대화

## 핵심 메커니즘

다른 모델 공급자는 캐싱에 대해 다양한 지원을 합니다:

### 자동 캐싱

자동 캐싱은 추가 구성이 필요하지 않으며; 시스템이 자동으로 재사용 가능한 콘텐츠를 식별하고 캐싱하며, OpenAI, DeepSeek 등의 모델에 적용됩니다.

#### OpenAI

* 최소 프롬프트 길이: 1024 토큰, 접두사가 글자 단위로 일치하면 자동으로 히트합니다
* GPT-5.6 이전 모델: 캐시 쓰기는 별도 과금 없음, 캐시 읽기는 해당 모델의 캐시 읽기 가격으로 과금
* GPT-5.6 및 이후(공식 표현 "GPT-5.6 models and later model families", 현재 gpt-5.6-sol / terra / luna): 캐시 쓰기는 입력 가격의 1.25배, 읽기는 0.1배로 과금되며, `prompt_cache_key`와 명시적 캐시 중단점 파라미터가 추가되었습니다
* 사용법, 과금, 히트 문제 해결은 [GPT 프롬프트 캐싱](/ko/api/GPT-Cache) 참고

#### Gemini

* 암시적 컨텍스트 캐싱이 기본적으로 활성화되어 있으며, 수동 구성 없이 캐싱이 자동으로 효과적입니다.
* 캐싱은 콘텐츠, 모델 및 파라미터가 동일할 때만 효과적입니다; 차이가 있으면 새 요청으로 처리되며 캐시에 적중하지 않습니다.
* 캐시 유효 기간은 개발자가 설정하며, 설정하지 않을 수도 있습니다. 지정하지 않으면 기본적으로 1시간입니다. 최소 또는 최대 기간 제한이 없으며, 비용은 캐시된 토큰 수와 캐시 기간에 따라 다릅니다.

#### DeepSeek / Grok / Moonshot / Groq

* 비용: 캐시에 쓰기는 무료이거나 동일한 가격이며, 캐시에서 읽기는 원래 가격보다 낮습니다

### Claude 모델 명시적 캐싱

* `cache_control`로 활성화해야 합니다: 요청 본문 최상위 필드로 자동 중단점 설정(대화에 따라 앞으로 이동), 또는 콘텐츠 블록 단위 중단점으로 캐시 위치를 세밀하게 제어
* 활성 상태의 모든 Claude 모델이 지원하며, 캐시 쓰기는 5분 캐시 1.25배·1시간 캐시 2배, 읽기는 0.1배로 전 모델에 동일하게 적용됩니다
* Anthropic Claude 모델에 적용됩니다

<Note>
  Claude는 모델별로 최소 캐시 가능 토큰 임계값을 설정합니다(512 / 1,024 / 2,048 / 4,096 등으로 다양하며, 버전이 높을수록 임계값이 높은 것은 아닙니다). 예를 들어 Claude Opus 4.8은 1,024, Claude Opus 4.7은 2,048, Claude Opus 4.6 / 4.5와 Claude Haiku 4.5는 4,096, Claude Fable 5는 512입니다. 임계값 미만의 접두사는 `cache_control`을 표시하더라도 캐시에 기록되지 않으며, 오류도 발생하지 않습니다. 응답에서 `cache_creation_input_tokens`와 `cache_read_input_tokens`가 동시에 0이면 이 경우입니다. 전체 구간과 문제 해결은 [Claude 프롬프트 캐싱](/ko/api/Claude-Cache)을 참고하세요.
</Note>

#### OpenAI 호환 인터페이스

`system`, `user` (이미지 포함), `tools`에서 `cache_control` 필드를 사용하여 캐싱 중단점을 설정할 수 있습니다. 다음 예시는 주요 구조만 표시합니다:

**System 메시지 캐싱 (기본 5분 TTL):**

```json theme={null}
{
  "model": "claude-opus-4-5",
  "messages": [
    {
      "role": "system",
      "content": [
        {"type": "text", "text": "You are an AI assistant"},
        {
          "type": "text",
          "text": "(long context)",
          "cache_control": {"type": "ephemeral"}
        }
      ]
    },
    {
      "role": "user",
      "content": [{"type": "text", "text": "Hello"}]
    }
  ]
}
```

**User 메시지 캐싱 (1시간 TTL):**

```json theme={null}
{
  "model": "claude-opus-4-5",
  "messages": [
    {
      "role": "system",
      "content": [{"type": "text", "text": "You are an AI assistant"}]
    },
    {
      "role": "user",
      "content": [
        {
          "type": "text",
          "text": "(long context)",
          "cache_control": {"type": "ephemeral", "ttl": "1h"}
        },
        {"type": "text", "text": "Hello"}
      ]
    }
  ]
}
```

**이미지 메시지 캐싱:**

```json theme={null}
{
  "role": "user",
  "content": [
    {
      "type": "image_url",
      "image_url": {"detail": "auto", "url": "data:image/jpeg;base64,/9j/4AAQ..."},
      "cache_control": {"type": "ephemeral"}
    },
    {"type": "text", "text": "What's this?"}
  ]
}
```

**Tool 정의 캐싱:**

`cache_control`을 tool 객체의 최상위 수준 (`type` 및 `function`과 동일한 수준)에 배치합니다:

```json theme={null}
{
  "tools": [{
    "type": "function",
    "function": {
      "name": "get_weather",
      "description": "Get current weather for a location",
      "parameters": {
        "type": "object",
        "properties": {"city": {"type": "string"}},
        "required": ["city"]
      }
    },
    "cache_control": {"type": "ephemeral", "ttl": "1h"}
  }]
}
```

#### Anthropic 호환 인터페이스

<CodeGroup>
  ```shellscript cURL theme={null}
  curl https://aihubmix.com/v1/messages \
    -H "content-type: application/json" \
    -H "x-api-key: $AIHUBMIX_API_KEY" \
    -H "anthropic-version: 2023-06-01" \
    -d '{
      "model": "claude-opus-4-6",
      "max_tokens": 1024,
      "system": [
        {
          "type": "text",
          "text": "You are an AI assistant tasked with analyzing literary works. Your goal is to provide insightful commentary on themes, characters, and writing style.\n"
        },
        {
          "type": "text",
          "text": "<the entire contents of Pride and Prejudice>",
          "cache_control": {"type": "ephemeral"}
        }
      ],
      "messages": [
        {
          "role": "user",
          "content": "Analyze the major themes in Pride and Prejudice."
        }
      ]
    }'

  # Call the model again with the same input until the caching checkpoint
  curl https://aihubmix.com/v1/messages # rest of input
  ```

  ```python Python theme={null}
  import anthropic

  client = Anthropic(
    api_key="<AIHUBMIX_API_KEY>",  
    base_url="https://aihubmix.com"
  )

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

  # Call the model again with the same input until the caching checkpoint
  response = client.messages.create(**params)
  print(response.usage.model_dump_json())
  ```
</CodeGroup>

#### 캐싱 기간

* 기본값: 5분
* 선택 사항: 1시간 ("ttl": "1h")

> 자세한 내용은 다음을 참조하세요: [Claude Prompt Caching](https://docs.aihubmix.com/en/blogs/aihubmix-openai-upgrade-claude#2-prompt-caching)

## 사용 권장 사항

1. **안정적인 접두사 유지**

고정된 콘텐츠를 프롬프트의 시작 부분에 배치하세요. 권장 구조:

```text theme={null}
[System Settings / Long Text / RAG Data] 
[User Question (Variable Part)]
```

2. **대형 텍스트 캐싱**

다음 콘텐츠를 우선적으로 캐싱하세요:

* RAG 데이터
* 긴 텍스트
* CSV / JSON 데이터
* 역할 설정

3. **TTL 제어**

* 짧은 세션 → 5분
* 긴 세션 → 1시간 (더 비용 효율적)

4. **캐시 쓰기 감소**

## 자주 변경되는 콘텐츠가 캐시에 들어가지 않도록 피하세요. 타임스탬프, 사용자 입력 변수, 고빈도 변경 데이터 등을 캐싱하지 마세요.

마지막 업데이트: 2026-07-10
