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 step in this tutorial compares a message list to a limit. To do that, you first need a number for how big the list is.
Why counts matter
A model's context window is measured in tokens, not characters or words. A token is a chunk of text produced by the model's tokenizer, which is the component that splits text into pieces. A token can be a whole word, part of a word, or a single punctuation mark. The same text gives different counts under different tokenizers. A count made for one model family is therefore only an approximation for another.
If you undercount, the request can be rejected or the oldest content can be cut without your knowing. If you overcount by a lot, you throw away history you could have kept.
Exact counts
An exact count comes from the tokenizer the model actually uses. There are two common sources:
- A local tokenizer library published for the model family. It is fast and works offline, but it only matches the models it was built for.
- A token-counting endpoint offered by some providers. It matches the provider's own tokenizer, but it costs a network round trip for each call.
Exact counts have one more trap. Chat APIs add formatting tokens around each message, such as role markers and separators. Counting only the text of each message misses these. The size of this overhead depends on the model and the API.
Estimates
An estimate is cheap and needs no dependencies. For English prose, a common rule of thumb is about 4 characters per token. This code uses that rule, plus a small fixed cost per message for the formatting overhead:
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 + 4
messages = [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Summarize the plot of Hamlet in two sentences."},
]
total = sum(estimate_tokens(m) for m in messages)
print(total)The function returns the same value on every run for the same input, so it is easy to test. The // 4 uses integer division, so the result is always a whole number.
Where estimates go wrong
The 4-characters rule is tuned for English. It is less reliable in these cases:
- Source code, JSON, and logs, which contain many short symbols and often produce more tokens per character.
- Languages that do not use the Latin alphabet, where one character can take one or more tokens.
- Long numbers, URLs, and identifiers, which tokenizers often split into many small pieces.
For these inputs the estimate usually runs low, which is the dangerous direction. You can compensate in two ways. Leave a safety margin in your budget, which the next chapter covers. You can also compare the estimate with real counts on a sample of your own traffic and adjust the divisor.
Choosing between them
| Situation | Better choice |
|---|---|
| Quick prototype, English chat | Estimate |
| Deciding whether to compact on every turn | Estimate, with a safety margin |
| Content close to the limit | Exact count |
| Code, JSON, or non-English text | Exact count |
| Billing or usage reports | Exact count from the provider |
A practical pattern is to use the estimate for routine checks and an exact count only when the estimate comes near the limit. This keeps most turns fast and still protects the cases that matter.
Exercise
A chat contains a 2,000-character JSON log pasted by the user. Using the estimate_tokens function, what does it return for this message, and why might the true count be higher?
Show answer
It returns 2000 // 4 + 4 = 504 tokens. The true count is likely higher because JSON has many short symbols, quotes, and numbers that tokenizers split into more tokens per character than ordinary English prose.