Anthropic
Anthropic
이 문서에서는 pydantic-ai에서 Anthropic을 사용하는 방법을 알려드려요. AnthropicModel을 설치·설정하고, API 키와 환경 변수로 모델을 사용하는 법부터 커스텀 프로바이더, 클라우드 플랫폼 연동, 프롬프트 캐싱, 컨텍스트 압축, 강제 도구 선택, thinking 블록 바인딩까지 폭넓게 다뤄요.
출처: 문서
본문
설치 (Install)
AnthropicModel을 사용하려면 anthropic 선택 그룹과 함께 pydantic-ai 또는 pydantic-ai-slim을 설치하세요.
pip install "pydantic-ai-slim[anthropic]"
또는 uv를 사용한다면:
uv add "pydantic-ai-slim[anthropic]"
구성 (Configuration)
Anthropic API를 사용하려면 console.anthropic.com/settings/keys에서 API 키를 생성하세요. AnthropicModelName은 사용 가능한 Anthropic 모델 목록을 담고 있어요.
환경 변수 (Environment variable)
API 키를 얻으면 환경 변수로 설정하세요:
export ANTHROPIC_API_KEY='your-api-key'
그러면 이름으로 AnthropicModel을 사용할 수 있어요:
from pydantic_ai import Agent
agent = Agent('anthropic:claude-sonnet-4-6')
...
또는 모델 이름만으로 직접 모델을 초기화할 수도 있어요:
from pydantic_ai import Agent
from pydantic_ai.models.anthropic import AnthropicModel
model = AnthropicModel('claude-sonnet-4-5')
agent = Agent(model)
...
Claude Opus 4.7 / 4.8 / 5 / 5.5 마이그레이션
Anthropic의 Claude Opus 마이그레이션 가이드는 Opus 4.7, 4.8, 5, 5.5 요청에서 temperature, top_p, top_k를 제거할 것을 권장해요. Pydantic AI는 claude-opus-4-7, claude-opus-4-8, claude-opus-5, claude-opus-5-5, claude-sonnet-5, claude-fable-5, claude-mythos-5에 대해 extra_body 오버라이드를 포함해 이 키들을 자동으로 제거해요.
같은 가이드는 Opus 4.6에서 마이그레이션할 때 max_tokens과 토큰 수 관련 가정을 다시 평가할 것을 권장해요. Opus 4.7이 (4.8로 이어진) 업데이트된 토크나이제이션을 도입했기 때문이에요. count_tokens()나 count_tokens_before_request에 의존한다면 새 모델에 맞춰 임계값을 검증하세요.
provider 인자 (provider argument)
provider 인자를 통해 커스텀 Provider를 제공할 수 있어요:
from pydantic_ai import Agent
from pydantic_ai.models.anthropic import AnthropicModel
from pydantic_ai.providers.anthropic import AnthropicProvider
model = AnthropicModel(
'claude-sonnet-4-5', provider=AnthropicProvider(api_key='your-api-key')
)
agent = Agent(model)
...
커스텀 HTTP 클라이언트 (Custom HTTP Client)
AnthropicProvider를 커스텀 httpx2.AsyncClient로 커스터마이즈할 수 있어요:
from httpx2 import AsyncClient
from pydantic_ai import Agent
from pydantic_ai.models.anthropic import AnthropicModel
from pydantic_ai.providers.anthropic import AnthropicProvider
custom_http_client = AsyncClient(timeout=30)
model = AnthropicModel(
'claude-sonnet-4-5',
provider=AnthropicProvider(api_key='your-api-key', http_client=custom_http_client),
)
agent = Agent(model)
...
레거시 httpx.AsyncClient는 받지 않아요. anthropic 1.0이 httpx2 위에 구축되어 클라이언트 생성 시 그것을 거부하기 때문이에요.
프로바이더가 만드는 AsyncAnthropic 클라이언트도 실패한 요청을 자체적으로 재시도해요. 기본적으로 max_retries=2라서 코드가 오류를 보기 전에 요청이 네트워크에 최대 세 번 도달할 수 있어요. 재시도 정책을 전송 계층에만 두려면 클라이언트를 직접 만들 때(예: anthropic_client=) max_retries=0을 전달하세요. 이 계층이 언제 작동하는지는 Provider SDK 재시도를 참고하세요.
모델 설정 (Model settings)
AnthropicModelSettings를 사용해 모델 동작을 커스터마이즈할 수 있어요:
from pydantic_ai import Agent
from pydantic_ai.models.anthropic import AnthropicModel, AnthropicModelSettings
model = AnthropicModel('claude-sonnet-4-5')
settings = AnthropicModelSettings(
temperature=0.2,
top_k=40,
service_tier='auto',
)
agent = Agent(model, model_settings=settings)
...
서비스 티어 (Service tier)
Anthropic은 서비스 티어를 제어해 지연 시간과 처리량을 관리하는 것을 지원해요. 통합 필드인 service_tier나 프로바이더 전용 필드인 anthropic_service_tier를 사용할 수 있어요. 둘 다 설정되면 anthropic_service_tier가 통합 필드보다 우선하며, Anthropic 고유 값('auto' 또는 'standard_only')을 받아요.
통합 필드는 Anthropic에서 다음과 같이 매핑돼요:
'auto':'auto'로 그대로 전달 (Anthropic 고유 값이며, 가능할 때 우선 처리량을 사용).'default':'standard_only'로 매핑 (표준 티어를 강제하고 우선 처리량을 거부).'flex'와'priority'는 Anthropic의 티어 모델에 없으므로 조용히 무시돼요.
클라우드 플랫폼 연동 (Cloud Platform Integrations)
AnthropicProvider에 커스텀 클라이언트를 전달해 클라우드 플랫폼을 통해 Anthropic 모델을 사용할 수 있어요.
AWS Bedrock
AWS Bedrock을 통해 Claude 모델을 사용하려면 Anthropic 문서에 따라 Bedrock 클라이언트를 설정한 뒤 AnthropicProvider에 전달하세요. 새 AsyncAnthropicBedrockMantle 클라이언트(Anthropic 권장, Messages API 사용)와 레거시 AsyncAnthropicBedrock 클라이언트(ARN 버전 모델 ID로 InvokeModel API 사용)를 모두 지원해요:
from anthropic import AsyncAnthropicBedrockMantle
from pydantic_ai import Agent
from pydantic_ai.models.anthropic import AnthropicModel
from pydantic_ai.providers.anthropic import AnthropicProvider
bedrock_client = AsyncAnthropicBedrockMantle() # 환경에서 AWS 자격 증명 사용
provider = AnthropicProvider(anthropic_client=bedrock_client)
model = AnthropicModel('anthropic.claude-haiku-4-5', provider=provider)
agent = Agent(model)
...
Bedrock vs BedrockConverseModel — 이 접근 방식은 Anthropic SDK를 AWS Bedrock 자격 증명과 함께 사용해요. AWS SDK(boto3)를 직접 사용하는 대안은
BedrockConverseModel을 참고하세요.
레거시
AsyncAnthropicBedrock클라이언트의 도구 검색 — 레거시InvokeModelAPI는bm25도구 검색 변형을 지원하지 않아요. 그래서ToolSearch가AsyncAnthropicBedrock클라이언트에서는 ('bm25'대신)'regex'로 기본 설정되고,ToolSearch(strategy='bm25')를 넘기면UserError가 발생해요.
레거시
AsyncAnthropicBedrock클라이언트의 토큰 계산 — Anthropic SDK는 Bedrock에서 고수준 토큰 계산 메서드를 차단해요. 그래서count_tokens()(및count_tokens_before_request)는 대신 Bedrock 자체/model/{model}/count-tokens엔드포인트를 호출해요. 이 엔드포인트는 기본(base) foundation-model ID(예:anthropic.claude-sonnet-4-20250514-v1:0)만 받아요. 리전 간 추론 프로필 ID(us./eu./global.접두사)와 수명이 끝난 모델 버전은 Bedrock이 거부해요.
Google Cloud
Google Cloud Vertex AI를 통해 Claude 모델을 사용하려면 Anthropic 문서에 따라 AsyncAnthropicVertex 클라이언트를 설정한 뒤 AnthropicProvider에 전달하세요:
from anthropic import AsyncAnthropicVertex
from pydantic_ai import Agent
from pydantic_ai.models.anthropic import AnthropicModel
from pydantic_ai.providers.anthropic import AnthropicProvider
vertex_client = AsyncAnthropicVertex(region='us-east5', project_id='your-project-id')
provider = AnthropicProvider(anthropic_client=vertex_client)
model = AnthropicModel('claude-sonnet-4-5', provider=provider)
agent = Agent(model)
...
Microsoft Foundry
Microsoft Foundry를 통해 Claude 모델을 사용하려면 Anthropic 문서에 따라 AsyncAnthropicFoundry 클라이언트를 설정한 뒤 AnthropicProvider에 전달하세요:
from anthropic import AsyncAnthropicFoundry
from pydantic_ai import Agent
from pydantic_ai.models.anthropic import AnthropicModel
from pydantic_ai.providers.anthropic import AnthropicProvider
foundry_client = AsyncAnthropicFoundry(
api_key='your-foundry-api-key', # 또는 ANTHROPIC_FOUNDRY_API_KEY 설정
resource='your-resource-name',
)
provider = AnthropicProvider(anthropic_client=foundry_client)
model = AnthropicModel('claude-sonnet-4-5', provider=provider)
agent = Agent(model)
...
설정 지침(Entra ID 인증 포함)은 Anthropic의 Microsoft Foundry 문서를 참고하세요.
작업 예산 (Task Budgets, Beta)
Anthropic의 작업 예산은 전체 에이전트 루프(thinking, 도구 호출, 도구 결과, 출력 포함)에 대한 조언용 토큰 예산을 Claude에 제공해서, 예산이 소비됨에 따라 모델이 페이스를 조절하고 우아하게 마무리할 수 있게 해줘요. AnthropicModelSettings.anthropic_task_budget으로 구성하며, AnthropicTaskBudget 페이로드를 받아 output_config.task_budget에 매핑해요.
Pydantic AI는 이 설정이 있으면 Anthropic의 필수 task-budgets-2026-03-13 베타를 자동으로 활성화해요. 지원은 현재 네이티브 Anthropic claude-fable-5, claude-fable-5-1, claude-mythos-5, claude-mythos-5-1, claude-opus-4-7, claude-opus-4-8, claude-opus-5, claude-opus-5-5, claude-sonnet-5 요청으로만 제한되며, Bedrock·Vertex·Microsoft Foundry Anthropic 모델 ID는 포함하지 않아요.
from pydantic_ai import Agent
from pydantic_ai.models.anthropic import AnthropicModel, AnthropicModelSettings
model = AnthropicModel('claude-opus-4-8')
settings = AnthropicModelSettings(
anthropic_task_budget={'type': 'tokens', 'total': 20_000},
)
agent = Agent(model, model_settings=settings)
...
작업 예산은 anthropic_effort와 함께 구성돼요. effort는 단계별 추론 깊이를 조절하고, 작업 예산은 루프 전체 총 작업량을 제한해요. 두 필드 모두 같은 output_config 객체 아래에 놓여요.
참고 — 작업 예산은 조언용이며 하드 상한이 아니에요. 강제 상한이 필요하면
max_tokens와 함께 사용하세요.
압축 중 예산 이어가기 (Carrying budgets across compaction)
서버 측 압축에 AnthropicCompaction을 사용한다면 이 절을 건너뛰어도 돼요. 서버가 카운트다운을 자체적으로 추적하므로 remaining은 비워두고 total이 스스로 조절하게 두세요.
task_budget의 remaining 필드는 클라이언트 측 압축 패턴을 위한 것이에요. 즉, 요청 사이에 이전 턴을 직접 요약해서 서버가 재작성 이전에 지출된 예산을 기억하지 못하는 경우를 위한 것이에요. Pydantic AI는 remaining을 추적하지 않아요. 다시 요청할 때 상위 요청들과 별개로 토큰 사용량을 직접 누적(예: 각 실행의 RunUsage)해서 다음 요청에 업데이트된 값을 전달하면, 카운트다운이 total로 리셋되는 대신 중단된 지점에서 이어져요. remaining을 설정하면 예산이 포함된 프롬프트 캐시 접두사도 무효화되므로, 캐싱을 유지하려면 total을 한 번 설정하고 서버가 실행 중 카운트다운에 맞춰 스스로 조절하게 두세요.
주의 —
task_budget.remaining은AnthropicCompaction과 상호 배타적이에요. 서버 측 압축이 예산을 자체적으로 추적하므로, Anthropic은 둘을 결합한 요청을 거부해요. 이 조합이 구성되면 Pydantic AI는 요청을 보내기 전에UserError를 발생시켜요. 하나를 선택하세요: 클라이언트 측 예산 추적용remaining또는 서버 측 압축용AnthropicCompaction.
프롬프트 캐싱 (Prompt Caching)
Anthropic은 프롬프트의 일부를 캐시해 비용을 줄이는 프롬프트 캐싱을 지원해요. Pydantic AI는 자동 캐싱, 블록별 메시지 캐싱, 명시적 캐시 중단점을 지원해요.
자동 캐싱 (Automatic Caching)
프롬프트 캐싱을 켜는 가장 간단한 방법은 AnthropicModelSettings.anthropic_cache예요. 이것은 Anthropic의 자동 캐싱을 사용하며, 최상위 cache_control 파라미터를 전달해 서버가 각 요청에서 마지막 캐시 가능 블록에 캐시 중단점을 자동 적용하게 해요:
from pydantic_ai import Agent
from pydantic_ai.models.anthropic import AnthropicModelSettings
agent = Agent(
'anthropic:claude-sonnet-4-6',
instructions='You are a helpful assistant.',
model_settings=AnthropicModelSettings(
anthropic_cache=True,
),
)
result1 = agent.run_sync('What is the capital of France?')
result2 = agent.run_sync(
'What is the capital of Germany?', message_history=result1.all_messages()
)
print(f'Cache write: {result1.usage.cache_write_tokens}')
print(f'Cache read: {result2.usage.cache_read_tokens}')
print(f'Cache hit ratio: {result2.usage.cache_hit_ratio}')
대화가 길어질수록 캐시 중단점이 앞으로 이동해야 하는 다중 턴 대화에 이상적이에요. anthropic_cache='1h'처럼 커스텀 TTL도 지정할 수 있어요.
Bedrock과 Vertex — Bedrock과 Vertex는 아직 자동 캐싱을 지원하지 않아요. 이 플랫폼에서는
anthropic_cache가 마지막 사용자 메시지에 블록별 캐싱으로 폴백돼 다중 턴 대화에서 같은 이점을 제공해요.
블록별 메시지 캐싱 (Per-block Message Caching)
anthropic_cache의 대안으로, AnthropicModelSettings.anthropic_cache_messages는 최상위 자동 캐싱 파라미터 대신 마지막 메시지의 마지막 콘텐츠 블록에 블록별 cache_control을 추가해요. Anthropic 메시지 형식을 받지만 최상위 자동 캐싱은 지원하지 않는 Anthropic 호환 게이트웨이·프록시(MiniMax, OpenRouter, LiteLLM 등)에서 사용하세요:
from anthropic import AsyncAnthropic
from pydantic_ai import Agent
from pydantic_ai.models.anthropic import AnthropicModel, AnthropicModelSettings
from pydantic_ai.providers.anthropic import AnthropicProvider
client = AsyncAnthropic(
api_key='your-api-key',
base_url='https://your-anthropic-compatible-gateway.example.com',
)
model = AnthropicModel(
'claude-sonnet-4-6',
provider=AnthropicProvider(anthropic_client=client),
)
agent = Agent(
model,
model_settings=AnthropicModelSettings(
anthropic_cache_messages=True,
),
)
result = agent.run_sync('What is the capital of France?')
print(result.output)
anthropic_cache_messages='1h'처럼 커스텀 TTL도 지정할 수 있어요. anthropic_cache_messages는 anthropic_cache와 결합할 수 없어요.
명시적 캐시 중단점 (Explicit Cache Breakpoints)
자동 캐싱 외에도 Pydantic AI는 특정 콘텐츠에 캐시 중단점을 두는 여러 방법을 제공해요:
CachePoint로 사용자 메시지 캐시: 사용자 메시지에CachePoint마커를 넣어 그 앞의 모든 것을 캐시하세요.- 마지막 메시지 블록 캐시:
AnthropicModelSettings.anthropic_cache_messages를True(기본 5m TTL)로 설정하거나'5m'/'1h'를 직접 지정하세요. - 시스템 지침 캐시:
AnthropicModelSettings.anthropic_cache_instructions를True(기본 5m TTL)로 설정하거나'5m'/'1h'를 직접 지정하세요. - 도구 정의 캐시:
AnthropicModelSettings.anthropic_cache_tool_definitions를True(기본 5m TTL)로 설정하거나'5m'/'1h'를 직접 지정하세요.
예시: 종합 캐싱 전략
최대 절감을 위해 자동 캐싱과 명시적 중단점을 결합하세요. 자동 캐싱이 대화를 처리하고, 명시적 중단점이 시스템 지침과 도구 정의를 고정해요:
from pydantic_ai import Agent, RunContext
from pydantic_ai.models.anthropic import AnthropicModelSettings
agent = Agent(
'anthropic:claude-sonnet-4-6',
instructions='Detailed instructions...',
model_settings=AnthropicModelSettings(
anthropic_cache=True, # 서버가 마지막 블록을 자동 캐시
anthropic_cache_instructions=True, # 시스템 지침을 명시적으로 캐시
anthropic_cache_tool_definitions='1h', # 도구 정의를 1h TTL로 명시적 캐시
),
)
@agent.tool
def search_docs(ctx: RunContext, query: str) -> str:
"""Search documentation."""
return f'Results for {query}'
result = agent.run_sync('Search for Python best practices')
print(result.output)
스마트 지침 캐싱 (Smart Instruction Caching)
anthropic_cache_instructions를 정적·동적 지침과 함께 사용하면, Pydantic AI는 캐시 경계를 최적 지점에 자동 배치해요. 정적 지침(Agent(instructions=...)에서)은 동적 지침(@agent.instructions 함수나 toolsets에서)보다 앞에 정렬되고, 캐시 지점은 마지막 정적 지침 부분 뒤에 배치돼요.
즉, 안정적인 정적 지침은 효율적으로 캐시되고, (요청 사이에 바뀔 수 있는) 동적 지침은 캐시 경계 밖에 남아 캐시 무효화를 일으키지 않아요.
from datetime import date
from pydantic_ai import Agent, RunContext
from pydantic_ai.models.anthropic import AnthropicModelSettings
agent = Agent(
'anthropic:claude-sonnet-4-6',
deps_type=str,
instructions='You are a helpful customer service agent. Follow company policy.', # (1)
model_settings=AnthropicModelSettings(
anthropic_cache_instructions=True, # (2)
),
)
@agent.instructions
def dynamic_context(ctx: RunContext[str]) -> str: # (3)
return f"Customer name: {ctx.deps}. Today's date: {date.today()}."
result = agent.run_sync('What is your return policy?', deps='Alice')
print(result.output)
정적 지침은 요청 간에 캐시돼요. 이것이 정적/동적 경계에 스마트 캐시 배치를 활성화해요. 동적 지침은 요청마다 바뀌므로 캐시되지 않아요.
CachePoint로 세밀한 제어 (Fine-Grained Control with CachePoint)
수동 CachePoint 마커로 캐시 위치를 정밀하게 제어하세요:
from pydantic_ai import Agent, CachePoint
agent = Agent(
'anthropic:claude-sonnet-4-6',
instructions='Instructions...',
)
# 특정 콘텐츠 블록의 캐시 포인트를 수동으로 제어
result = agent.run_sync([
'Long context from documentation...',
CachePoint(), # 이 지점까지 모든 것을 캐시
'First question'
])
print(result.output)
캐시 사용 통계 접근 (Accessing Cache Usage Statistics)
result.usage로 캐시 사용 통계에 접근하세요:
from pydantic_ai import Agent
from pydantic_ai.models.anthropic import AnthropicModelSettings
agent = Agent(
'anthropic:claude-sonnet-4-6',
instructions='Instructions...',
model_settings=AnthropicModelSettings(
anthropic_cache=True,
),
)
result = agent.run_sync('Your question')
usage = result.usage
print(f'Cache write tokens: {usage.cache_write_tokens}')
print(f'Cache read tokens: {usage.cache_read_tokens}')
캐시 포인트 제한 (Cache Point Limits)
Anthropic은 요청당 최대 4개의 캐시 포인트를 강제해요. Pydantic AI는 이 제한을 자동으로 관리해 요청이 항상 오류 없이 준수되도록 보장해요.
캐시 포인트 할당 방식 (How Cache Points Are Allocated)
캐시 포인트는 여러 소스에서 나올 수 있어요:
- 자동 캐싱:
anthropic_cache를 통해 (서버가 마지막 캐시 가능 블록에 1개 캐시 포인트 적용). - 마지막 메시지 블록:
anthropic_cache_messages설정을 통해 (마지막 메시지 콘텐츠 블록에 캐시 포인트 추가). - 시스템 프롬프트:
anthropic_cache_instructions설정을 통해 (마지막 시스템 프롬프트 블록에 캐시 포인트 추가). - 도구 정의:
anthropic_cache_tool_definitions설정을 통해 (마지막 도구 정의에 캐시 포인트 추가). - 메시지:
CachePoint마커를 통해 (메시지 콘텐츠에 캐시 포인트 추가).
각 설정은 최대 1개 캐시 포인트를 사용하지만, anthropic_cache와 anthropic_cache_messages(상호 배타적)를 제외하면 결합할 수 있어요. 총합이 4를 초과하면 Pydantic AI가 오래된 메시지의 초과 캐시 포인트를 자동으로 잘라내요.
예시: 자동·명시적 캐싱 결합
자동 캐싱과 명시적 중단점이 있는 에이전트를 정의하세요:
from pydantic_ai import Agent, CachePoint
from pydantic_ai.models.anthropic import AnthropicModelSettings
agent = Agent(
'anthropic:claude-sonnet-4-6',
instructions='Detailed instructions...',
model_settings=AnthropicModelSettings(
anthropic_cache=True, # 1 캐시 포인트 (서버 적용)
anthropic_cache_instructions=True, # 1 캐시 포인트
anthropic_cache_tool_definitions=True, # 1 캐시 포인트
),
)
@agent.tool_plain
def my_tool() -> str:
return 'result'
# 4개 슬롯 중 3개 사용 (자동 1 + 지침 1 + 도구 1)
# 명시적 CachePoint 마커 1개 여유
result = agent.run_sync([
'Context', CachePoint(), # 4번째 캐시 포인트 - OK
'Question'
])
print(result.output)
usage = result.usage
print(f'Cache write tokens: {usage.cache_write_tokens}')
print(f'Cache read tokens: {usage.cache_read_tokens}')
자동 캐시 포인트 제한 (Automatic Cache Point Limiting)
모든 소스(설정 + CachePoint 마커)의 명시적 캐시 포인트가 가용 예산을 초과하면, Pydantic AI는 오래된 메시지 콘텐츠(가장 최근 것은 유지)에서 초과 캐시 포인트를 자동으로 제거해요.
설정에서 2개 명시적 캐시 포인트를 가진 에이전트를 정의하세요:
from pydantic_ai import Agent, CachePoint
from pydantic_ai.models.anthropic import AnthropicModelSettings
agent = Agent(
'anthropic:claude-sonnet-4-6',
instructions='Instructions...',
model_settings=AnthropicModelSettings(
anthropic_cache_instructions=True, # 1 캐시 포인트
anthropic_cache_tool_definitions=True, # 1 캐시 포인트
),
)
@agent.tool_plain
def search() -> str:
return 'data'
# 이미 2개 캐시 포인트 사용 중 (지침 + 도구)
# CachePoint 마커 2개 더 추가 가능 (총 4개 제한)
result = agent.run_sync([
'Context 1', CachePoint(), # 가장 오래됨 - 제거됨
'Context 2', CachePoint(), # 유지됨 (3번째 포인트)
'Context 3', CachePoint(), # 유지됨 (4번째 포인트)
'Question'
])
# 최종 캐시 포인트: 지침 + 도구 + Context 2 + Context 3 = 4
print(result.output)
usage = result.usage
print(f'Cache write tokens: {usage.cache_write_tokens}')
print(f'Cache read tokens: {usage.cache_read_tokens}')
핵심 요점:
- 시스템·도구 캐시 포인트는 항상 유지돼요.
anthropic_cache는anthropic_cache_instructions,anthropic_cache_tool_definitions처럼 1개 캐시 포인트로 계산돼요.- 제한을 초과하면 메시지의
CachePoint마커가 오래된 것부터 제거돼요. - 이렇게 하면 메시지 수준 캐싱의 이점을 누리면서도 중요한 캐싱(지침/도구)이 유지돼요.
대화 중간 시스템 메시지 (Mid-conversation system messages)
긴 세션 도중에 에이전트의 system_prompt에 지침을 추가하면 프롬프트의 앞부분을 다시 쓰는데, 이는 그 뒤의 모든 캐시된 접두사를 무효화해요. Anthropic은 시스템 메시지를 대화 안쪽, 즉 지침 자체의 히스토리 위치(앞쪽이 아니라)에 받아들이는 방식으로 이를 피해요. 그래서 그 지점까지 캐시된 모든 것이 캐시된 채 유지돼요.
첫 번째 ModelRequest 밖의 모든 SystemPromptPart는 대화 중간 지침이에요 — 저장된 message_history에서 왔든 실행 중 RunContext.enqueue에서 왔든 상관없어요. 추가로 켤 것은 없어요:
from pydantic_ai import Agent, RunContext, SystemPromptPart
agent = Agent('anthropic:claude-opus-4-8', system_prompt='You are a code reviewer.')
@agent.tool
def require_type_annotations(ctx: RunContext[None]) -> str:
ctx.enqueue(SystemPromptPart(content='Every suggestion must include explicit type annotations.'))
return 'rule added'
지침을 제자리에 두면 그 앞의 접두사가 재사용 가능하지만, 자체적으로 캐싱을 켜지는 않아요 — 그건 여전히 anthropic_cache, anthropic_cache_messages, 명시적 CachePoint에서 나와요. 큐에 넣은 배치 끝의 CachePoint는 그 배치에서 그 앞의 모든 것(지침 포함)을 캐시해요. 뒤에 더 많은 콘텐츠가 있는 포인트는 놓은 지점까지 캐시하고 지침을 밖에 남겨요. 지침은 동반하는 콘텐츠 뒤에 전송되므로, 콘텐츠가 밖에 있는 경계 안에 있을 수 없어요.
지원은 모델과 전송 방식에 따라 달라져요. Microsoft Foundry 통합은 이 역할을 서빙하지 않고, 일부 Claude 모델은 항목을 받아들이지만 실행하지 않아요. 현재 목록은 Anthropic의 대화 중간 시스템 메시지 문서에 있어요. Pydantic AI는 사용 중인 모델·전송 방식에 맞는 렌더링을 선택하며, 같은 위치에 <system> 태그가 붙은 사용자 메시지로 폴백하므로 어느 쪽이든 지침이 놓은 곳에 적용돼요.
둘의 차이는 모델이 사용자로부터 받아들이기를 주저해야 하는 지침에서 드러나요. 네이티브 항목이 주어지면 Claude는 상위 프롬프트가 설정한 제한을 들어올리지만, <system> 태그에 있는 동일한 텍스트는 거부해요. 신뢰할 것이 없는 지침(예: 형식 변경)에는 둘 다 작동해요.
이것이 프로바이더 간에 어떻게 동작하는지, 어떻게 구절하는지, 신뢰할 수 없는 콘텐츠가 여기에 들어가면 안 되는 이유는 대화 중간 시스템 프롬프트를 참고하세요.
배치 (Placement) — Anthropic은 시스템 메시지가 사용자 턴과 모델의 답변 사이에 있어야 한다고 요구해요. 그래서 Pydantic AI는 히스토리가 이미 그 조건을 충족하지 않으면 위치를 조정해요. 사용자 콘텐츠가 함께 없는 지침에는 따라올 최소
.사용자 메시지가 붙고, 다른 사용자 턴 앞에 놓일 지침은 자신이 제어하는 답변 바로 앞으로 이동해요. 어느 쪽도 지침이 적용되는 턴을 바꾸지 않아요 — 와이어에서 어디에 앉는지만 바꿔요.
빠른 모드 (Fast mode)
빠른 모드는 초당 더 많은 출력 토큰을 제공하며 현재 Claude Opus 4.6, Claude Opus 4.7, Claude Opus 4.8, Claude Opus 5, Claude Opus 5.5에서 지원돼요. 연구 프리뷰예요. anthropic_speed를 'fast'로 설정해 켜세요. 그러면 Pydantic AI가 필수 fast-mode-2026-02-01 베타를 자동으로 추가해요. 지원되지 않는 모델에서는 anthropic_speed='fast'가 UserWarning과 함께 무시돼요. 가격, 속도 제한, 지원 모델의 최신 목록은 Anthropic 빠른 모드 문서를 참고하세요.
from pydantic_ai import Agent
from pydantic_ai.models.anthropic import AnthropicModelSettings
agent = Agent(
'anthropic:claude-opus-4-8',
model_settings=AnthropicModelSettings(anthropic_speed='fast'),
)
...
프롬프트 캐시 상호작용 —
'fast'와'standard'사이를 전환하면 프롬프트 캐시가 무효화돼요. 다른 속도의 요청은 캐시된 접두사를 공유하지 않으므로, 캐시에 민감한 대화에서는 속도 하나를 선택하세요.
Bedrock, Vertex, Foundry — 빠른 모드는 직접 Anthropic API에서만 사용할 수 있어요. Bedrock·Vertex·Foundry 클라이언트는
speed파라미터를 지원하지 않으므로, 그 클라이언트에서는anthropic_speed='fast'가UserWarning과 함께 무시돼요.
강제 도구 선택 (Forced tool choice)
대부분의 Anthropic 모델은 tool_choice='required'(또는 도구 이름 목록)로 도구 호출을 강제하게 해요. 단, 확장 thinking이 활성화된 동안은 예외예요. 적응형 thinking은 강제 호출과 호환돼요. Anthropic은 Claude Fable 5.1, Claude Mythos 5.1, Claude Opus 5.5를 thinking 없이도 강제 도구 선택을 무조건 거부하는 것으로 문서화하며, Pydantic AI는 이를 anthropic_supports_forced_tool_choice=False로 표시해요.
강제를 지원하지 않는 모델에서:
- 명시적
tool_choice='required'(또는 도구 이름 목록)는UserError를 발생시켜요. 대신tool_choice='auto'를 사용하세요. - Pydantic AI가 대신 해결한
required선택(예: 출력 도구에서)은'auto'로 부드럽게 폴백돼요. 해결된 선택이 단일 도구를 지목했다면tool_choice가'auto'로 남는 동안 가용 도구 목록이 그 도구로 필터링돼요. 캐시된 접두사에 도구 배열이 포함되므로 Anthropic의 프롬프트 캐시도 무효화돼요. 따라서 모델이 호출하는 대신 텍스트로 답할 수 있는데, 출력 도구가 필수면 Pydantic AI는 도구 호출 프롬프트로 재시도해요.
Tool Output이 강제 도구 선택으로 해결되므로 확장 thinking과도 호환되지 않아요. 베어 구조화된 output_type은 Native Output(또는 JSON 스키마 지원 없는 모델에서는 Prompted Output)으로 전환되고, 명시적 ToolOutput(...)는 UserError를 발생시켜요. 적응형 thinking은 Tool Output을 유지해요 — 단, 위에서 강제 자체를 거부하는 모델은 제외해요. 이 모델들은 thinking 설정이 있으면 항상 그랬던 것처럼 동작해요. 베어 구조화된 output_type은 Tool Output에서 전환되고, 명시적 ToolOutput(...)는 UserError를 발생시켜요.
thinking 블록 바인딩 (Thinking block binding)
Claude Fable 5.1과 Claude Opus 5.5는 각 thinking 블록을 그것을 만든 대화 접두사에 바인딩해요. 그 접두사가 바뀐 뒤 메시지 히스토리를 재생하면 400(The block is bound to a different conversation)으로 실패해요. Pydantic AI의 두 가지 일반 기능이 그것을 바꿔요:
둘 다 프로바이더 프롬프트 캐시를 잃게 하는 것과 같은 불안정성이에요. 턴 사이에 바뀌는 요청 접두사 말이에요. thinking 블록은 그것을 볼 수 있는 400으로 만들고, 캐시는 볼 수 없는 청구서로 만들어요. 바뀐 뒤의 모든 요청이 전체 대화를 캐시되지 않은 요율로 조용히 재전송하거든요. 접두사를 안정적으로 유지할 수 있다면, 거부를 처리하는 것보다 그것이 더 가치 있어요.
Anthropic은 2026년 8월 31일 이후 생성된 계정에 대해 검사를 강제해요. 오래된 계정은 불일치를 기록하지만, 요청이 thinking.block_binding.prefix_mismatch_behavior를 설정한 경우에만 그에 따라 작동해요.
Pydantic AI는 기본적으로 아무것도 설정하지 않아요. 그래서 오래된 계정은 reasoning을 그대로 재생해요. 검사가 강제되는 곳에서는 거부된 요청이 prefix_mismatch_behavior='drop_block'으로 한 번 재시도돼요. 오래된 블록이 버려지고 실행이 계속되며, AnthropicStaleThinkingBlockWarning이 무슨 일이 있었는지 설명해요. 모델은 더 이상 그 턴의 reasoning을 보지 못해요 — 실패한 실행에 한 턴의 thinking을 맞바꾸는 거예요. anthropic_binds_thinking_blocks=True로 표시된 모델만 재시도해요.
Anthropic은 드롭을 한 요청에만 적용해요. 그 응답이 변환을 기록하므로, Pydantic AI는 그 응답 히스토리를 사용해 영향받는 대화의 나머지에서 drop_block을 계속 보내요. 이렇게 하면 모델에 가변 상태를 저장하거나 무관한 대화를 바꾸지 않고도 이후 모든 턴에서 거부된 요청을 피할 수 있어요. 같은 동작이 count_tokens()에도 적용돼요. 토큰 계산은 첫 번째 일치하는 거부를 한 번 재시도하고, 복구 히스토리를 나르는 이후 계산은 드롭을 즉시 보내요. 계산 중에만 보인 복구는 이후 계산에만 적용돼요. 이 엔드포인트는 서버 측 도구를 생략해서 추론과 다른 접두사를 가질 수 있기 때문이에요. 명시적 block_binding은 계산과 추론 모두에서 여전히 우선해요.
자동 동작은 직접 Anthropic API, Pydantic AI Gateway 및 기타 AsyncAnthropic 호환 프록시, Claude Platform on AWS, 레거시 Amazon Bedrock, Google Vertex AI에서 사용할 수 있어요. AWS 운영 Bedrock Messages API 클라이언트(AsyncAnthropicBedrockMantle)에서는 활성화되지 않아요(이 클라이언트는 Anthropic 베타 헤더를 받지 않음). Microsoft Foundry도 현재 이 베타가 문서화되지 않아 활성화되지 않아요. 모든 전송에서 명시적 설정은 그대로 전달돼요.
Anthropic은 모든 드롭을 보고하고, Pydantic AI는 두 가지 방식으로 표면화해요. 계측 하에서 Pydantic AI 모델 요청 스팬은 anthropic.input_transformations 이벤트를 지니므로, 드롭이 발생할 때 트레이스에 보여요. 무관한 주변 애플리케이션 스팬은 절대 수정되지 않아요. 응답에서는 항상 provider_details에 기록돼요:
from pydantic_ai import Agent
from pydantic_ai.messages import ModelResponse
agent = Agent('anthropic:claude-fable-5-1')
result = agent.run_sync('What is the capital of France?')
for message in result.new_messages():
if isinstance(message, ModelResponse) and message.provider_details:
for transformation in message.provider_details.get('input_transformations', []):
print(transformation['path'], transformation['reason'])
거부된 요청(그리고 경고)을 건너뛰려면 드롭을 처음부터 요청하세요. Pydantic AI는 명시적 block_binding을 주어진 대로, 필드가 요구하는 베타와 함께 보내고 절대 재시도하지 않아요:
from pydantic_ai import Agent
from pydantic_ai.models.anthropic import AnthropicModelSettings
settings: AnthropicModelSettings = {
'anthropic_thinking': {
'type': 'adaptive',
'block_binding': {'prefix_mismatch_behavior': 'drop_block'},
}
}
agent = Agent('anthropic:claude-fable-5-1', model_settings=settings)
...
reasoning을 잃는 대신 크게 실패하려면 같은 자리에 'error'를 설정하세요. 재시도를 유지하되 경고만 듣지 않으려면 경고를 필터링하세요:
import warnings
from pydantic_ai.models.anthropic import AnthropicStaleThinkingBlockWarning
warnings.simplefilter('ignore', AnthropicStaleThinkingBlockWarning)
세 번째 동작은 없어요. prefix_mismatch_behavior는 'error' 또는 'drop_block' 중 하나예요. None을 전달하면 Anthropic의 계정 기본값을 명시적으로 요청하는 것이며, 검사가 강제되지 않는 곳에서 블록을 유지해요.
thinking 블록을 바인딩하지 않는 모델은 기본적으로 영향을 받지 않아요. 명시적 block_binding이 없으면 요청에 필드도 바인딩 베타도 지니지 않고, 그 400은 재시도되지 않아요. block_binding을 직접 설정하면 어떤 모델이든 둘 다 와이어에 올라가요 — 베타는 프로파일 플래그가 아니라 필드를 따라가요 — 그리고 그러한 요청도 재시도되지 않아요. Anthropic은 Claude Mythos 5.1을 이 검사를 실행하지 않는 것으로 문서화하므로, 그것도 표시되지 않아요.
메시지 압축 (Message Compaction)
Anthropic은 긴 대화를 관리하는 자동 컨텍스트 압축을 지원해요. 입력 토큰이 구성된 임계값을 초과하면 API가 컨텍스트를 보존하면서 오래된 메시지를 대체하는 요약을 자동 생성해요.
압축 후에는 이후 요청이 최신 압축 블록부터 압축된 창만 보내므로 요청 크기가 줄어들어요 — 어느 쪽이든 API는 이전 콘텐츠를 무시해요. 상주 시스템 프롬프트는 영향을 받지 않아요. 별도의 system 파라미터로 전송되며 압축이 대체하지 않기 때문이에요.
압축을 켜는 가장 쉬운 방법은 AnthropicCompaction capability예요:
from pydantic_ai import Agent
from pydantic_ai.models.anthropic import AnthropicCompaction
agent = Agent(
'anthropic:claude-sonnet-4-6',
capabilities=[AnthropicCompaction(token_threshold=100_000)],
)
capability는 다음을 받아요:
token_threshold(기본: 150,000, 최소: 50,000): 입력 토큰이 이 값을 초과하면 압축이 트리거돼요.instructions: 요약을 생성하는 방법에 대한 커스텀 지침.pause_after_compaction:True면 응답이stop_reason='compaction'으로 압축 블록 뒤에 멈춰서, 계속하기 전에 명시적 처리를 허용해요.
대안으로 모델 설정을 통해 anthropic_context_management로 압축을 직접 구성할 수도 있어요:
from pydantic_ai import Agent
from pydantic_ai.models.anthropic import AnthropicModelSettings
agent = Agent('anthropic:claude-sonnet-4-6')
result = agent.run_sync(
'Hello!',
model_settings=AnthropicModelSettings(
anthropic_context_management={
'edits': [{'type': 'compact_20260112', 'trigger': {'type': 'input_tokens', 'value': 100_000}}]
}
),
)
참고 — Anthropic이 반환한 압축 블록은 읽을 수 있는 텍스트 요약을 담고 있어요. 메시지 히스토리에 포함되면 이후 요청에서 자동으로 왕복 처리돼요.
코드 실행 도구 버전 (Code Execution Tool Version)
기본적으로 Pydantic AI는 선택한 모델에 호환되는 Anthropic 코드 실행 도구 버전을 골라요. 특정 지원되는 Anthropic 도구 버전이 필요하면 AnthropicModelSettings.anthropic_code_execution_tool_version으로 이를 재정의할 수 있어요:
from pydantic_ai import Agent, CodeExecutionTool
from pydantic_ai.capabilities import NativeTool
from pydantic_ai.models.anthropic import AnthropicModelSettings
agent = Agent(
'anthropic:claude-sonnet-4-6',
capabilities=[NativeTool(CodeExecutionTool())],
model_settings=AnthropicModelSettings(anthropic_code_execution_tool_version='20260120'),
)
모델이 지원하지 않는 도구 버전을 명시적으로 선택하면 Pydantic AI가 UserError를 발생시켜요.
코드 실행 컨테이너 (Code Execution Containers)
메시지 히스토리에서 실행을 계속하면, Pydantic AI는 그 히스토리에 기록된 Anthropic 코드 실행 컨테이너를 자동으로 재사용해요. Anthropic 컨테이너는 30일 후에 만료되며, 만료된 컨테이너를 참조하는 요청은 오류를 반환해요.
CodeExecutionTool로 파일을 업로드하는 요청에서 히스토리 파생 컨테이너에 대해 Anthropic이 HTTP 500을 반환하면, Pydantic AI는 거부된 컨테이너 ID 없이 한 번 재시도해서 Anthropic이 새 컨테이너를 만들고 업로드를 받게 해요. 다른 오류는 이 재시도 없이 발생해요. 새 컨테이너에는 만료된 컨테이너의 상태나 파일이 없어요.
컨테이너 연속성이 필요하면 anthropic_container을 명시적으로 설정하세요. 명시적으로 구성된 컨테이너는 절대 자동 교체되지 않으며, 대신 Anthropic의 원래 오류가 발생해요.