文本
统计消息 token
统计 Messages 请求的输入 token 数,不生成响应。
概述
发送与创建消息相同的 model、messages、system、tools 和 thinking 字段(不需要 max_tokens),即可在发送请求前统计输入 token 数。模型的 accepted_request_formats 必须包含 anthropic_messages。
说明
- Token 统计需要 API 密钥,不收费。
- 统计结果用于请求规划。真实请求的费用以其响应中的
usage为准。 - TokenLab 优先使用模型自带计数器的结果。该计数器不可用时,TokenLab 返回本地估算值,并设置响应头
X-TokenLab-Count-Tokens-Source: local_estimate。 - 鉴权、权限和输入错误仍然会失败。引用
file_id的请求必须使用模型自带计数器,没有可用计数器时返回503。这类请求需要同时发送anthropic-beta: files-api-2025-04-14。
请求
curl -X POST "https://api.tokenlab.sh/v1/messages/count_tokens" \
-H "x-api-key: sk-your-api-key" \
-H "anthropic-version: 2023-06-01" \
-H "Content-Type: application/json" \
-d '{
"model": "claude-sonnet-5",
"messages": [
{"role": "user", "content": "Hello, Claude!"}
]
}'响应
{
"input_tokens": 12
}重要字段
input_tokensinteger
请求输入 token 的估算数量。
授权
BearerAuth AuthorizationBearer <token>
API Key 身份验证。在 Dashboard > API > API Keys 中创建或管理 API Key。
位置: header
请求体
application/json
响应
application/json
application/json
application/json
application/json
application/json
application/json
application/json
application/json
application/json