import anthropic
client = anthropic.Anthropic()
# 웹 검색과 캐시 중단점이 있는 첫 번째 요청
messages = [
{
"role": "user",
"content": "What's the current weather in San Francisco today?"
}
]
response1 = client.messages.create(
model="claude-opus-4-1-20250805",
max_tokens=1024,
messages=messages,
tools=[{
"type": "web_search_20250305",
"name": "web_search",
"user_location": {
"type": "approximate",
"city": "San Francisco",
"region": "California",
"country": "US",
"timezone": "America/Los_Angeles"
}
}]
)
# 대화에 Claude의 응답 추가
messages.append({
"role": "assistant",
"content": response1.content
})
# 검색 결과 이후 캐시 중단점이 있는 두 번째 요청
messages.append({
"role": "user",
"content": "Should I expect rain later this week?",
"cache_control": {"type": "ephemeral"} # 이 지점까지 캐시
})
response2 = client.messages.create(
model="claude-opus-4-1-20250805",
max_tokens=1024,
messages=messages,
tools=[{
"type": "web_search_20250305",
"name": "web_search",
"user_location": {
"type": "approximate",
"city": "San Francisco",
"region": "California",
"country": "US",
"timezone": "America/Los_Angeles"
}
}]
)
# 두 번째 응답은 캐시된 검색 결과의 이점을 얻으면서도
# 필요한 경우 새로운 검색을 수행할 수 있습니다
print(f"Cache read tokens: {response2.usage.get('cache_read_input_tokens', 0)}")