본문으로 건너뛰기

[pydantic-ai] Anthropic 캐시 가능 타입에 document 추가

PR 링크: pydantic/pydantic-ai#3513 상태: Merged | 변경: +3 / -3

들어가며

Pydantic AI는 Anthropic의 prompt caching 기능을 지원하여 반복 요청의 비용을 절감합니다. 캐시를 적용하려면 content block의 type이 허용 목록에 포함되어야 하는데, Anthropic API가 지원하는 document 타입이 이 목록에서 빠져 있었습니다. 결과적으로 PDF 등의 문서를 포함한 프롬프트에 캐시가 적용되지 않는 문제가 있었습니다.

핵심 코드 분석

cacheable_types에 document 추가

Before (anthropic.py):

cacheable_types = {'text', 'tool_use', 'server_tool_use', 'image', 'tool_result'}

After:

cacheable_types = {'text', 'tool_use', 'server_tool_use', 'image', 'tool_result', 'document'}

Anthropic 공식 문서에 명시된 캐시 가능 타입 목록에 맞춰 document를 추가했습니다. 이로써 PDF, 텍스트 파일 등 document 타입의 content block에도 cache_control이 정상적으로 부여됩니다.

테스트 업데이트

Before (test_anthropic.py):

params: list[dict[str, Any]] = [{'type': 'document', 'source': {'data': 'test'}}]
with pytest.raises(UserError, match='Cache control not supported for param type: document'):
    AnthropicModel._add_cache_control_to_last_param(params)

After:

params: list[dict[str, Any]] = [{'type': 'thinking', 'source': {'data': 'test'}}]
with pytest.raises(UserError, match='Cache control not supported for param type: thinking'):
    AnthropicModel._add_cache_control_to_last_param(params)

기존에 document가 지원되지 않는 타입으로 테스트했던 부분을 실제로 지원되지 않는 thinking 타입으로 변경하여 에러 케이스 테스트를 유지합니다.

왜 이게 좋은가

  • Anthropic API의 document 타입(PDF 등)을 포함한 프롬프트에서 prompt caching이 정상 동작합니다.
  • 문서 기반 RAG나 대용량 컨텍스트 전달 시 캐시를 통해 최대 90%의 비용을 절감할 수 있습니다.
  • 3줄 변경으로 API 명세와의 불일치를 해결한 간결한 수정입니다.

정리

  • 외부 API의 지원 타입 목록은 주기적으로 점검하라: API가 새 타입을 추가하면 클라이언트 코드의 허용 목록도 함께 업데이트해야 합니다.
  • 에러 테스트의 입력값이 실제 에러 케이스인지 확인하라: 지원 범위가 변경되면 테스트의 전제도 함께 검증해야 합니다.

참고 자료

⚠️ 알림: 이 분석은 AI가 실제 코드 diff를 기반으로 작성했습니다.

댓글

관련 포스트

PR Analysis 의 다른글