Claude Token Counting API: Estimate Costs Before You Send
October 30, 2026
The count_tokens endpoint returns a precise input token count before any inference occurs — no output tokens billed, no model call made. Use it for cost estimation, context-window validation, and prompt caching eligibility checks.
The count_tokens endpoint returns an input_tokens count before your request reaches the model — no output tokens consumed, no billing charge. Pass the same messages, system, and tools arrays you plan to send; Claude counts exactly what it would see. Use it for cost estimation, context-window validation, and caching eligibility checks.
This is an independent guide to the Claude API for CCA-F exam preparation. Plinth Prep is not affiliated with, endorsed by, or sponsored by Anthropic.
What does the count_tokens endpoint return?
The endpoint — POST /v1/messages/count_tokens — returns a single field: input_tokens. That integer is the exact number of tokens Claude would process if you sent the same payload to POST /v1/messages. No inference happens, no output tokens are generated, and the call itself carries no billing charge.
When you include cache_control breakpoints in the request, the response also provides a breakdown — per Anthropic's published documentation — across cache_creation_input_tokens and cache_read_input_tokens. This lets you see, before committing to a full inference call, how many tokens would be written to a new cache entry versus served from an existing one.
How do you call count_tokens — request structure and required fields?
The required fields mirror messages.create: model and messages. Pass the exact arrays you plan to use for inference. The Python SDK exposes client.messages.count_tokens(); TypeScript uses client.messages.countTokens().
import anthropic
client = anthropic.Anthropic()
count = client.messages.count_tokens(
model="claude-opus-4-8",
system="You are a financial analyst.",
messages=[
{
"role": "user",
"content": "Summarize the Q3 earnings report.\n\n" + report_text
}
],
)
print(count.input_tokens) # e.g. 14200
The TypeScript equivalent:
const count = await client.messages.countTokens({
model: "claude-opus-4-8",
system: "You are a financial analyst.",
messages: [
{ role: "user", content: `Summarize the Q3 earnings report.\n\n${reportText}` }
],
});
console.log(count.input_tokens);
Pass system and tools whenever your actual request will include them. Omitting them from the count call produces an undercount — those fields add real tokens.
Does count_tokens account for tools, system prompts, and images?
Yes. The endpoint counts everything Claude would process in a real request:
- System prompt: Pass via the
systemparameter, formatted exactly as you would for inference. - Tool definitions: Include your
toolsarray. Tool schemas — including thename,description, andinput_schema— add tokens just as they do in a messages request. - Images: Base64 and URL image blocks are counted at the token cost Claude would charge. Image token counts vary by model and resolution, per Anthropic's published documentation.
- Full message history: The entire
messagesarray, including any existing assistant turns from a multi-turn conversation.
One implementation note: in some SDKs the tools parameter in MessageCountTokensParams uses a slightly different union type than in MessageCreateParams. TypeScript and C# developers may encounter a compile-time distinction when passing strongly-typed tool objects; the underlying wire format is identical.
When should you use count_tokens instead of estimating manually?
Claude does not use OpenAI's tiktoken tokenizer. Applying tiktoken — or any character-based approximation — to Claude inputs typically undercounts by 15–20% on English text and by significantly more on code or non-English content. At scale, that margin compounds: a batch estimated at 80,000 tokens per request may actually bill at 95,000.
Reach for count_tokens before sending when any of these apply:
- You are approaching a context-window limit. Per published materials, Opus 4.8, Opus 4.7, Opus 4.6, and Sonnet 4.6 each offer a 1M-token context window; Haiku 4.5 offers 200K. A pre-flight count lets you trim or split a request before the API rejects it, saving the latency of a failed call.
- You are configuring prompt caching. Anthropic's documentation specifies model-dependent minimum cacheable prefix sizes. For Opus 4.8, Opus 4.7, Opus 4.6, and Haiku 4.5, that minimum is 4,096 tokens; for Sonnet 4.6 it is 2,048 tokens. If your system prompt falls below the threshold, no cache entry is written — counting first verifies eligibility without spending a cache-write charge.
- You need a cost estimate before executing a run. Multiply
input_tokensby the per-token input rate for your model. Per published pricing, Claude Opus 4.8 is $5.00 per million input tokens, Sonnet 4.6 is $3.00, and Haiku 4.5 is $1.00. Verify current rates at Anthropic's official pricing page, as pricing can change.
How does token counting interact with prompt caching?
You can include cache_control breakpoints in a count_tokens request exactly as you would in a messages request. Per Anthropic's published token counting documentation, the response will include not only input_tokens but also cache_creation_input_tokens and cache_read_input_tokens.
This enables two pre-flight checks before spending any inference budget:
- Caching eligibility. If
cache_creation_input_tokensreturns zero despite acache_controlmarker, your prefix is below the model's minimum cacheable threshold. You can extend the prompt, switch to a model with a lower minimum, or remove the marker. - Cache hit prediction. If
cache_read_input_tokensshows a non-zero count, an existing cache entry covers that prefix. On the actual inference call, those tokens will be billed at roughly 0.1× the normal input rate.
The render order for caching is tools → system → messages. A cache_control marker on the last system block caches all tool definitions and system tokens before it. Volatile content — the per-user query, dynamic timestamps — must appear after the last breakpoint, or it will invalidate the cached prefix on every request. Running count_tokens with your cache markers before the first live request confirms that placement is working as intended.
What does the CCA-F exam test about token counting and cost management?
The Claude Certified Architect — Foundations exam covers cost management and resource optimization as part of its published domain areas, per Anthropic's certification materials. Domain names, weights, passing thresholds, and scoring methodology can change between exam versions or cohorts; always verify current exam details at Anthropic's official certification pages.
Based on available public materials, exam-relevant concepts in this area include:
- Understanding that
count_tokensconsumes no output tokens and carries no inference charge - Knowing that token counts are model-specific — the same payload produces different counts on different models, so the
modelparameter must match the intended inference model - Recognizing why OpenAI's tiktoken tokenizer produces incorrect results for Claude inputs
- Describing the minimum cacheable prefix constraint and how
count_tokenscan verify eligibility before committing to a cache-write charge - Applying the pre-flight pattern: count → validate context fit → estimate cost → send
Exam scenarios may present a developer who needs to decide whether a request fits within a context window, whether prompt caching will activate, or how to estimate the cost of a batch run — all situations where count_tokens is the correct tool to reach for first.
Reading about the count_tokens endpoint builds conceptual understanding, but the CCA-F tests whether you can apply that understanding under exam conditions. Plinth Prep is an independent study resource — not affiliated with Anthropic — with practice questions covering cost management, prompt caching design, and Claude API mechanics. Visit plinthprep.com to work through exam-aligned scenarios and confirm you have genuinely internalized these patterns, not just read about them.
Frequently asked questions
- What does the Claude count_tokens endpoint return?
- The count_tokens endpoint returns a single input_tokens integer — the exact number of tokens Claude would process for the given payload. No output tokens are generated and no inference billing occurs. When cache_control markers are included, the response also provides cache_creation_input_tokens and cache_read_input_tokens fields, per Anthropic's published documentation.
- Does count_tokens account for tools, system prompts, and images in Claude?
- Yes. The count_tokens endpoint counts all inputs Claude would process: the system prompt, tool definitions in the tools array, image blocks, and the full messages history. Pass the exact same arrays you plan to use for inference — tool schemas and image content add tokens to the count just as they do in a real messages request.
- Why is tiktoken inaccurate for counting Claude API tokens?
- Claude does not use OpenAI's tiktoken tokenizer. Applying tiktoken to Claude inputs typically undercounts by 15 to 20 percent on English text and by significantly more on code or non-English content. The count_tokens endpoint uses Claude's actual tokenizer and returns a model-specific count matched to the model you pass.
- What is the minimum token size for Claude prompt caching to activate?
- The minimum cacheable prefix is model-specific, per Anthropic's published materials. For Claude Opus 4.8, Opus 4.7, Opus 4.6, and Haiku 4.5, the minimum is 4,096 tokens. For Sonnet 4.6, Haiku 3.5, and Haiku 3, it is 2,048 tokens. Prefixes below the threshold are silently not cached even when cache_control is set.
- When should you call count_tokens before sending a Claude API request?
- Call count_tokens before a request when you need to verify the input fits within the context window, produce a precise cost estimate at a known token rate, or confirm a prompt-cached prefix exceeds the model's minimum cacheable threshold. The call itself is free and consumes no output tokens.