Token Counting / Count Tokens
Estimate the number of input tokens in a request before making an actual model call — useful for cost estimation or making context truncation decisions upfront. No charges, no fallback triggered, no quota consumed.
When to Use
- Confirm you haven't exceeded the context window before constructing a long prompt
- Decide how many chunks to include in a RAG pipeline
- Display an estimated cost to end users
- Run batch budget calculations in CI pipelines or scripts
Usage (Anthropic Messages)
Only the Anthropic Messages protocol has a native count_tokens endpoint. (For equivalent Turing paths under other protocols, see the "Other Protocols" section below.)
from anthropic import Anthropic
client = Anthropic(
base_url="https://live-turing.cn.llm.tcljd.com/api/v1",
auth_token="your-api-key",
)
result = client.messages.count_tokens(
model="turing/claude-sonnet-5",
messages=[{"role": "user", "content": "Estimate the number of input tokens in this request"}],
)
print(result.input_tokens) # -> integer
curl $TURING_BASE_URL/messages/count_tokens \
-H "Authorization: Bearer $TURING_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "turing/claude-sonnet-5",
"messages": [{"role": "user", "content": "Estimate the number of input tokens in this request"}]
}'
Complete request / response schema: /api/count-message-tokens
Supported Fields
Largely the same as a standard /messages request, but excludes generation parameters such as max_tokens and temperature:
| Field | Purpose |
|---|---|
model | Tokenizer to use for the specified model |
messages | Conversation history |
system | System prompt |
tools | Tool definitions (counted toward tokens) |
tool_choice | Tool selection strategy |
thinking | Token estimate when reasoning is enabled |
cache_control | Top-level cache markers (affects the count) |
Estimation for Other Protocols
The OpenAI Chat Completions / Responses protocol does not have a corresponding count_tokens endpoint. Common approaches:
- Local tokenizer (recommended): Use the
tiktokenpackage to tokenize locally for OpenAI-family modelsimport tiktokenenc = tiktoken.encoding_for_model("gpt-4")print(len(enc.encode("Text to estimate"))) - Send a request with
max_tokens=1and readusage.prompt_tokensfrom the response (incurs a small charge)
Notes
- Token counts are estimates: the exact count for image / audio / video inputs may differ slightly from actual inference
- When
cache_controlis used,input_tokensreturns the total count assuming the expected cache hit (still the sum of non-cached + cache read + cache write tokens) - Estimates do not count against quota or budget
See also
/api/count-message-tokens— Full schema + Try-It- Messages API — Correspondence between
count_tokensinput and generation request structure - Prompt Caching — Token counting semantics when caching is used
- Billing & Usage — Mapping between Anthropic
input_tokensand platform billing