Count message tokens
Endpoint
POST
/v1/messages/count_tokensCompatible with the Anthropic count_tokens API. The request body matches Create a message without max_tokens; it only counts, generates no reply, and produces no output tokens.
Request
Same headers as Create a message: x-api-key (or Authorization: Bearer), anthropic-version: 2023-06-01, and content-type: application/json.
{
"model": "claude-sonnet-5",
"messages": [
{"role": "user", "content": "Introduce yourself in one sentence"}
]
}
Parameters
| Field | Type | Required | Notes |
|---|---|---|---|
model |
string | Yes | Claude model ID |
messages |
array | Yes | The messages to count, in the same format as Create a message |
system |
string or array | No | System prompt, included in the count |
Response
{"input_tokens": 16}
| Field | Notes |
|---|---|
input_tokens |
Tokens these messages occupy as input |
Examples
curl https://api.moyiapi.com/v1/messages/count_tokens \
-H "x-api-key: sk-moyiapi-xxxxxx" \
-H "anthropic-version: 2023-06-01" \
-H "content-type: application/json" \
-d '{
"model": "claude-sonnet-5",
"messages": [{"role": "user", "content": "Introduce yourself in one sentence"}]
}'
Errors
| HTTP status | error.type |
When it happens |
|---|---|---|
| 401 | missing_auth_credential / invalid_api_key / invalid_bearer_token |
Authentication failed; see Authentication |