Sub topic 5
Tokens and the context window
Prerequisites
This chapter assumes you can send a chat request and read the response, as covered in the earlier chapters. You should know the usage object exists and be comfortable with Python and JSON. Field names below follow the chat-completions shape. Other providers name things differently, so check your provider's documentation.
What a token is
A model does not read characters or words. It reads tokens. A token is a chunk of text that the model's tokenizer produces. The tokenizer is a fixed program that splits text into pieces from a vocabulary of tens of thousands of entries. Each piece maps to an integer ID, and the model works on those IDs.
A token can be a whole common word, part of a rare word, a single punctuation mark, or a space plus a word fragment. Some examples with a typical English tokenizer:
theis usually one token.tokenizationmay split into two or three tokens.- A long identifier such as
getUserAccountBalancesplits into several tokens. - Text in languages other than English, emoji, and rare symbols often use more tokens per character.
Rules of thumb for English prose are about 4 characters per token, or about 0.75 words per token. Treat these as rough estimates. Code, JSON, and non-English text usually cost more tokens than the same length of English prose. Different model families use different tokenizers, so the same text can have different token counts across models.
Why tokens matter
Tokens are the unit for three things you care about:
- Limits. The context window is measured in tokens.
- Cost. Providers bill per token, usually at different prices for input and output.
- Latency. Generation time grows with the number of output tokens, and processing time grows with the number of input tokens.
The context window
The context window is the maximum number of tokens the model can handle in one request. It covers everything: the system message, the full message history, any tool definitions, and the reply the model generates.
The key point is that input and output share the same budget:
prompt tokens + completion tokens <= context windowSuppose a model has a 128,000-token window. If your prompt uses 120,000 tokens, the reply can use at most 8,000 tokens. Many models also have a separate cap on output length that is smaller than the window. A model may accept 128,000 tokens of context but limit a single reply to, say, 16,000 tokens. Check both numbers in your provider's model documentation.
Reading token counts from the response
The response reports what the request actually used. In the chat-completions shape, the usage object looks like this:
{
"usage": {
"prompt_tokens": 42,
"completion_tokens": 18,
"total_tokens": 60
}
}prompt_tokenscounts everything you sent, including the message formatting the API adds around each message.completion_tokenscounts what the model generated.total_tokensis the sum.
Some providers add detail fields, for example cached prompt tokens or reasoning tokens. Reasoning tokens are tokens a model spends thinking before it answers. They are billed and count toward the output limit even though you may not see them in the reply text.
The usage numbers are the ground truth for billing. Log them on every call.
Counting tokens before you send
Sometimes you need the count before the request, for example to decide whether to trim history. You have two options.
- Use the provider's tokenizer. Many providers publish a tokenizer library or a token-counting endpoint. This gives an exact count for that model.
- Estimate. Divide the character count by 4 and add a safety margin.
The following example uses the open-source tiktoken library to count tokens. It is accurate for OpenAI models that use the named encoding. For other providers it is only an approximation.
import tiktoken
# Pick the encoding that matches your model. If you are unsure,
# treat the result as an estimate and keep a safety margin.
encoding = tiktoken.get_encoding("cl100k_base")
texts = [
"Explain what a token is in one sentence.",
"getUserAccountBalance",
"Bonjour, comment allez-vous ?",
'{"name": "Sam", "age": 31}',
]
for text in texts:
ids = encoding.encode(text)
print(f"{len(ids):3d} tokens | {len(text):3d} chars | {text}")Install it with pip install tiktoken. The first call to get_encoding may download vocabulary data, so it needs network access the first time.
Counting the text of your messages gives a lower bound. The API adds a few tokens of overhead per message for role markers and separators. Tool definitions and images also consume tokens. Leave a margin of a few percent, or use the provider's counting method for exact figures.
Budgeting a request
A practical budget has three parts:
- Count the prompt tokens (system message, history, new message, tools).
- Choose the largest reply you are willing to accept, and set the length parameter to it (the next chapter covers
max_tokensand related settings). - Check that prompt plus reply is below the window, with margin.
def fits(prompt_tokens, max_reply_tokens, context_window, margin=0.05):
"""Return True if the request should fit in the context window."""
limit = int(context_window * (1 - margin))
return prompt_tokens + max_reply_tokens <= limit
print(fits(prompt_tokens=120_000, max_reply_tokens=8_000, context_window=128_000)) # False
print(fits(prompt_tokens=100_000, max_reply_tokens=8_000, context_window=128_000)) # TrueThe first call returns False because the 5 percent margin reduces the usable limit to 121,600 tokens, and 128,000 tokens of prompt plus reply exceeds it. This is deliberate. Token counts from an estimate can be off, and a request that is a few tokens over the limit fails outright.
What happens when you exceed the window
Behavior depends on the provider and model, but there are two common outcomes.
- Rejection. The API returns a 400-class error that says the context length was exceeded. The message usually states the maximum and the number you requested. This is the most common behavior, and it is the safer one because nothing is silently lost.
- Truncation. Some systems drop the oldest content or cut the prompt without telling you. The model then answers from incomplete input. Check your provider's documentation to learn which applies.
A third case is separate. The prompt fits, but the reply hits the length cap before it is finished. The request succeeds, but the response ends mid-sentence, and the finish_reason is length instead of stop. Always check finish_reason when output completeness matters.
Edge cases and common errors
- Forgetting that output counts. A prompt that fits by itself can still fail if you request a large reply cap on top of it. Some APIs reject the request up front when prompt tokens plus the requested maximum exceed the window.
- History growth. Each turn in a conversation resends all earlier messages, so the prompt grows every turn. A chat that works for 10 turns can fail at turn 200. The chapter on conversation state covers trimming and summarizing.
- Whitespace and formatting. Leading spaces, newlines, and indentation can change tokenization. Pretty-printed JSON costs more tokens than compact JSON, so send compact JSON when you pass data to a model.
- Counting characters instead of tokens. A limit of 4,000 characters is not a limit of 4,000 tokens. Use token counts for anything tied to the window or the bill.
- Mixing tokenizers. A count from one model's tokenizer can be wrong for another model. Recount when you switch models.
- Long context is not free. A large window lets you send more, but cost and latency rise with every token you send. Models can also use information in the middle of a very long prompt less reliably than information near the start or end. Send what is relevant, not everything you have.
Compact comparison
| Concept | Measured in | Who sets it | What exceeding it does |
|---|---|---|---|
| Context window | Tokens, prompt plus reply | The model | Request is rejected, or input is truncated |
| Output cap (model limit) | Tokens, reply only | The model | Reply is cut off |
| Reply length setting | Tokens, reply only | You | Reply ends early with `finish_reason` of `length` |
| Price | Currency per token | The provider | Higher bill |
Exercise
A model has a 32,000-token context window. Your prompt uses 29,500 tokens, and you ask for a reply of up to 4,000 tokens. Will the request fit? What is the largest reply cap that would fit, ignoring any safety margin? And if the reply stops mid-sentence on a request that succeeded, which response field do you check first?
Show answer
It will not fit, because 29,500 + 4,000 = 33,500, which is over 32,000. The largest reply cap that fits is 32,000 - 29,500 = 2,500 tokens. For a reply that stops mid-sentence, check finish_reason. A value of length means the reply hit the length limit.
Exercise
A teammate says, "Our limit is 8,000 characters, so we never hit the context window." Give two reasons this reasoning is unreliable.
Show answer
First, the window is measured in tokens, not characters, and the number of tokens per character varies. Code, JSON, and non-English text use more tokens per character than English prose. Second, the reply and the resent conversation history also count toward the window, so the input text alone does not tell you the total.