Tokens and Tokenization
Independent educational resource, not an official Anthropic course. Facts about the API, prices and limits were checked against Anthropic's documentation on 15 November 2026 and the code was run against a local mock of the API, not the live service. Check the linked official pages before relying on a number, and test with your own key.
Tokens are the unit of everything in the Claude API: what you send, what comes back, what you pay, what fits in the context window and how fast you can go. Developers who treat "words" and "tokens" as the same thing get wrong cost estimates and surprising errors. This lesson explains what a token is, what counts as one, how to measure them, and why the numbers change from model to model.
Learning objectives
- Explain what a token is and why it is not a word.
- List everything in a request that consumes tokens.
- Count tokens with the API instead of guessing.
- Understand why the same text can produce different counts on different models.
- Use a rough estimate responsibly for planning.
Prerequisites
What a token is
A language model does not read letters or words directly. Text is first split into pieces called tokens by a component called a tokenizer, and the model reads and writes those pieces. A token can be a whole common word, part of a longer word, a single character, punctuation, or a run of spaces. The model's reply is also produced token by token.
Anthropic's documentation gives two useful conversions for the current tokenizer: 1 million tokens is roughly 555,000 words, or about 2.5 million Unicode characters. For models released before Claude Opus 4.7, 1 million tokens fit about 750,000 words. Treat these as averages: the true ratio depends on the text.
What consumes tokens
| In the request | In the response |
| The system prompt | The visible answer |
Every message in messages, including earlier turns you resend | Thinking tokens (they are part of max_tokens and are billed as output) |
| Tool definitions and tool results | Tool-call requests the model writes |
| Images and PDF pages | |
Anthropic's token-counting examples show how different inputs weigh: a one-line message with a one-line system prompt came to 14 input tokens; a request with one small tool definition came to 403; a request with an example image came to 1,028. These are examples from the documentation, not rules: your numbers depend on your content.
Why the same text counts differently
- Different content. Plain English, source code, JSON, tables and non-English scripts split differently. Measure your own content instead of assuming it behaves like English prose.
- Different tokenizer. Claude Opus 4.7 and later models use a newer tokenizer. The documentation says the same input text produces approximately 30 percent more tokens than on earlier models, with the exact increase depending on the content. The Fable 5.x and Mythos 5.x models share that tokenizer.
The practical consequence is stated plainly in the docs: when you migrate models, recount your prompts against the model you plan to use, and do not reuse counts measured on an older one for cost or context-fit estimates.
Step by step: count tokens with the API
The token counting endpoint takes the same inputs as a normal request and returns input_tokens. It is free to use, has its own rate limits, and returns an estimate: the real count can differ slightly, and Anthropic says you are not billed for tokens it adds for system optimisation. This script measures four kinds of text and prints a rough estimate next to the real count so you can see how far off a guess can be:
import anthropic
client = anthropic.Anthropic()
MODEL = "claude-sonnet-5-5"
SAMPLES = {
"plain English": "Please send me the invoice for last month's hosting plan.",
"Laravel code": "Route::get('/users/{user}', [UserController::class, 'show'])->middleware('auth');",
"JSON": '{"id": 42, "email": "sam@example.com", "roles": ["admin", "editor"], "active": true}',
"Urdu": "براہ کرم پچھلے مہینے کے ہوسٹنگ پلان کا انوائس بھیج دیں۔",
}
def count(text: str) -> int:
"""Ask the API how many input tokens this text would use. The call is free but rate limited."""
result = client.messages.count_tokens(
model=MODEL,
messages=[{"role": "user", "content": text}],
)
return result.input_tokens
def rough_estimate(text: str) -> int:
"""A planning guess only. Anthropic says 1M tokens is about 2.5M Unicode characters on the current
tokenizer, so roughly 2.5 characters per token. Real counts vary with the content, so measure."""
return round(len(text) / 2.5)
for name, text in SAMPLES.items():
tokens = count(text)
print(f"{name:14} chars={len(text):3} counted={tokens:3} rough={rough_estimate(text):3}")
Run it with your key and read the "counted" column. (When this script was tested against a local mock of the API, which returns a fixed number, only the structure was verified; the real counts come from the live service.) The rough_estimate function applies the documented ratio of about 2.5 characters per token. Use it for back-of-the-envelope planning only; anything that affects money or a hard limit should use the counted value.
The same call in PHP, using the official SDK:
$count = $client->messages->countTokens(
messages: [['role' => 'user', 'content' => $text]],
model: 'claude-sonnet-5-5',
);
echo $count->inputTokens;
The endpoint does not accept server tools or the MCP connector, and images or documents given by URL or file ID must be sent as base64 to be counted. It does not use prompt caching, so a count ignores any cache savings.
Where token counts matter
- Cost. You are billed per million input and output tokens (lesson 1.2).
- Limits. Your rate limits are measured in requests, input tokens and output tokens per minute, and the context window is a token limit (lessons 1.5 and 2.1).
- Latency. More tokens in and out generally means a slower response.
max_tokens. It caps the tokens generated, including thinking, not the words. A cap of 100 tokens produces fewer than 100 words.
Real-world use case (illustrative scenario)
This scenario is an invented example to show how the ideas fit together. It is not a case study and its details are not measured results.
Imagine a team planning a feature that summarises customer emails, each about 1,200 words. A word-based guess says "about 1,200 tokens". Counting real emails with the API would show a different figure, and after moving to a newer model the counts would rise again because of the tokenizer change. The sensible fix is to put the counting call into a nightly test with sample emails, so a model change shows up as a cost-forecast change before launch instead of on an invoice.
Common errors and solutions
| Mistake | Consequence | Fix |
| Using words as tokens | Budgets and limits wrong by a large factor. | Count with the API; use the documented ratios only for planning. |
| Reusing old counts after a model change | About 30% under-estimate on Opus 4.7-and-later tokenizers. | Recount per model. |
| Counting with URL-sourced images | invalid_request_error from the counting endpoint. | Send base64 for counting. |
| Forgetting thinking tokens | Output costs and limits higher than the visible text suggests. | Read usage.output_tokens; it includes them. |
| Treating the count as exact | Hard limits overshot by a few tokens. | Leave a safety margin (lesson 1.5). |
Security considerations
Token counts are cheap to compute, so use them as a guard: reject or truncate oversized user input before it reaches the model, and cap per-user usage. Sending a user's multi-megabyte paste straight through is both a cost risk and an easy way to exhaust your rate limits. Do not log the text you count if it contains personal data; log the counts.
Performance and cost considerations
- The counting endpoint has its own request-per-minute limits, separate from message creation, so counting does not eat into your generation capacity.
- Shorter prompts, shorter outputs and trimmed history all reduce tokens; lesson 2.9 covers cost tracking in code.
- Cached input still counts toward the context window; caching changes the price, not the size (lesson 1.5).
Key takeaways
- A token is a piece of text, not a word; current rule of thumb is about 2.5 characters or 0.55 words per token.
- Everything you send and everything the model generates, including thinking, consumes tokens.
- Newer tokenizers produce about 30% more tokens for the same text; recount when you change models.
- Use the free token counting endpoint for real numbers, and treat it as an estimate.
Lesson recap: everything sent and generated consumes tokens, so estimate roughly and measure with the counting endpoint.
Knowledge check
- Is a token the same as a word?
- Name four things in a request that consume tokens.
- Why recount a prompt after moving from an older model to Claude Opus 4.7 or later?
- Does the token counting endpoint cost money?
- Does
max_tokens include thinking tokens?
Answers and explanations
- No. A token can be a word, part of a word, a character or punctuation. The ratio varies with the text.
- The system prompt, messages (including resent history), tool definitions and results, and images or PDF pages.
- Those models use a newer tokenizer that yields about 30% more tokens for the same text, so old counts underestimate cost and context use.
- No. It is free, but subject to its own rate limits.
- Yes. Thinking tokens are a subset of
max_tokens and are billed as output.
Official references and further reading
Related tutorials