Sub topic 6
Context Window Limits and Why They Matter
This chapter assumes you can call a chat-style LLM API in Python, know what a token is, and have read the earlier chapters on hosted APIs, open-weight models, and model size. It covers what a context window is, how to check whether your inputs fit, and how the window affects cost and model choice.
What the context window is
The context window is the maximum number of tokens a model can handle in one request. It covers everything the model sees and produces in that request:
- The system prompt and instructions.
- The conversation history you send.
- Any documents, search results, or examples you include.
- The output the model generates.
Providers usually publish one number, such as 8,000 or 128,000 tokens. Some providers also publish a separate cap on output tokens, which is often much smaller than the window. Check both numbers in the model's documentation.
The model has no memory between requests. Every call starts fresh, so anything you want it to use must fit in the window again each time.
Input and output share one budget
The window is a shared budget. If a model has a 16,000-token window and you send 15,000 input tokens, only about 1,000 tokens remain for the answer. A long answer is cut off or the API returns an error, depending on the provider.
A practical rule is to decide your maximum output length first, then compute how much input you can afford:
def input_budget(window: int, max_output: int, safety_margin: int = 200) -> int:
"""Tokens available for input after reserving output and a margin."""
return window - max_output - safety_margin
print(input_budget(window=16_000, max_output=1_000))
# 14800The safety margin covers small differences between your token count and the provider's. Chat formats add hidden tokens for message roles and separators, so an exact match is unlikely.
Counting tokens before you send
Tokens are not words. English text averages roughly three-quarters of a word per token, so 1,000 words is about 1,300 tokens. Code, other languages, and unusual text often use more tokens per word. Different models use different tokenizers, so the same text can have different counts on different models.
For a rough check, a character-based estimate works:
def estimate_tokens(text: str) -> int:
"""Rough estimate: about 4 characters per token for English text."""
return max(1, len(text) // 4)
document = "word " * 10_000
print(estimate_tokens(document))
# 12500Use this only for early planning. For real limits, use the tokenizer that matches your model. Many providers offer a token-counting endpoint, and open-weight models ship with a tokenizer you can load locally. Count with the same tokenizer you will deploy against, since a count from another model family can be off by 10 to 30 percent.
Why the window matters for model choice
The window sets a hard ceiling on what a task can include. Work through three questions.
- What is the largest input you will ever send? Measure the longest realistic case, not the average. One 200-page contract breaks a design sized for 10-page documents.
- Does the conversation grow? A chatbot that resends the full history adds tokens every turn. Eventually it hits the limit.
- How much output do you need? Summaries are short, while code generation or report writing can be long.
Windows vary widely between models. Small open-weight models often ship with windows of a few thousand to tens of thousands of tokens, while many hosted models offer well over 100,000. Treat any figure you read here as an example and confirm the current value for the exact model version you plan to use. Some open-weight models also let you configure a smaller window at serving time, and the default may be lower than the model's maximum.
The window affects cost
On hosted APIs you pay per token, so a large window is a ceiling on spend, not a free feature. Sending 100,000 tokens per request costs far more than sending 2,000, even though both fit. Reusing the cost function from the previous chapter:
def request_cost(input_tokens: int, output_tokens: int,
price_in_per_million: float, price_out_per_million: float) -> float:
return (input_tokens / 1_000_000) * price_in_per_million + \
(output_tokens / 1_000_000) * price_out_per_million
# Made-up prices: $1.00 per million input tokens, $4.00 per million output tokens
small = request_cost(2_000, 300, 1.00, 4.00)
large = request_cost(100_000, 300, 1.00, 4.00)
print(f"2k input: ${small:.4f} 100k input: ${large:.4f} ratio: {large / small:.0f}x")
# 2k input: $0.0032 100k input: $0.1012 ratio: 32xStuffing everything into the window costs about 32 times more per request in this example. Some providers offer discounted pricing for cached repeated prefixes, which helps when the same long instructions or document appear in many requests. Check whether your provider supports it and how long the cache lasts.
On self-hosted models, long inputs cost memory instead of money. The model stores intermediate values for every token in the context, called the KV cache, and it grows with context length and with the number of simultaneous requests. A long window can force you to serve fewer users at once or to buy more GPU memory. Latency also rises with input length, because the model must process all input tokens before the first output token appears.
A bigger window is not always better
A large window does not guarantee the model uses the whole input well. Known problems include:
- Weaker recall in the middle. Some models find facts near the start or end of a long input more reliably than facts in the middle.
- Distraction. Irrelevant text can pull the answer off course.
- Quality drop at long lengths. A model that works well on 4,000 tokens may be less accurate at 100,000.
You can only learn this by testing. The evaluation chapter shows how to build a set of cases. For long-context tasks, include cases at your real maximum length, with the key fact placed at different positions.
Strategies when the input does not fit
| Strategy | How it works | Main trade-off |
|---|---|---|
| Truncate | Cut the input at the limit | Loses information, possibly the important part |
| Summarize | Condense older history or documents first | Extra model calls, some detail lost |
| Retrieve | Search a collection and send only relevant pieces | Needs an index, and retrieval can miss the right piece |
| Chunk and combine | Process pieces separately, then merge results | More calls, and cross-piece reasoning is harder |
| Choose a larger-window model | Use a model that fits everything | Higher cost and sometimes more latency |
Pick the least expensive strategy that passes your evaluation set. Retrieval is often the best first choice for large document collections, because it keeps per-request input small regardless of collection size.
Here is a simple guard that trims old conversation turns to stay within budget:
def trim_history(messages: list[dict], budget: int, count) -> list[dict]:
"""Keep the system message and the newest turns that fit in `budget` tokens."""
system, rest = messages[0], messages[1:]
kept: list[dict] = []
used = count(system["content"])
for message in reversed(rest):
cost = count(message["content"])
if used + cost > budget:
break
kept.append(message)
used += cost
return [system] + list(reversed(kept))
history = [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "First question " * 50},
{"role": "assistant", "content": "First answer " * 50},
{"role": "user", "content": "Latest question"},
]
trimmed = trim_history(history, budget=100, count=lambda t: len(t) // 4)
print(len(trimmed))
# 2The function drops the oldest turns first and always keeps the system message. A real application might summarize the dropped turns instead of discarding them.
Common errors
- Sizing for the average input. Plan for the longest realistic request, then add margin.
- Forgetting the output. Reserve output tokens before filling the input.
- Using the wrong tokenizer. Counts from one model family do not transfer reliably.
- Assuming the advertised maximum is the configured value. A self-hosted server may use a smaller default.
- Treating fit as quality. Text that fits may still be handled poorly. Test it.
Exercises
Exercise
A model has a 32,000-token window. Your application needs answers up to 2,000 tokens, and you want a 300-token safety margin. The system prompt uses 500 tokens and each retrieved document chunk uses 1,500 tokens. How many chunks can you include if the user question is 200 tokens?
Show answer
Input budget = 32,000 - 2,000 - 300 = 29,700 tokens. Fixed input = 500 + 200 = 700 tokens. Remaining = 29,000 tokens. 29,000 / 1,500 = 19.33, so you can include 19 chunks.
Exercise
With the made-up prices of $1.00 per million input tokens and $4.00 per million output tokens, what does one request with 50,000 input tokens and 500 output tokens cost, and why might you still avoid sending that much input if a 5,000-token input passes your evaluation?
Show answer
Cost = 0.05 x $1.00 + 0.0005 x $4.00 = $0.05 + $0.002 = $0.052 per request. The 5,000-token input would cost about $0.007, roughly seven times less. If it passes your evaluation, the extra input only adds cost and latency, and it may reduce accuracy through distraction.