Sub topic 3
Counting tokens: exact counts versus estimates
This chapter assumes you can write basic Python, know the system, user, and assistant message roles, and have a general idea of what a token is. Every later budgeting decision in this tutorial depends on a token count, so this chapter covers how to get one, how far to trust it, and how to build in a safety margin.
Why counts matter
A model's context window is measured in tokens, not characters or words. If you send more tokens than the window allows, the request fails or the oldest content is dropped, depending on the provider. The count also decides cost and latency.
To trim history to fit a limit, you need to know how many tokens each message uses. There are three ways to get that number:
- Ask the provider's counting endpoint or read the usage the API returns.
- Run the model's tokenizer locally.
- Estimate from the text length.
Each has a different price in accuracy, speed, and dependencies.
What a tokenizer does
A tokenizer splits text into pieces from a fixed vocabulary. A piece can be a whole common word, part of a rare word, a single punctuation mark, or a few bytes of an unusual character. The model sees the integer ID of each piece, and the token count is the number of pieces.
This has practical consequences:
- Common English prose averages roughly 4 characters per token, or about 0.75 words per token. This is a rule of thumb, not a guarantee.
- Code, JSON, URLs, and identifiers tend to use more tokens per character, because punctuation and unusual strings split into many small pieces.
- Languages such as Chinese, Japanese, Arabic, and Hindi often use many more tokens per character than English, and some tokenizers are far less efficient on them than others.
- Emoji and rare Unicode characters can cost several tokens each.
- Different models use different tokenizers. The same text can have different counts for different model families, and sometimes for different versions in one family.
The last point matters most. A count is only valid for the tokenizer that produced it.
Message overhead
Chat APIs do not feed the model just your text. The provider wraps each message in special tokens that mark the role and the message boundaries, and adds a few tokens that prime the model's reply. The exact format is provider-specific, and sometimes model-specific.
So the cost of a message list is not the sum of the tokenized content strings. It is roughly:
total = sum(content tokens) + per-message overhead × number of messages + reply primingOverhead is usually a handful of tokens per message. It looks small, but a conversation with 200 short messages can carry hundreds of tokens of overhead. Tool definitions, tool call arguments, and images are counted too, and they often cost far more than plain text.
Three ways to count
Exact: the provider's counter
Some providers offer an endpoint that takes the same payload you would send and returns the input token count without generating a reply. This is the most accurate option, because it uses the real tokenizer and the real message wrapping, including tools.
The costs are a network round trip for every count, possible rate limits, and a dependency on the provider being reachable. That makes it a poor fit for counting inside a loop over every message.
After a real request, the response normally includes a usage field with the actual input and output token counts. This is free and exact for the request you just made.
Exact: a local tokenizer
For some model families, the vendor or community publishes a tokenizer library you can run locally. It is fast and works offline. It gives exact content counts for that tokenizer, but you must still add the message overhead yourself, and you must pick the tokenizer that matches your model. Using the wrong one gives plausible but wrong numbers.
For example, with the tiktoken library for OpenAI-style models:
import tiktoken
def count_tokens(messages, encoding_name="cl100k_base"):
# Content counts are exact for this encoding. The overhead constants
# are approximations: check your model's documentation for the real ones.
encoding = tiktoken.get_encoding(encoding_name)
per_message_overhead = 4
reply_priming = 3
total = reply_priming
for message in messages:
total += per_message_overhead
total += len(encoding.encode(message["content"]))
return total
messages = [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "How many tokens is this conversation?"},
]
print(count_tokens(messages))Install the library first with pip install tiktoken. The encoding name must match your model. Even then, the overhead constants are only approximate for newer models.
Estimate: a character heuristic
When you have no tokenizer, or you need a count thousands of times per second, estimate from length. The simplest version divides the character count by about four:
def estimate_tokens(message):
# Rough heuristic: about 4 characters per token, plus a small per-message overhead.
# Replace with your model's real tokenizer when exact counts matter.
return len(message["content"]) // 4 + 4This is the estimator the later chapters reuse. It has no dependencies, runs in microseconds, and works for any provider. Its weakness is that it is only as good as the 4-characters-per-token assumption.
Comparing the options
| Method | Accuracy | Speed | Dependencies | Best used for |
|---|---|---|---|---|
| Provider counting endpoint | Exact, including tools | Slow (network call) | Network, credentials | Final check before a large or critical request |
| Usage field in the response | Exact, for the request just sent | Free | None | Calibration and logging |
| Local tokenizer | Exact for content, approximate overhead | Fast | Library matched to the model | Per-message counting in a trimming loop |
| Character heuristic | Rough, can be off by 20 percent or more | Fastest | None | Prototypes, pre-filters, unknown models |
How wrong can an estimate be?
The 4-characters-per-token rule errs in a predictable direction: it undercounts text that tokenizes badly. Consider these cases for a heuristic of len(text) // 4:
- Plain English prose: close to the real count, often within 10 percent.
- Source code and JSON: real counts are often higher than the estimate, because symbols and short identifiers each become their own token.
- Non-English text: the real count can be two to three times the estimate or more, depending on the language and tokenizer.
- Long runs of digits or random strings, such as hashes and base64: the real count can be well above the estimate.
An undercount is the dangerous direction. If you believe a request is 7,000 tokens and it is really 9,000, you can exceed a limit you thought you were safely under.
You can measure the error for your own traffic. Compare your estimate with the usage the API returns:
def estimate_error(estimated_tokens, actual_tokens):
# Positive means the estimate was too low (the unsafe direction).
return (actual_tokens - estimated_tokens) / actual_tokens
samples = [
("prose", 1000, 1080),
("json", 1000, 1450),
("japanese", 1000, 2300),
]
for label, estimated, actual in samples:
print(f"{label}: {estimate_error(estimated, actual):.0%}")The sample numbers here are illustrative. Collect real pairs from your logs, group them by content type, and use the worst group to decide your safety margin.
Choosing a strategy
A practical approach combines the methods instead of picking one:
- Use the cheap estimate or local tokenizer for the many small decisions, such as deciding which messages to keep in a trimming loop.
- Apply a safety margin to the budget, so estimation error does not push you over the limit.
- Read the usage field after each response and log the estimated and actual counts side by side.
- Use the logged ratio to adjust the margin, or to switch to a real tokenizer if the error is too large.
- Reserve the provider's counting endpoint for cases where an overflow is costly, such as long-running agents with large tool outputs.
Chapter 4 turns the safety margin into an explicit input budget. For now, the rule is simple: the less exact your count, the more room you leave unused.
Common mistakes
- Counting words instead of tokens. Word counts can be off by a third for English and much more for code or other languages.
- Using one model's tokenizer to count for another model. The result looks reasonable and is silently wrong.
- Forgetting overhead, tool definitions, and system messages. These are part of the input and count against the limit.
- Counting only the new message instead of the whole list. The API is stateless, so the whole list is the input every time.
- Ignoring output tokens. The reply also needs space, which the next chapter covers.
- Calibrating on prose and deploying on code or non-English text.
Summary
Tokens are the unit that limits your input, and the count depends on the tokenizer, the content type, and the message wrapping. Exact counts come from the provider or a matching local tokenizer. Heuristics are fast and portable, but they undercount code and non-English text. Use whichever method fits the cost of being wrong, measure the error against real usage, and keep a margin.
Exercise
Your application estimates tokens as len(content) // 4 + 4. It works well in testing with English chat, but in production some requests with pasted JSON logs fail with a context length error. Give two reasons the estimate may be too low for those requests, and name two changes that would fix the problem.
Show answer
Reasons: (1) JSON and logs contain many symbols, short keys, and numbers, which tokenize into more pieces than the 4-characters-per-token rule assumes, so the real count is higher than the estimate. (2) The estimate ignores things the provider counts, such as tool definitions and the real per-message wrapping, so the total is understated further. Fixes: switch to a local tokenizer that matches the model (or the provider's counting endpoint) for these requests, and increase the safety margin in the budget, calibrating it by comparing estimates with the usage field from real responses grouped by content type.
Exercise
A teammate counts tokens for a conversation by running the tokenizer on each message's content and adding up the results. The sum is 1,200, but the API reports 1,310 input tokens. What accounts for the gap, and which value should the budget use?
Show answer
The gap comes from tokens the provider adds that are not in the content strings: the role and boundary markers around each message, the tokens that prime the reply, and any tool definitions in the request. The budget should use the larger, real figure, or the local count plus a per-message overhead and margin that you calibrated against the API's reported usage.