端点:POST /v1/messages/count_tokens
与 Anthropic count_tokens API 兼容。请求体格式与 创建消息 相同,不需要 max_tokens;只计数,不生成回复,不产生输出 token。
请求
请求头与创建消息相同:x-api-key(或 Authorization: Bearer)、anthropic-version: 2023-06-01、content-type: application/json。
json
{
"model": "claude-sonnet-5",
"messages": [
{ "role": "user", "content": "用一句话介绍你自己" }
]
}参数
| 字段 | 类型 | 必填 | 说明 |
|---|---|---|---|
model | string | 是 | Claude 模型 ID |
messages | array | 是 | 要计数的对话消息,格式同创建消息 |
system | string 或数组 | 否 | 系统提示词,一并计入 |
响应
json
{ "input_tokens": 16 }| 字段 | 说明 |
|---|---|
input_tokens | 这些消息作为输入时占用的 token 数 |
示例
bash
curl https://caapi.top/v1/messages/count_tokens \
-H "x-api-key: sk-xxxxxx" \
-H "anthropic-version: 2023-06-01" \
-H "content-type: application/json" \
-d '{
"model": "claude-sonnet-5",
"messages": [{"role": "user", "content": "用一句话介绍你自己"}]
}'错误
| HTTP 状态 | error.type | 触发条件 |
|---|---|---|
| 401 | missing_auth_credential / invalid_api_key / invalid_bearer_token | 鉴权失败,详见 鉴权 |