Sub topic 3
Counting tokens
This chapter assumes you can read basic Python, have called an LLM through a chat or completion API, and know what a token is (a chunk of text the model reads as one unit). You also need to be comfortable with simple arithmetic. By the end you will be able to count tokens locally with a tokenizer library, read the count the API reports, and explain why the two numbers can differ.
Why count tokens at all
Every limit and every price in an LLM call is expressed in tokens, not words or characters. You need a token count to answer three practical questions:
- Will this prompt, plus the output I allow, fit in the context window?
- Roughly what will this call cost?
- Which part of my prompt is using the most space?
There are two ways to get a count. You can count before the call by running a tokenizer yourself. Or you can read the count after the call from the usage data the API returns. They serve different purposes, and the rest of this chapter covers both.
Counting locally with a tokenizer
A tokenizer is the program that splits text into tokens and maps each token to an integer ID. Because each model family has its own tokenizer, a local count is exact only when you use the tokenizer that matches the model. tiktoken is an open-source library that implements the tokenizers used by OpenAI models. Install it with pip install tiktoken. It downloads the vocabulary file the first time you load an encoding, so that first run needs network access.
import tiktoken
enc = tiktoken.get_encoding("cl100k_base")
text = "Tokens are not the same as words."
token_ids = enc.encode(text)
print(len(text.split()), "words")
print(len(token_ids), "tokens")
print([enc.decode([t]) for t in token_ids])The script prints the number of words (split on whitespace), the number of tokens, and the text of each token. The two counts differ. Punctuation usually becomes its own token, and a space is usually attached to the start of the word that follows it. The last line of output shows this, with entries like " not" rather than "not".
encode returns a list of integers, so len(token_ids) is the token count. Decoding each ID separately, as the last line does, is useful for inspection. It can show odd results for characters that span several tokens, because a single token may hold only part of a character's bytes.
What changes the count
The same meaning can cost very different numbers of tokens. These factors matter most in practice:
| Factor | Effect on token count |
|---|---|
| Common English words | Often one token per word, with the leading space included |
| Rare words, names, and typos | Split into several subword pieces |
| Source code and JSON | More tokens per character than prose, because of symbols, indentation, and identifiers |
| Numbers | Often split into short digit groups |
| Non-English text | Often more tokens for the same meaning, especially for languages the vocabulary covers less well |
| Whitespace and formatting | Runs of spaces, newlines, and Markdown symbols all add tokens |
A rule of thumb for English prose is about four characters per token, or roughly three quarters of a word. This is useful for a back-of-the-envelope check. It is a poor guide for code, tables, or text in other languages, where it can be off by a large margin. Use it to sanity-check a number, not to enforce a limit.
import math
import tiktoken
enc = tiktoken.get_encoding("cl100k_base")
def rough_estimate(text):
return math.ceil(len(text) / 4)
samples = {
"prose": "The quick brown fox jumps over the lazy dog near the river bank.",
"code": "def f(x):\n return {'a': [x, x * 2], 'b': None}\n",
"numbers": "3.14159265358979323846 2718281828459045",
}
for name, text in samples.items():
exact = len(enc.encode(text))
print(f"{name:8} chars/4 = {rough_estimate(text):3} tokenizer = {exact:3}")Run it and compare the two columns for each sample. The gap is usually small for prose and larger for code and digits.
Counting a chat, not just a string
A chat request is a list of messages, not one string. The provider wraps each message in special tokens that mark the role (system, user, assistant) and the message boundaries. Those wrapper tokens count toward your input. The exact overhead depends on the model and the provider, and it can change between model versions.
The function below counts the content of each message and adds a configurable per-message overhead. The defaults (4 per message and 3 to prime the reply) are approximations taken from OpenAI's published guidance for older chat models. Treat them as placeholders, and replace them with values for your own model.
import tiktoken
def count_chat_tokens(messages, enc, per_message=4, reply_priming=3):
total = reply_priming
for message in messages:
total += per_message
total += len(enc.encode(message["content"]))
total += len(enc.encode(message["role"]))
return total
enc = tiktoken.get_encoding("cl100k_base")
messages = [
{"role": "system", "content": "You are a concise assistant."},
{"role": "user", "content": "Explain what a token is in one sentence."},
]
print(count_chat_tokens(messages, enc))The result is an estimate of the input tokens for these two messages. It leaves out anything else the provider adds to your request, so the billed number can be higher.
Hidden input you also pay for
Several things add input tokens that you may not see in your message text:
- System prompts. These are sent on every call and count every time.
- Tool and function definitions. The JSON schemas you pass for tool calling are converted to text for the model and counted as input. A large set of tools can add thousands of tokens.
- Structured-output schemas. A response format schema is also part of the prompt.
- Images, audio, and documents. These are converted to tokens by provider-specific rules. A local text tokenizer cannot count them at all.
- Retrieved context. Passages you paste in from a search step count like any other text.
If you count only the user's latest message, you will underestimate. Count everything you send, in the form you send it.
Counting with the provider's own tools
Some providers offer a token-counting endpoint or a client-library helper that runs the provider's real tokenizer on your full request, including messages, tools, and images. Where one exists, it is the most accurate way to count before a call, because it uses the exact tokenizer and template. It may add a network round trip, and it may have its own rate limits. Check your provider's documentation for the current name and behavior of this feature, since the details differ and change over time.
A sensible policy is to use a local tokenizer for quick, frequent checks, such as trimming a history in a loop. Use the provider's counter, where available, for the final check before a large or costly request.
Counting after the call
The most reliable numbers come from the response itself. Almost every API returns a usage object with the input tokens and output tokens the provider billed for that call. The field names differ by provider, but the content is the same idea. Chapter 8 covers reading this data in detail. For this chapter, the point is that the reported count is the number you are charged for, so it is the ground truth for cost.
Use it to calibrate your local estimates. Log your estimated input count next to the billed input count for real requests. If the billed count is consistently higher by a stable amount, the difference is probably message overhead or tool definitions, and you can add that amount to your estimate. If the gap varies widely, your tokenizer probably does not match the model.
def estimate_error(estimated, billed):
return (billed - estimated) / billed
# Example numbers: you estimated 1,180 tokens and the API billed 1,240.
print(f"{estimate_error(1180, 1240):.1%}") # 4.8%A small, stable error like this is normal. A large or drifting error is a signal to investigate.
Common mistakes
- Counting words instead of tokens. The two numbers differ, and the ratio changes with the type of text.
- Forgetting the output. Limits apply to input plus output together, so counting only the prompt is not enough. The next chapters cover this budget.
- Mixing tokenizers. Counts from one model family do not transfer exactly to another.
- Ignoring overhead. Role markers, tool schemas, and system prompts all add tokens.
- Counting characters of decoded pieces. Decoding one token at a time can split multi-byte characters, so use it only to look at tokens, not to measure text.
- Treating a rule of thumb as a limit check. The four-characters-per-token rule is for planning, not for enforcement.
Exercise
You estimate a chat request at 3,900 input tokens with a local tokenizer for a different model family. The model's context window is 4,096 tokens and you want to allow 300 output tokens. Is it safe to send? Give two reasons for your answer.
Show answer
No. Input plus output is 3,900 + 300 = 4,200 tokens, which is already above 4,096, so the request does not fit even if the estimate is exact. In addition, the estimate comes from a tokenizer that does not match the model, and it may leave out message wrapper tokens or tool schemas, so the real input count could be higher. Shorten the prompt or lower the output limit, and keep a safety margin.
Exercise
Your logs show your local count is 1,000 tokens for a request and the API reports 1,060 input tokens. Over many requests the gap is always between 55 and 65 tokens. What does this suggest, and what would you do?
Show answer
A small, stable gap suggests fixed overhead that your local count misses, such as role markers or tool definitions. Add about 60 tokens to your local estimate for this kind of request. If the gap were large or varied widely, you should check whether your tokenizer matches the model.