Claude Platform Docs
  • 消息
  • 托管智能体
  • 管理

Search...
⌘K
第一步
Claude 简介快速入门
使用 Claude 构建
功能概览使用 Messages API停止原因与回退拒绝与回退回退额度
模型能力
扩展思考自适应思考努力程度任务预算(测试版)快速模式(研究预览)结构化输出引用流式传输消息批量处理搜索结果流式传输拒绝多语言支持嵌入
工具
概览工具使用的工作原理教程:构建使用工具的智能体定义工具处理工具调用并行工具使用工具运行器(SDK)严格工具使用工具使用与提示缓存服务器工具故障排除网页搜索工具网页抓取工具代码执行工具顾问工具记忆工具Bash 工具计算机使用工具文本编辑器工具
工具基础设施
工具参考管理工具上下文工具组合工具搜索编程式工具调用细粒度工具流式传输
上下文管理
上下文窗口压缩上下文编辑提示缓存对话中系统消息构建编排模式缓存诊断(测试版)令牌计数
处理文件
Files APIPDF 支持图像与视觉
技能
概览快速入门最佳实践企业技能API 中的技能
MCP
远程 MCP 服务器MCP 连接器
云平台上的 Claude
Amazon BedrockAmazon Bedrock(旧版)AWS 上的 Claude PlatformMicrosoft FoundryVertex AI

Log in
令牌计数
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Claude Platform Docs

Solutions

  • AI agents
  • Code modernization
  • Coding
  • Customer support
  • Education
  • Financial services
  • Government
  • Life sciences

Partners

  • Claude on AWS
  • Claude on Google Cloud

Learn

  • Blog
  • Courses
  • Use cases
  • Connectors
  • Customer stories
  • Engineering at Anthropic
  • Events
  • Powered by Claude
  • Service partners
  • Startups program

Company

  • Anthropic
  • Careers
  • Economic Futures
  • Research
  • News
  • Responsible Scaling Policy
  • Security and compliance
  • Transparency

Learn

  • Blog
  • Courses
  • Use cases
  • Connectors
  • Customer stories
  • Engineering at Anthropic
  • Events
  • Powered by Claude
  • Service partners
  • Startups program

Help and security

  • Availability
  • Status
  • Support
  • Discord

Terms and policies

  • Privacy policy
  • Responsible disclosure policy
  • Terms of service: Commercial
  • Terms of service: Consumer
  • Usage policy
消息/上下文管理

令牌计数

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

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

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

此功能符合零数据保留(ZDR)的条件。当您的组织签订了 ZDR 协议时,通过此功能发送的数据在 API 响应返回后不会被存储。


如何统计消息令牌

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



令牌计数应被视为估算值。在某些情况下,创建消息时实际使用的输入令牌数量可能会有少量差异。

令牌计数可能包含 Anthropic 为系统优化而自动添加的令牌。系统添加的令牌不会向您计费。计费仅反映您的内容。

支持的模型

所有活跃模型均支持令牌计数。

统计基本消息中的令牌

client = anthropic.Anthropic()

response = client.messages.count_tokens(
    model="claude-opus-4-8",
    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-4-8",
    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 httpx

image_url = "https://upload.wikimedia.org/wikipedia/commons/a/a7/Camponotus_flavomarginatus_ant.jpg"
image_media_type = "image/jpeg"
image_data = base64.standard_b64encode(httpx.get(image_url).content).decode("utf-8")

client = anthropic.Anthropic()

response = client.messages.count_tokens(
    model="claude-opus-4-8",
    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": 1551 }

统计包含扩展思考的消息中的令牌



有关更多详细信息,请参阅扩展思考下如何计算上下文窗口

  • 先前助手轮次中的思考块会被忽略,不会计入您的输入令牌
  • 当前助手轮次的思考会计入您的输入令牌
client = anthropic.Anthropic()

response = client.messages.count_tokens(
    model="claude-sonnet-4-6",
    thinking={"type": "enabled", "budget_tokens": 16000},
    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 的消息中的令牌



令牌计数支持 PDF,其限制与 Messages API 相同。

import base64
import anthropic

client = anthropic.Anthropic()

with open("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-4-8",
    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 5 和 Claude Mythos 5 上的令牌计数

Claude Fable 5 和 Claude Mythos 5 使用随 Claude Opus 4.7 引入的分词器,对于相同的文本,该分词器生成的令牌数量比 Claude Opus 4.7 之前的模型多约 30%。令牌计数端点会根据您传入的 model 所对应的分词器返回计数,因此要衡量您的工作负载的差异,请对同一请求进行两次计数:一次使用您当前的模型,一次使用 model: "claude-fable-5"(或 "claude-mythos-5"),然后比较两个 input_tokens 值。



**计费与迁移:**Claude Fable 5 和 Claude Mythos 5 上的使用量和计费反映的是此分词器的计数。如果您从 Claude Opus 4.7 之前的模型迁移,相同的内容会消耗约 30% 更多的令牌。在将工作负载迁移到 Claude Fable 5 和 Claude Mythos 5 时,请勿重复使用在 Claude Opus 4.7 之前的模型上测得的令牌计数来估算成本或上下文窗口的适配情况。请使用 model: "claude-fable-5"(或 "claude-mythos-5")对您的提示进行计数。


定价和速率限制

令牌计数免费使用,但会根据您的使用层级受到每分钟请求数的速率限制。如果您需要更高的限制,请通过 Claude Console 联系销售团队。

使用层级每分钟请求数(RPM)
1100
22,000
34,000
48,000


令牌计数和消息创建具有各自独立的速率限制。使用其中一个不会占用另一个的限额。


常见问题


后续步骤


统计消息令牌

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

上下文窗口

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

速率限制

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

提示缓存

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

Was this page helpful?

  • 如何统计消息令牌
  • 支持的模型
  • 统计基本消息中的令牌
  • 统计包含工具的消息中的令牌
  • 统计包含图像的消息中的令牌
  • 统计包含扩展思考的消息中的令牌
  • 统计包含 PDF 的消息中的令牌
  • Claude Fable 5 和 Claude Mythos 5 上的令牌计数
  • 定价和速率限制
  • 常见问题
  • 后续步骤