TokenLab

Text

Count Message Tokens

Counts the input tokens of a Messages request without creating a response.

POST
/v1/messages/count_tokens

Overview

Send the same model, messages, system, tools, and thinking fields as Create Message, without max_tokens, to count the input tokens before you send the request. The model must list anthropic_messages in accepted_request_formats.

Notes

  • Token counting needs an API key and is not billed.
  • The count is for planning. The charge for the real request comes from the usage in its response.
  • TokenLab prefers a count from the model's own counter. When that counter is not available, TokenLab returns a local estimate and sets the response header X-TokenLab-Count-Tokens-Source: local_estimate.
  • Authentication, permission, and input errors still fail. A request that references a file_id needs the model's own counter and returns 503 when none is available. Send anthropic-beta: files-api-2025-04-14 with such a request.

Example

Request

cURL
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!"}
    ]
  }'

Response example

Response

200 OK
{
  "input_tokens": 12
}

Important fields

input_tokensinteger
Estimated number of input tokens in the request.

Authorization

BearerAuth
AuthorizationBearer <token>

API Key authentication. Create or manage API keys in Dashboard > API > API Keys.

In: header

Request Body

application/json

Response

application/json

application/json

application/json

application/json

application/json

application/json

application/json

application/json

application/json