Claude Platform Docs
Messages컨텍스트 관리

토큰 카운팅

Claude에 메시지를 보내기 전에 메시지의 토큰 수를 계산합니다. 토큰 수를 사용하여 속도 제한과 비용을 관리하고, 모델 라우팅 결정을 내리고, 프롬프트를 목표 길이에 맞추세요.

"Token counting"(토큰 카운팅)을 사용하면 Claude에 메시지를 보내기 전에 메시지의 토큰 수를 확인할 수 있습니다. 이를 통해 프롬프트와 사용량에 대해 정보에 기반한 결정을 내릴 수 있습니다. 토큰 카운팅을 사용하면 다음을 수행할 수 있습니다:

  • "rate limit"(속도 제한)과 비용을 사전에 관리
  • 현명한 모델 라우팅 결정
  • 프롬프트를 특정 길이로 최적화

메시지 토큰을 계산하는 방법

토큰 카운팅 엔드포인트는 메시지 생성과 동일한 구조화된 입력 목록을 받으며, "system prompt"(시스템 프롬프트), 도구, 이미지, PDF를 지원합니다. 응답에는 총 입력 토큰 수가 포함됩니다.

이 엔드포인트는 Messages API가 허용하는 일부 입력에 대해 invalid_request_error를 반환합니다. 해당 입력은 웹 검색, 웹 가져오기, 코드 실행, 도구 검색과 같은 서버 도구(advisor 도구를 제외한 모든 서버 도구), MCP 커넥터, 그리고 url 또는 file 소스를 사용하는 image 또는 document 블록입니다. 이미지와 PDF의 토큰 수를 계산하려면 base64로 보내세요. 서버 도구나 MCP 서버를 사용하는 요청의 경우, Messages API 응답의 usage 객체에 사용된 토큰이 보고됩니다.

지원 모델

모든 활성 모델이 토큰 카운팅을 지원합니다.

기본 메시지의 토큰 계산

client = anthropic.Anthropic()

response = client.messages.count_tokens(
    model="claude-opus-5-5",
    system="You are a scientist",
    messages=[{"role": "user", "content": "Hello, Claude"}],
)

print(response.json())
Output
{ "input_tokens": 14 }

도구가 포함된 메시지의 토큰 계산

client = anthropic.Anthropic()

response = client.messages.count_tokens(
    model="claude-opus-5-5",
    tools=[
        {
            "name": "get_weather",
            "description": "Get the current weather in a given location",
            "input_schema": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "The city and state, e.g. San Francisco, CA",
                    }
                },
                "required": ["location"],
            },
        }
    ],
    messages=[{"role": "user", "content": "What's the weather like in San Francisco?"}],
)

print(response.json())
Output
{ "input_tokens": 403 }

이미지가 포함된 메시지의 토큰 계산

import base64
import httpx2

image_url = "https://platform.claude.com/docs/images/vision-example.jpg"
image_media_type = "image/jpeg"
image_data = base64.standard_b64encode(httpx2.get(image_url).content).decode("utf-8")

client = anthropic.Anthropic()

response = client.messages.count_tokens(
    model="claude-opus-5-5",
    messages=[
        {
            "role": "user",
            "content": [
                {
                    "type": "image",
                    "source": {
                        "type": "base64",
                        "media_type": image_media_type,
                        "data": image_data,
                    },
                },
                {"type": "text", "text": "Describe this image"},
            ],
        }
    ],
)
print(response.json())
Output
{ "input_tokens": 1028 }

"oversized_image": "error"를 설정한 임베디드 이미지 블록은 Messages API가 거부하는 것과 정확히 동일하게 카운트 시점에 거부됩니다.

사고가 포함된 메시지의 토큰 계산

client = anthropic.Anthropic()

response = client.messages.count_tokens(
    model="claude-opus-5-5",
    thinking={"type": "adaptive"},
    messages=[
        {
            "role": "user",
            "content": "Are there an infinite number of prime numbers such that n mod 4 == 3?",
        },
        {
            "role": "assistant",
            "content": [
                {
                    "type": "thinking",
                    "thinking": "This is a nice number theory question. Let's think about it step by step...",
                    "signature": "EuYBCkQYAiJAgCs1le6/Pol5Z4/JMomVOouGrWdhYNsH3ukzUECbB6iWrSQtsQuRHJID6lWV...",
                },
                {
                    "type": "text",
                    "text": "Yes, there are infinitely many prime numbers p such that p mod 4 = 3...",
                },
            ],
        },
        {"role": "user", "content": "Can you write a formal proof?"},
    ],
)

print(response.json())
Output
{ "input_tokens": 88 }

PDF가 포함된 메시지의 토큰 계산

import base64
import anthropic

client = anthropic.Anthropic()

with open("/path/to/document.pdf", "rb") as pdf_file:
    pdf_base64 = base64.standard_b64encode(pdf_file.read()).decode("utf-8")

response = client.messages.count_tokens(
    model="claude-opus-5-5",
    messages=[
        {
            "role": "user",
            "content": [
                {
                    "type": "document",
                    "source": {
                        "type": "base64",
                        "media_type": "application/pdf",
                        "data": pdf_base64,
                    },
                },
                {"type": "text", "text": "Please summarize this document."},
            ],
        }
    ],
)

print(response.json())
Output
{ "input_tokens": 2188 }

Claude Fable 및 Claude Mythos 모델의 토큰 수

Claude Fable 5.1, Claude Mythos 5.1, Claude Fable 5, Claude Mythos 5는 Claude Opus 4.7과 함께 도입된 토크나이저를 공유합니다. 프롬프트는 네 모델 모두에서 동일하게 계산되며, Claude Opus 4.7 이전 모델보다 약 30퍼센트 더 높게 계산됩니다(정확한 증가량은 콘텐츠에 따라 다릅니다). 토큰 카운팅 엔드포인트는 전달한 model의 토크나이저를 기준으로 계산합니다. 워크로드에 대한 차이를 측정하려면 동일한 요청을 현재 모델로 한 번, 이동하려는 모델로 한 번, 총 두 번 계산한 다음 두 input_tokens 값을 비교하세요.


가격 및 속도 제한

토큰 카운팅은 무료로 사용할 수 있지만 사용 등급에 따른 분당 요청 수 속도 제한이 적용됩니다. 더 높은 한도가 필요한 경우 속도 제한 페이지에서 Request rate limit increase를 사용하세요.

사용 등급분당 요청 수(RPM)
Start5,000
Build10,000
Scale20,000

FAQ


다음 단계

토큰 카운팅 엔드포인트에 대한 전체 API 레퍼런스를 읽어보세요.

토큰 수를 사용하여 프롬프트를 모델의 컨텍스트 윈도우 내로 유지하세요.

요청을 보내기 전에 토큰 수를 확인하여 사용 등급 내로 유지하세요.

프롬프트 접두사를 캐싱하여 반복되는 프롬프트의 비용과 지연 시간을 줄이세요.

Compatibility

Supported platforms
  • Claude API
  • Claude Platform on AWS
  • Amazon Bedrock
  • Google Cloud
  • Microsoft Foundry

Was this page helpful?