Context window
The maximum tokens a model handles in one call, input and output combined: 128k to 1M+ today. Usable quality degrades well before the advertised limit, and every token costs money and latency.
Analogy: A desk, not a filing cabinet: everything the model works with must be on the desk for this call. A bigger desk helps, but piling it high makes things harder to find, and you pay rent per sheet.
How it works
- System prompt, tools, history and docs all share the window; the model has no memory outside it.
- Output has a separate, smaller cap (16,384 tokens for GPT-4o), set per call with
max_tokens. - Test effective context: in RULER (2024), only about half of models claiming 32k+ held up at 32k.
- Chat re-sends the whole history each turn, so session input tokens grow ~quadratically with turns.
- Plan overflow: reserve output room, then drop oldest turns, summarize history or retrieve only what's relevant.
Check yourself
Answer to mark it learned; your answers aren't scored.
On a 128k-context model, summaries of very long uploaded contracts stop mid-sentence. Logs show prompts of ~127k tokens and no API error. Best fix on the same model?
Go deeper
Full explanation
The context window is the maximum number of Tokens & tokenization a model can process in one request. System prompt, tool definitions, conversation history, retrieved documents, the user message and the generated output all share it. The model has no memory between calls: whatever isn't in the window doesn't exist for it.
Common sizes (2025–26) run from 128k (GPT-4o, Llama 3.1) through 200k (Claude 4.5 and earlier) to ~1M (Gemini 2.5 Pro, GPT-4.1, Claude 4.6+). 128k tokens is roughly 300 pages of English. Output has a separate, much smaller cap (e.g., 16,384 tokens for GPT-4o), set per call with max_tokens.
Three things matter more than the headline number:
- Effective vs advertised context. Models ace needle-in-a-haystack lookups but degrade on real reasoning over long inputs, and facts in the middle are used worst (Lost in the middle & context rot).
- Cost and latency scale with tokens. You pay for every input token on every call, and prefill time grows with prompt length: hundreds of thousands of tokens can mean seconds to tens of seconds before the first token.
- Overflow needs a policy. When content won't fit: truncate (drop the oldest turns, never the system prompt), summarize older history into a rolling summary, or retrieve only what's relevant per call (RAG (Retrieval-Augmented Generation)). Reserve room for the output first.
Code Fit chat history into the window with a rolling summary
import tiktoken
enc = tiktoken.get_encoding("o200k_base") # match your model's tokenizer
WINDOW = 128_000 # model context window: input + output
MAX_OUTPUT = 4_000 # reserve the answer's room first
SAFETY = 1_000 # message formatting overhead, tokenizer drift
def n_tokens(msg: dict) -> int:
return len(enc.encode(msg["content"])) + 4 # ~per-message overhead
def fit_history(system: dict, history: list[dict], summarize) -> list[dict]:
"""Keep recent turns verbatim; fold older ones into a summary instead of dropping them."""
budget = WINDOW - MAX_OUTPUT - SAFETY - n_tokens(system)
history_budget = int(budget * 0.8) # leave ~20% for the summary
kept, used = [], 0
for msg in reversed(history): # newest first: recency matters most
cost = n_tokens(msg)
if used + cost > history_budget:
break
kept.insert(0, msg)
used += cost
older = history[: len(history) - len(kept)]
if older: # an LLM call; cache the summary across turns instead of redoing it
summary = summarize(older, max_tokens=budget - used)
system = {**system, "content": system["content"] + "\n\nEarlier conversation, summarized:\n" + summary}
return [system] + keptReal example
A support chat sends a 3,000-token system prompt plus tools, and each turn adds ~600 tokens of user and assistant text. Turn 40 sends 3,000 + 40 × 600 = 27,000 input tokens, well inside 128k, so nobody worries. But the whole history is re-sent every turn: the session bills ~612k input tokens, not 27k. Capping history at 8k tokens with a rolling summary cuts that to ~390k and keeps latency flat from turn 14 on; caching the stable 3,000-token prefix with Prompt caching trims the bill further.
Trade-offs +3 · −3
+ You gain
- Whole-document tasks work without a retrieval pipeline: contracts, transcripts, code files.
- The model can relate facts across sections that chunked retrieval would separate.
- Fast prototyping: paste the data first, build retrieval only when cost or quality demands it.
− You pay
- Cost and prefill latency grow with every token sent, on every call.
- Quality degrades with length and position well before the advertised limit.
- Some providers charge a higher per-token rate above a threshold (e.g., Gemini 2.5 Pro above 200k).
Use it when
Fill the window deliberately for a single long artifact that must be read whole, many-shot prompts, or prototypes before building retrieval, and cache the prefix when the same long input repeats.
Avoid it when
Don't stuff it by default: large or changing corpora, high-QPS or latency-sensitive paths, and multi-hop reasoning over facts scattered across 100k+ tokens are better served by retrieval and trimming.
Numbers to know 5
- 128k tokens ≈ ~96k English words ≈ ~300 pages.
- Common windows (2025–26): 128k (GPT-4o, Llama 3.1), 200k (Claude ≤4.5), ~1M (Gemini 2.5 Pro, GPT-4.1, Claude 4.6+).
- Output caps are separate and smaller: 16,384 tokens for GPT-4o, 65,536 for Gemini 2.5 Pro.
- RULER (2024): of models claiming 32k+ context, only about half held up at 32k.
- Chat re-sends history every turn, so session input tokens grow ~quadratically with turn count.
Common pitfalls 4
- Not reserving output: a 127k prompt on a 128k model leaves ~1k tokens, and the answer is cut off mid-sentence.
- Framework truncation that silently drops the oldest messages first, system prompt included.
- Treating needle-in-a-haystack scores as proof the model reasons well over 500k tokens.
- Burying the key instruction mid-prompt; put long documents first and the question and instructions at the end.
Interview questions 2
Answer out loud first, then reveal.
The model supports 1M tokens. Why not put all our documents in the prompt instead of building RAG?Show answer
Three reasons, then the exception. Cost: a 1M-token prompt is paid on every call, so even at $1 per million input tokens that's ~$1 per question before output. Latency: prefilling that much can take tens of seconds. Quality: effective context is well below the advertised one; RULER and the lost-in-the-middle results show degradation with length and position. Most corpora also exceed 1M tokens, change daily and need per-user permissions. The exception: one large document, or a small stable corpus with prompt caching, where long context is simpler and often better.
How do you handle a conversation that outgrows the context window?Show answer
I budget explicitly: window minus reserved output minus system prompt and tools is what history and retrieval can use. Then, in order: cut waste first, since raw tool outputs and verbose JSON are usually the biggest offenders; keep the system prompt and the last few turns verbatim; fold older turns into a rolling summary; and move durable facts into retrievable memory instead of carrying them. The failure mode I watch for is silent truncation, so I log token counts per call and eval long sessions, because summaries lose details like IDs and numbers.