Skip to main content

POST /v1/messages/count_tokens

Count the number of tokens that would be used by a messages request. This is useful for estimating costs and ensuring you stay within model token limits.
This endpoint is specific to Anthropic’s API format. For OpenAI-format requests, token counting is typically done client-side or through the provider’s tokenizer.

Authentication

Requires provider authentication headers:

Request

Headers

string
required
Must be set to anthropic
string
required
Bearer token for Anthropic API
string
API version (e.g., 2023-06-01)

Body Parameters

string
required
The model to count tokens for (e.g., claude-3-5-sonnet-20241022)
array
required
Array of message objects in Anthropic format
string
System prompt (optional)
array
Array of tool definitions (if using tool calling)

Response

integer
Number of tokens in the input (messages + system prompt + tools)

Example

Response Example

Use Cases

Calculate the cost of a request before sending it by counting tokens and multiplying by the model’s per-token price.
Ensure your messages fit within the model’s context window (e.g., 200K tokens for Claude 3.5 Sonnet).
Compare token counts across different prompt formulations to optimize for cost and efficiency.
Determine which messages to keep or remove when approaching token limits in multi-turn conversations.

Token Counting with Tools

When using tool calling, tools are included in the token count:

Pricing

Token counting requests do not consume any tokens or incur costs. Use this endpoint freely to estimate costs before making actual API calls.

Create Message

Send a messages request to Claude

Anthropic Provider

Anthropic integration guide