Sub topic 2
Context windows and what happens when you exceed them
This chapter assumes you can read Python, know the system, user, and assistant message roles, and have a rough idea of what a token is. It builds on the previous chapter's point that a chat API is stateless and your code resends the history on every request.
What a context window is
A context window is the maximum number of tokens a model can handle in a single request. Every model has one. The limit covers everything the model sees and everything it writes in reply. That includes:
- the system prompt
- every earlier user and assistant message you resend
- tool definitions and tool results, if you use tools
- the reply the model generates
The reply counts because the model produces it one token at a time, and each new token is added to the same sequence. Input and output share one budget, or in some APIs two related budgets. Check your provider's documentation for the exact rule.
A simple model of the limit:
input tokens + output tokens <= context windowMany providers also set a separate cap on output tokens, which is usually smaller than the window. So there are two limits to respect: the total window, and the maximum reply length.
Why long conversations hit the limit
The history grows with every turn, and you resend all of it each time. The request at turn N contains turns 1 through N. The size of one request grows roughly linearly, but the total tokens you have sent over the whole conversation grows quadratically. The table below uses an average of 300 tokens per turn, where a turn is one user message plus one assistant reply.
| Turn | Tokens in this request | Total tokens sent so far |
|---|---|---|
| 1 | 300 | 300 |
| 10 | 3,000 | 16,500 |
| 50 | 15,000 | 382,500 |
| 100 | 30,000 | 1,515,000 |
Two problems follow from this. The first is the hard limit: eventually one request does not fit. The second is cost and speed. You pay for input tokens on every request, and longer inputs take longer to process. A conversation can become slow and expensive long before it becomes impossible.
What happens when you exceed the limit
The result depends on the provider, the API, and any client library you put in between. You will see one of three behaviors.
The request is rejected
This is the most common behavior for direct API calls. The API returns an error, usually an HTTP 400, with a message saying the prompt is too long or that the input plus requested output exceeds the maximum. The error text and error code vary by provider, so match on the status and, where available, a structured error code rather than on message wording.
Rejection is the safest failure. Your code finds out immediately and can react. Plan for it: catch the error, trim or compact the history, and retry once. Do not retry the identical request, since it will fail the same way.
The input is silently truncated
Some services and some framework layers cut the input to fit instead of failing. When this happens, the part removed is often the beginning, which is where the system prompt lives. The model then loses its instructions and its persona, and nothing in your logs says why. Because the result is a plausible but wrong answer, this is harder to debug than an error.
If you use a library or hosted product that manages history for you, find out what it does at the limit. Do not assume.
The reply is cut off
This case is different. Your input fits, but the room left for the reply is too small, or you set the output cap too low. The model stops mid-sentence. Most APIs report this through a finish reason. Common values are stop or end_turn for a normal finish and length or max_tokens for a cut-off reply. Check the exact name in your provider's documentation.
A reply that ends because of the length limit is incomplete. If it is a JSON object, it will not parse. If it is code, it will not compile. Treat that finish reason as a signal, not as a finished answer.
def check_reply(finish_reason, text):
# Names vary by provider; "length" and "max_tokens" are common.
if finish_reason in ("length", "max_tokens"):
raise RuntimeError(
"Reply was cut off by the output limit. "
"Raise the output cap or reduce the input."
)
return text
print(check_reply("stop", "Done."))Limits that are not hard errors
A request can fit and still go badly. Even under the limit, very long inputs can degrade answers in ways that are hard to see.
- Position effects. Models often use information at the start and end of a long input more reliably than information in the middle. A fact buried in the middle of 100,000 tokens may be missed or misused.
- Distraction. Old, irrelevant messages compete with the current question. The model may follow an outdated instruction or mix up two similar topics.
- Latency. The time before the first token grows with input length.
- Cost. Input tokens are billed on every request, so a long history is paid for repeatedly. Some providers discount repeated prefixes through caching, but the history still has to be sent.
A large advertised window is therefore a ceiling, not a target. A larger window delays the problem without removing it, and a conversation that is long enough will still cross it.
Common mistakes
- Counting only the history. Forgetting the system prompt, tool definitions, and the reply allowance. Requests then fail at lengths you believed were safe.
- Treating the window as the input limit. If the window is 200,000 tokens and you ask for up to 8,000 output tokens, your input must stay under 192,000. The next chapters cover how to set this budget.
- Retrying without changing anything. A "too long" rejection never succeeds on retry.
- Trusting silent handling. Frameworks that trim automatically may drop the system prompt or split a tool call from its result.
- Ignoring the finish reason. Truncated replies pass for complete ones unless you check.
- Assuming one limit for all models. Window sizes differ by model and change between versions. Read the limit from configuration, not from a constant buried in code.
A guard that detects the problem early
You can catch overflow before the API does. The check below uses a rough estimate, which the next chapter replaces with better counting. It is enough to show the shape of the guard.
def estimate_tokens(message):
# Rough heuristic: about 4 characters per token, plus per-message overhead.
return len(message["content"]) // 4 + 4
def fits_in_window(messages, context_window, max_output_tokens):
used = sum(estimate_tokens(m) for m in messages)
return used + max_output_tokens <= context_window
history = [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Explain context windows. " * 2000},
]
if not fits_in_window(history, context_window=8192, max_output_tokens=1024):
print("Over budget: truncate or summarize before sending.")
else:
print("Safe to send.")Running this prints Over budget: truncate or summarize before sending. because the user message alone is about 12,000 tokens by the estimate. Because the estimate is approximate, real guards leave a safety margin, a point the budgeting chapter returns to.
Choosing a response
When a conversation approaches the limit, you have four options. Each trades something away.
| Option | What it does | What it costs |
|---|---|---|
| Fail with an error | Tells the user the conversation is too long | Poor experience, but nothing is lost silently |
| Truncate | Drops the oldest messages | Loses old facts entirely |
| Summarize | Replaces old messages with a shorter text | Loses detail, risks errors, costs an extra model call |
| Move out of the prompt | Stores history elsewhere and retrieves parts on demand | Adds infrastructure and retrieval errors |
The rest of this tutorial covers these options in order, starting with how to count tokens accurately, then truncation, then summaries, and then how to combine them.
Exercise
A model has a 16,000-token context window. Your system prompt is 600 tokens, your history is 14,900 tokens, and you set the maximum output to 1,000 tokens. Will the request be accepted, and what two distinct problems could appear if you shrank the window or raised the output cap further?
Show answer
Input is 600 + 14,900 = 15,500 tokens. Adding the 1,000-token output allowance gives 16,500, which exceeds 16,000, so the request is likely to be rejected (or the reply may be cut off, depending on the provider's rule). It does not fit. The two distinct problems are: (1) the request is rejected because input plus output exceeds the window, and (2) if the provider accepts the request but leaves too little room, the reply stops early with a finish reason such as "length", producing an incomplete answer. A third risk is silent truncation by a framework that trims the start of the input and drops the system prompt.
Exercise
Your application calls a framework that manages chat history for you. Users report that after long conversations the assistant stops following its formatting rules, but no errors appear in the logs. What is the most likely cause, and how would you confirm it?
Show answer
The framework is probably truncating the input silently and removing the oldest content, which includes the system prompt that holds the formatting rules. To confirm, log the exact messages and token count sent on each request, or inspect the framework's trimming settings, and check whether the system message is still present in long conversations. The fix is to pin the system prompt and trim or summarize the remaining history yourself.