Claude Platform Docs
Messages上下文管理

令牌计数

在将消息发送给 Claude 之前计算其中的令牌数。使用令牌计数来管理速率限制和成本、做出模型路由决策,并使提示符合目标长度。

"Token counting"(令牌计数)让您能够在将消息发送给 Claude 之前确定其中的令牌(token)数量。这有助于您在提示和用量方面做出明智的决策。借助令牌计数,您可以:

  • 主动管理 "rate limits"(速率限制)和成本
  • 做出明智的 "model routing"(模型路由)决策
  • 将提示优化到特定长度

如何计算消息令牌数

令牌计数端点接受与创建消息相同的结构化输入列表,包括对系统提示、工具、图像和 PDF 的支持。响应中包含输入令牌的总数。

对于 Messages API 接受的少数几种输入,此端点会返回 invalid_request_error:服务器工具(例如网络搜索、网页获取、代码执行和工具搜索,即除 advisor 工具之外的所有服务器工具)、MCP 连接器,以及使用 url 或 file 来源的 image 或 document 块。请以 base64 格式发送图像和 PDF 以对其进行计数。对于使用服务器工具或 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

常见问题


后续步骤

阅读令牌计数端点的完整 API 参考。

使用令牌计数使提示保持在模型的上下文窗口之内。

在发送请求之前检查令牌计数,以保持在您的使用层级范围内。

通过缓存提示前缀,降低重复提示的成本和延迟。

Compatibility

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

Was this page helpful?