Sub topic 6
Why History Cannot Grow Forever: The Context Window
This chapter assumes you can write basic Python (functions, lists, dictionaries, exceptions). It also assumes you have read the earlier chapters, so you know that a chat API is stateless and that your program keeps the history as a list of role-tagged messages and resends it on every turn.
The model reads a bounded amount of text
Every model has a context window: the maximum amount of text it can take in and produce in a single request. The limit is measured in tokens, not characters or words. A token is a chunk of text, often a short word or part of a longer one. In English, a token averages about four characters, but the ratio varies by language, by code, and by the model's tokenizer.
The window is shared. Your input and the model's reply must fit inside it together:
prompt tokens + reply tokens <= context windowThe prompt here is the whole history: the system message, every earlier user message, and every earlier assistant reply, plus the new user message.
Why the problem grows with each turn
Because the client resends everything, each request is larger than the one before. The reply to turn 10 costs more input than the reply to turn 1, even if the new question is short.
The diagram below shows the shape of the problem.
Two costs follow from this, even before you hit the limit:
- Money. Most providers charge per token. A long history is billed again on every turn.
- Latency. More input tokens usually means a slower first response.
What happens at the limit
When the prompt is too large, providers typically behave in one of two ways:
- They reject the request with an error, often described as a context length or maximum tokens error.
- They accept it but leave too little room for the reply, so the answer is cut short.
Either way, your program must act before the limit, not after. A chat that works for 20 turns and then crashes on turn 21 is a common bug in first versions.
Estimating size
You do not need an exact count to start. Your provider's SDK or documentation usually offers a token counter for its models. If you want a rough guess without a library, characters divided by four is a workable estimate for English text.
def estimate_tokens(messages):
"""Rough token estimate: about 4 characters per token, plus a small
per-message overhead for role and formatting."""
total = 0
for m in messages:
total += len(m["content"]) // 4 + 4
return total
history = [
{"role": "system", "content": "You are a concise, helpful assistant."},
{"role": "user", "content": "Explain what a context window is."},
]
print(estimate_tokens(history))Treat this as a guide only. Use it to decide when to trim, and keep a safety margin of a few hundred tokens or more.
Budgeting the window
A practical plan splits the window into parts:
| Part | Notes |
|---|---|
| System message | Fixed size, always kept |
| Older turns | The part you will trim or summarize |
| New user message | Size is up to the user |
| Reply reserve | Room you leave for the model's answer |
If the window is 8,000 tokens and you reserve 1,000 for the reply, your history budget is 7,000 tokens. When the estimate exceeds the budget, you remove the oldest turns first. The next chapter implements this as a sliding window.
Common errors
- Counting only the new message. The limit applies to the whole request, not the latest input.
- Forgetting the reply. If the history fills the window exactly, the model has no space to answer.
- Trusting message counts. Ten messages may be 200 tokens or 20,000. Limits are in tokens, so a message-count window is only a proxy.
- Trimming the system message. It defines the bot's behavior, so it must survive any trimming.
Exercise
A model has an 8,000-token context window. Your system message is 300 tokens, you reserve 1,000 tokens for the reply, and the user's new message is 200 tokens. How many tokens of earlier conversation can you keep?
Show answer
8,000 - 300 - 1,000 - 200 = 6,500 tokens. Anything beyond that must be trimmed or summarized.
Exercise
Why does the cost of each turn rise even when the user types short messages?
Show answer
The client resends the entire history on every request, so the input grows with every turn and you are billed for all of it each time.