Sub topic 3
Counting tokens
This chapter assumes you can read basic Python and have called an LLM through a chat or completion API. It also assumes you know a token is the unit of text a model reads and writes. Here you will learn two ways to count tokens: before a call with a tokenizer library, and after a call with the usage data the API returns.
Why count at all
Limits and prices are both stated in tokens. A word count or character count tells you little, because one word can be one token or several. You need real token counts to check that a request fits the context window and to estimate cost.
Counting before the call with a tokenizer
A tokenizer is the code that splits text into tokens and maps each token to an integer ID. Counting tokens means encoding the text and taking the length of the result.
The open-source tiktoken library does this for OpenAI models. The example below prints the word count, the token count, and the text of each token.
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 sentence has seven words, but the token count is not seven. Punctuation such as the final period usually becomes its own token, and a leading space is normally attached to the word that follows it. Rare or long words split into several pieces. Exact splits depend on the encoding, so run the code to see the real output.
Counting after the call with usage data
Most APIs return the token counts they actually billed. This is the number to trust for cost, because it comes from the provider's own tokenizer and includes everything the provider added. The next chapters cover reading it in detail. For now, remember the two main fields: tokens in the input and tokens in the output.
Why might your own count differ from the reported one? Chat requests carry extra tokens that your raw text does not include:
- Message formatting, such as role markers around each message.
- A system prompt you did not count.
- Tool or function definitions sent with the request.
- Hidden output, such as reasoning tokens, in the output total.
Comparing the two methods
| Method | When you can use it | Accuracy | Needs a network call |
|---|---|---|---|
| Tokenizer library | Before sending | Exact for text with the matching tokenizer, but misses formatting overhead | No |
| API usage data | After the call | Exact, as billed | Yes |
The usual pattern is to count with a library before the call to decide whether to send, then record the usage data after the call to track real spending.
Common errors
- Using word count as a proxy. English text often runs somewhat above one token per word, and code, numbers, and non-English text can run much higher. Measure instead of guessing.
- Counting only the user message. The system prompt, earlier turns, and tool definitions all count as input.
- Using the wrong tokenizer. A count from
cl100k_basewill not match a model that uses a different vocabulary. - Forgetting the output. The input count is only half of the budget. The output also uses tokens, and later chapters combine the two.
A reusable helper
Wrapping the count in a function lets you pass it to other code. The trimming function in a later chapter takes any such function as an argument.
import tiktoken
enc = tiktoken.get_encoding("cl100k_base")
def count_tokens(text):
return len(enc.encode(text))
print(count_tokens("Tokens are not the same as words."))Exercise
You count a prompt with a tokenizer library and get 1,200 tokens. The API reports 1,260 input tokens for the same call. Give two likely reasons for the difference, and say which number to use for billing.
Show answer
Likely reasons: the request included overhead your text count missed, such as role markers around messages, a system prompt, or tool definitions, or the library's tokenizer differs slightly from the model's own. Use the API's 1,260, because it is what the provider billed.
Exercise
A teammate estimates tokens by multiplying the word count by 1. Name one kind of content where this will undercount badly.
Show answer
Source code, numbers, or non-English text. These usually split into many more tokens per word than ordinary English prose.