Sub topic 4
The context window
This chapter assumes you can read basic Python and have called a chat or completion API before. It also assumes you know a token is a chunk of text, usually a word or part of one, and that you can count tokens with a tokenizer library. Here you will learn what the context window is, what fills it, and how to check a request against it.
What the context window is
The context window is the maximum number of tokens a model can handle in a single call. It covers everything the model reads and everything it writes in that call. A model with an 8,000-token window cannot process a 7,900-token prompt and also write a 1,000-token answer, because the total would be 8,900.
Two points are easy to get wrong:
- The window is a limit per call, not a memory. The model keeps nothing between calls. If a chat seems to remember earlier turns, it is because your application sent those turns again.
- The window is measured in tokens, not words or characters. A 100,000-token window holds roughly 75,000 English words, but the ratio changes with the language, the content, and the tokenizer.
Window sizes differ by model and change over time. Look up the figure for the exact model and version you call. Do not assume a family of models shares one value.
What counts toward the window
Every token the model processes in the call uses space in the window. The main consumers are:
- The system prompt, which holds your instructions and persona.
- The conversation history: every earlier user message and assistant reply you include.
- The new user message.
- Attached material, such as pasted documents, retrieved passages, and tool or function definitions.
- Tool calls and tool results from earlier steps in an agent loop.
- Images and other non-text input. Providers convert these to tokens by their own rules.
- The model's output, including any hidden reasoning tokens (covered in a later chapter).
Items 1 to 6 are input. Item 7 is output. Both draw from the same pool.
Checking that a request fits
Before sending a request, check that the input plus the output you allow stays within the window. The spine's helper does this in one line:
def fits_in_window(input_tokens, max_output_tokens, context_window):
return input_tokens + max_output_tokens <= context_window
print(fits_in_window(2000, 500, 8000)) # True
print(fits_in_window(7600, 500, 8000)) # FalseThe check uses max_output_tokens, the cap you set on the reply, and not the number of tokens the model will actually write. You cannot know the actual length in advance. Many providers reject a request when input plus the cap exceeds the window, even if the real reply would have been short. Others accept the request and cut the output off when the window fills. Read your provider's documentation for the exact behavior, and do not rely on either one.
The next chapter covers output limits in detail. For now, treat the output cap as space you set aside before the call.
Computing the remaining room
In practice you often want to know how much input space is left. Subtract everything that is already committed, including the reserved output:
def remaining_input_budget(context_window, max_output_tokens,
system_tokens, history_tokens):
return context_window - max_output_tokens - system_tokens - history_tokens
room = remaining_input_budget(
context_window=8000,
max_output_tokens=1000,
system_tokens=500,
history_tokens=5200,
)
print(room) # 1300The new user message, plus any retrieved text or attachments, must fit in those 1,300 tokens. If it does not, you have to shrink something: trim the history, shorten the system prompt, or retrieve less text. Trimming is covered in a later chapter.
A negative result means the request is already over the limit before the new message is added. Treat it as a signal to act, not a number to pass along.
Counting accurately
The check is only as good as the token counts you feed it. Three habits help:
- Count with the tokenizer that matches the model. A count from one tokenizer can be off by ten percent or more for another model family, especially for code and non-English text. The
tiktokenexample from the earlier chapter is exact only for the encodings it implements. - Count the whole request, not only the text you wrote. Chat APIs add formatting tokens around each message to mark roles. Tool definitions and structured-output schemas are also converted to tokens. A character-by-character count of your visible text will undercount.
- Leave a safety margin when you estimate. Keeping 5 to 10 percent of the window free absorbs small counting errors. If the provider offers a token-counting endpoint, use it for the final check, because it counts what the server will actually see.
The most reliable number is the one the provider reports after the call. The usage chapter shows where to read it.
What happens when you exceed the window
Providers handle an over-long request in one of a few ways. Which one you get depends on the provider, the model, and sometimes a setting.
| Behavior | What you see | Risk |
|---|---|---|
| Reject the request | An error response, often a 400-class status naming the token limit | Safe but your app must handle the error |
| Truncate the input silently | A normal reply that ignores part of your prompt | The model answers without the dropped text, and you may not notice |
| Stop the output early | A reply that ends mid-sentence, with a stop reason such as a length limit | Partial answers can look finished |
Handle the rejection case explicitly. Do not retry the same request, because it will fail the same way. Shrink the input first, then retry.
A large window is not a free pass
A bigger window raises the ceiling, but three costs remain.
Cost. You pay for every input token on every call. Filling a 200,000-token window on each request is expensive even when the model accepts it. Pricing and history growth are covered in the chapters that follow.
Latency. Longer inputs take longer to process before the first output token appears. Calls near the limit are noticeably slower than short ones.
Quality. Models do not use all positions in a long prompt equally well. Research on long-context models has repeatedly shown weaker recall for facts placed in the middle of a very long input than for facts near the start or end. The effect varies by model and has shrunk in newer ones, but you should test with your own data instead of assuming perfect recall across the whole window.
Edge cases to plan for
- Different limits for input and output. Some models allow a large input window but a much smaller output cap. The combined limit and the output limit both apply, and you must satisfy both.
- Windows change between versions. A newer version of a model may have a different window than the one you tested. Store the window size in configuration, not as a constant scattered through your code.
- Tokenizer changes. A new model generation may use a new tokenizer. The same text can then produce more or fewer tokens, which changes both whether it fits and what it costs.
- Tool-heavy agents. Each tool result you append is more history. An agent loop that appends large tool outputs can fill the window in a few steps. Truncate or summarize tool results before adding them.
- Retrieved text. If you add retrieved passages to the prompt, budget for them up front. Decide how many tokens retrieval may use, then fetch only that many.
Putting it together
A safe pre-flight routine for each call looks like this:
- Look up the window size and the output cap for the model.
- Choose
max_output_tokensfor this task, as small as the task allows. - Count the system prompt, history, new message, and attachments with the matching tokenizer.
- Run
fits_in_windowwith a margin. If it fails, reduce the input and check again. - Send the request, then check the stop reason and the usage figures in the response.
This routine prevents rejected calls and silent truncation. It also gives you the numbers the cost chapters build on.
Exercise
A model has a 16,000-token context window. Your system prompt is 800 tokens, your conversation history is 11,400 tokens, and you set maxoutputtokens to 2,000. (a) How many tokens are left for the new user message? (b) A user pastes a 2,500-token document. Does the request fit, and what are two ways to make it fit?
Show answer
(a) 16,000 - 2,000 - 800 - 11,400 = 1,800 tokens remain. (b) No. The 2,500-token document exceeds the 1,800 tokens of room by 700 tokens, so input plus output would be 16,700 against a limit of 16,000. You can fit it by trimming at least 700 tokens of the oldest history, by lowering maxoutputtokens by at least 700 (to 1,300 or less) if shorter replies are acceptable, or by shortening or summarizing the document.
Exercise
A request succeeds, and the reply ends in the middle of a sentence. The response reports a finish reason that indicates a length limit. Which part of the budget caused this, and what should you check first?
Show answer
The reply hit the output cap or filled the window, so there was not enough reserved output space. Check maxoutputtokens against the length of answer you need, and check whether input plus maxoutputtokens sits close to the window size. Raise the cap if the window allows it, or shrink the input to free space.