Sub topic 6
Why history cannot grow forever: the context window
This chapter assumes you have the chat loop from the earlier chapters: a history list of role-tagged dictionaries that is sent in full on every turn. It also assumes you are comfortable with basic Python arithmetic and functions. No model SDK is needed, because the code here only measures and simulates.
The working model
A model can read only a limited amount of text per request. That limit is the context window, and it is measured in tokens. A token is a chunk of text that the model's tokenizer produces. In English it is often a short word or a piece of a longer one. A rough rule of thumb is that one token is about four characters, or about three-quarters of a word. Code, non-English text, and unusual words usually take more tokens per character.
The window is shared. Everything the model reads and everything it writes in one request must fit inside it:
| Part of the request | Counts toward the window? |
|---|---|
| System message | Yes, on every request |
| All earlier user and assistant messages | Yes, because you resend them |
| The new user message | Yes |
| The reply the model generates | Yes, it uses the same budget |
| Per-message formatting overhead added by the provider | Yes, a few tokens per message |
Because the API is stateless, your client resends the whole history each turn. The input therefore grows every turn, and eventually it cannot fit.
Growth is worse than it looks
Each turn adds one user message and one reply to the history. Each request then sends all of it again. The size of the latest request grows linearly with the number of turns. The total you send over a whole conversation, which determines cost and time, grows quadratically.
Take a concrete case. The system message is 200 tokens. Each turn has a 100-token user message and a 300-token reply. The window is 8,000 tokens, and you reserve 1,000 tokens for the reply.
- The request at turn n contains 200 + 400 × (n − 1) + 100 tokens.
- Input must stay at or below 8,000 − 1,000 = 7,000 tokens.
- Turn 17 sends 6,700 tokens and fits. Turn 18 would send 7,100 and does not.
- Across turns 1 to 17 you send 59,500 input tokens in total, although the conversation itself holds only about 6,700 tokens of text.
The simulation below reproduces these numbers. It runs as written.
def first_failing_turn(window, reserved, system, user, reply):
"""Return (turn that no longer fits, total input tokens sent before it)."""
sent_total = 0
history_size = system
turn = 1
while True:
request = history_size + user
if request + reserved > window:
return turn, sent_total
sent_total += request
history_size += user + reply
turn += 1
if __name__ == "__main__":
turn, sent = first_failing_turn(
window=8000, reserved=1000, system=200, user=100, reply=300
)
print(f"Turn {turn} does not fit. Input tokens sent so far: {sent}")Expected output:
Turn 18 does not fit. Input tokens sent so far: 59500Real models have much larger windows than 8,000 tokens. The shape of the problem stays the same, though. A bigger window delays the failure and does not remove it. Long inputs also cost more per request and respond more slowly, and many models use information in a very long prompt less reliably than information in a short one. So even when the history technically fits, trimming it can be the better choice.
Measuring the history
To act before a request fails, the program needs a size estimate. The most accurate source is the tokenizer that belongs to your model. Many providers publish one, offer a token-counting endpoint, or return a usage count with each response. Those details differ by provider, so this tutorial keeps counting behind one small function that you can replace.
def estimate_tokens(text):
"""Rough estimate: about four characters per token. Replace with the
tokenizer or counting endpoint of your provider for real limits."""
return max(1, len(text) // 4)
def history_tokens(history, per_message_overhead=4):
"""Estimate the input size of a message list."""
return sum(
estimate_tokens(m["content"]) + per_message_overhead for m in history
)
def fits(history, context_window, reserved_for_reply):
"""True if the history plus room for a reply fits in the window."""
return history_tokens(history) + reserved_for_reply <= context_window
if __name__ == "__main__":
history = [
{"role": "system", "content": "You are a concise, helpful assistant."},
{"role": "user", "content": "Explain what a context window is."},
]
print(history_tokens(history))
print(fits(history, context_window=8000, reserved_for_reply=1000))The overhead of four tokens per message is an assumption. Providers wrap each message in role markers, and the exact cost varies. Treat the result as an estimate and keep a safety margin.
Choosing the numbers
You need three values, and each one has a source.
- The context window. Read it from your model's documentation. It differs between models, and it can differ between versions of the same model.
- The reply reservation. Many APIs let you cap the reply length with a parameter. Reserve at least that cap. If you reserve nothing, a long history can leave the model almost no room to answer, and the reply may be cut off mid-sentence.
- A safety margin. Because your count is an estimate, aim for something like 90 percent of the usable budget. A request that is slightly over the real limit fails just as completely as one that is far over.
Keep these values in one place, such as constants near the top of the file, so you can change the model without hunting through the code.
CONTEXT_WINDOW = 8000
REPLY_RESERVE = 1000
SAFETY_FACTOR = 0.9
INPUT_BUDGET = int((CONTEXT_WINDOW - REPLY_RESERVE) * SAFETY_FACTOR)With these values, INPUT_BUDGET is 6,300 tokens. The next chapter uses a budget like this to decide how much history to drop.
Common errors
- Counting characters or messages instead of tokens. Twenty short messages and twenty pasted log files are very different sizes. A limit of "the last 20 messages" protects you only if messages stay small. The sliding window in this tutorial uses a message count for simplicity, so combine it with a token check when users may paste large text.
- Forgetting that the reply counts. If the input uses the entire window, there is no room left for output. Always compare input plus reservation against the window.
- Leaving out the system message. It is sent every turn. A long system prompt permanently reduces the space for conversation.
- Confusing the window with the output limit. Many models accept far more input than they will produce in a single reply. They are separate limits in the documentation.
- Assuming the failure is graceful. Providers typically reject an oversized request with an error, and they do not trim it for you. Some tools and frameworks do trim silently, which can drop your system message without any warning. Check what your library does.
- Testing only with short conversations. The bug appears at turn 40, not turn 4. Test with a fake model and a deliberately small window, as the testing chapter shows.
What to do when the history is too big
You have three broad options, and the following chapters build them in order.
- Drop the oldest turns. This is the sliding window. It is simple and predictable, but the bot forgets what was dropped.
- Summarize the oldest turns. You replace many messages with a short summary, which keeps the gist at the cost of an extra model call and some lost detail.
- Store facts outside the conversation. Long-term memory keeps selected information in a file or database and retrieves it when needed.
Whichever you choose, the system message must survive, and the remaining messages must still start with a user message and keep their pairs intact.
Exercise
A model has a 16,000-token window. Your system message is 500 tokens, and you reserve 2,000 tokens for each reply. With a 90 percent safety factor, what is the input budget? Then, if every turn adds 600 tokens to the history (user message plus reply), how many complete earlier turns can the history hold before the next user message of 100 tokens no longer fits?
Show answer
The input budget is (16,000 − 2,000) × 0.9 = 12,600 tokens. The history size before turn n is 500 + 600 × (n − 1), and the new 100-token user message must fit as well. So 500 + 600k + 100 ≤ 12,600, where k is the number of earlier turns. That gives 600k ≤ 12,000, so k ≤ 20. The history can hold 20 complete earlier turns, and the 21st turn is the first to send a request that exceeds the budget.