AnthropicTokenCounter
AnthropicTokenCounter
AnthropicTokenCounter는 Anthropic의 POST /v1/messages/count_tokens 엔드포인트로 특정 Claude 모델에 대한 ChatMessage 객체와 선택적 도구 스키마의 입력 토큰을 세어요. 엔드포인트는 응답을 생성하지 않고 정확한 개수를 반환하므로 생성 비용이 들지 않아요.
Import path: haystack_integrations.token_counters.anthropic.AnthropicTokenCounter
필수 init 변수: model — 개수를 셀 Claude 모델
API reference: Anthropic
GitHub link: https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/anthropic
Package name: anthropic-haystack
출처: 문서
본문
원격 API를 호출하기 때문에 Anthropic API 키가 필요하고 매 횟수마다 네트워크 지연이 더해져요. Claude 모델에 대해 정확하고 모델별 개수가 필요할 때 사용하세요. 로컬 추정이 필요하면 ApproximateTokenCounter나 TiktokenCounter를 쓰세요.
Installation
anthropic-haystack 패키지를 설치하세요:
pip install anthropic-haystack
Usage
토큰 개수는 모델별로 다르므로, 생성에 사용할 모델을 전달하세요:
from haystack.dataclasses import ChatMessage
from haystack_integrations.token_counters.anthropic import AnthropicTokenCounter
messages = [
ChatMessage.from_system("You are a helpful assistant."),
ChatMessage.from_user("Explain retrieval-augmented generation."),
]
counter = AnthropicTokenCounter(model="claude-sonnet-4-5")
token_count = counter.count(messages)
print(token_count)
기본적으로 카운터는 ANTHROPIC_API_KEY 환경 변수에서 API 키를 읽습니다. Haystack Secret을 명시적으로 전달하고, 기본 Anthropic 클라이언트의 HTTP timeout과 max_retries를 설정할 수도 있어요:
from haystack.utils import Secret
counter = AnthropicTokenCounter(
model="claude-sonnet-4-5",
api_key=Secret.from_env_var("MY_ANTHROPIC_API_KEY"),
timeout=30.0,
max_retries=3,
)
도구 스키마가 소비하는 컨텍스트를 포함하려면 count()에 도구를 전달하세요:
token_count = counter.count(messages, tools=[search_tool])
카운터는 count()를 처음 호출할 때 API 클라이언트를 만들어요. 대신 애플리케이션 시작 시 만들려면 warm_up()을 명시적으로 호출하세요. 사용이 끝나면 close()를 호출해 클라이언트의 HTTP 리소스를 해제합니다:
counter.warm_up()
...
counter.close()
Non-text content
Anthropic은 이미지와 PDF 파일을 요청의 일부로 세므로, 카운터는 평면 추정치를 적용하는 대신 그 항목들을 정확히 측정해요. AnthropicChatGenerator와 같은 콘텐츠 타입을 지원합니다: JPEG, PNG, GIF, WebP 이미지와 application/pdf 파일이요. 다른 MIME 타입은 추정되는 대신 오류를 발생시켜요.
Use with compaction
count를 CompactionHook에 전달하면, Claude가 쓰는 토크나이저와 같은 방식으로 Agent 대화의 크기를 재요:
from haystack.hooks.compaction import CompactionHook, SlidingWindowCompactor
compaction_hook = CompactionHook(
compactor=SlidingWindowCompactor(),
context_window=200_000,
token_counter=AnthropicTokenCounter(model="claude-sonnet-4-5"),
)
참고로 훅은 매 Agent 스텝마다 메시지를 세므로, 매 컴팩션 검사가 API 왕복 한 번을 소비해요.
더 알아보기 (Learn more)
- ApproximateTokenCounter — 로컬 추정 카운터
- CompactionHook — 컨텍스트 컴팩션
- AnthropicChatGenerator — Anthropic 채팅 생성기