본문 바로가기
C.W.K.
Stream
Lesson 05 of 06 · published

프롬프트 캐싱은 안정된 앞부분에서 돈을 아껴

~16 min · prompt-caching, cache-control, ephemeral

Level 0Observer
0 XP0/64 lessons0/13 achievements
0/150 XP to next level150 XP to go0% complete

같은 앞부분을 다시 계산하지 않아

프롬프트 앞부분을 캐시 대상으로 표시하면 Anthropic이 그 구간의 모델 상태를 저장해. 다음 호출이 같은 앞부분을 보내면 다시 토큰화하지 않고 캐시에서 읽어 비용과 시간을 줄이지. 첫 캐시 쓰기는 일반 입력보다 비싸므로, 실제로 여러 번 재사용할 구간에만 이득이 생겨.

중단점은 여기까지 같다는 표시야

시스템 텍스트·도구 목록·메시지·문서의 콘텐츠 블록에 cache_control: {"type": "ephemeral"}을 붙일 수 있어. 중단점은 그 자리까지가 재사용할 앞부분임을 뜻해. 요청마다 최대 4개를 지원하므로 시스템 지침, 도구 정의, 안정된 대화 구간처럼 성격이 다른 덩어리를 나눌 수 있어.

한 글자만 바뀌어도 뒤 캐시가 끊겨

시스템 프롬프트의 공백, 도구 정의, 메시지 순서가 달라지면 해당 앞부분의 캐시가 무효가 돼. 동적으로 바뀌는 값은 뒤로 보내고, 오래 유지할 규칙과 자료는 앞에 고정해. 캐시 적중률은 옵션 하나보다 프롬프트 조립 순서가 결정해.

원칙: 캐싱은 안정된 앞부분에 보상해. 프롬프트의 첫 구간은 의도적으로 단조롭고 예측 가능하게 만들어.

Code

System 프롬프트랑 tools 리스트 cache·python
PIPPA_PERSONA = open("system_prompt.md").read()  # 수십 KB의 stable identity

response = client.messages.create(
    model="claude-sonnet-4-6",
    max_tokens=1024,
    system=[
        {
            "type": "text",
            "text": PIPPA_PERSONA,
            "cache_control": {"type": "ephemeral"},  # breakpoint #1
        }
    ],
    tools=[
        # ... 긴 tool 정의 ...
        {"name": "last_tool", "description": "...", "input_schema": {...},
         "cache_control": {"type": "ephemeral"}},  # breakpoint #2
    ],
    messages=[{"role": "user", "content": "hi"}],
)

u = response.usage
print("cache_creation_input:", u.cache_creation_input_tokens)
print("cache_read_input:", u.cache_read_input_tokens)
print("input:", u.input_tokens, "output:", u.output_tokens)
Cache hit 검증·python
# Cache TTL 안에 같은 호출 두 번 (ephemeral 디폴트 5분).
for i in (1, 2):
    r = client.messages.create(
        model="claude-sonnet-4-6",
        max_tokens=64,
        system=[{"type": "text", "text": LARGE_STABLE_TEXT, "cache_control": {"type": "ephemeral"}}],
        messages=[{"role": "user", "content": f"call {i}"}],
    )
    u = r.usage
    print(f"call {i}: write={u.cache_creation_input_tokens}, read={u.cache_read_input_tokens}")
# 기대: call 1은 write > 0, read = 0. Call 2는 write = 0, read > 0.

External links

Exercise

10번 연속 호출에서 같은 앞부분을 보내는 프롬프트를 골라 캐시 중단점을 추가해. 캐시가 없을 때와 한 번의 쓰기·뒤의 읽기가 있을 때 총비용을 비교해.
Hint
캐시 쓰기는 일반 입력보다 약 25% 비싸지만 읽기는 훨씬 싸서 보통 2~3번 재사용하면 손익분기점을 넘어.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.