Anthropic Claude API Prompt Caching 사용하기
작성 일자 : 2024년 10월 13일
Anthropic Claude API Prompt Caching 사용하기
- Prompt Caching은 반복적인 작업이나 동일한 프롬프트가 있는 요청에 대해, 처리 시간과 비용을 절약할 수 있는 기능입니다.
- Claude 3.5 Sonnet과 Claude 3 Opus 버전에서는 최소 1024토큰 이상의 프롬프트에 대해 캐싱을 사용할 수 있습니다.
- Claude 3 Haiku 버전에서는 최소 2048토큰 이상의 프롬프트에 대해 캐싱을 사용할 수 있습니다.
- Caching된 프롬프트의 TTL은 5분입니다.
- 프롬프트에서 캐시 중단점을 최대 4개까지 정의할 수 있습니다.
Prompt Caching 과정
프롬프트 캐싱이 활성화된 상태에서 요청을 보내는 경우:
- 시스템에서 프롬프트 접두사가 최근 쿼리에서 이미 캐시되어 있는지 확인합니다.
- 캐시된 버전이 있으면 캐시된 버전을 사용하여 처리 시간과 비용을 줄입니다.
- 그렇지 않으면 전체 프롬프트를 처리하고 나중에 사용할 수 있도록 접두사를 캐시합니다.
Prompt Caching이 필요한 경우
- 많은 예제가 포함된 프롬프트
- 많은 양의 컨텍스트 또는 배경 정보
- 일관된 지침이 있는 반복 작업
- 상호간의 반복으로 이어지는 긴 대화
Prompt Caching Pricing
- 캐시 쓰기 토큰은 기본 입력 토큰보다 25% 더 비쌉니다. ($3/MTok -> $3.75/MTok)
- 맨 첫 번째 요청에 대해서 캐시 쓰기 토큰을 사용
- 캐시 읽기 토큰은 기본 입력 토큰보다 90% 저렴합니다. ($3/MTok -> $0.30 / MTok)
- 이후, 캐시된 프롬프트를 사용할 때 캐시 읽기 토큰을 사용
- 일반 입력 및 출력 토큰은 표준 요금으로 가격이 책정됩니다
예제
다음은 프롬프트 캐싱을 사용하는 예제입니다.
import anthropic
import os
from dotenv import load_dotenv
load_dotenv()
client = anthropic.Anthropic(api_key=os.getenv("ANTHROPIC_API_KEY"))
story_book = """
Once upon a time, in a small coastal village nestled between towering cliffs and the endless ocean, there lived a girl named Aria.
...(생략)
As she stood at the edge of the cliff one last time, gazing out at the vast, endless ocean, Aria knew that her adventure was only just beginning. With the Moonstone around her neck and the power of the tides within her, she was ready to face whatever lay beyond the horizon."""
response = client.beta.prompt_caching.messages.create(
model="claude-3-5-sonnet-20240620",
max_tokens=1024,
system=[
{
"type": "text",
"text": "You are an AI assistant tasked with analyzing story books."
},
{
"type": "text",
"text": f"Here is the full text of a story book: {story_book}",
"cache_control": {"type": "ephemeral"}
}
],
messages=[
{
"role": "user",
"content": "What was the story about?"
}
]
)
print(response)
첫 번째 요청
PromptCachingBetaMessage(id='msg_01WApG8tzohCsJqCzVEAW4W9', content=[TextBlock(text="The story is about ...The story ends with the suggestion that Aria's adventure is just beginning, hinting at future challenges and growth.", type='text')], model='claude-3-5-sonnet-20240620', role='assistant', stop_reason='end_turn', stop_sequence=None, type='message', usage=PromptCachingBetaUsage(cache_creation_input_tokens=1217, cache_read_input_tokens=0, input_tokens=13, output_tokens=226))
cache_creation_input_tokens
: 1217cache_read_input_tokens
: 0input_tokens
: 13output_tokens
: 226
두 번째 요청
PromptCachingBetaMessage(id='msg_01Cx1vsccgkm6vg1WR9XxHM9', content=[TextBlock(text='The umbrella mentioned in the story ... discovered the Moonstone pendant.', type='text')], model='claude-3-5-sonnet-20240620', role='assistant', stop_reason='end_turn', stop_sequence=None, type='message', usage=PromptCachingBetaUsage(cache_creation_input_tokens=0, cache_read_input_tokens=1217, input_tokens=16, output_tokens=60))
cache_creation_input_tokens
: 0cache_read_input_tokens
: 1217input_tokens
: 16output_tokens
: 60
Reference
Prompt Caching (beta) - Anthropic
Large Context caching example This example demonstrates basic Prompt Caching usage, caching the full text of the legal agreement as a prefix while keeping the user instruction uncached. For the first request: input_tokens: Number of tokens in the user mess
docs.anthropic.com