Context Windows Explained
Independent educational resource, not an official Anthropic course. Facts about the API, prices and limits were checked against Anthropic's documentation on 15 November 2026 and the code was run against a local mock of the API, not the live service. Check the linked official pages before relying on a number, and test with your own key.
The context window is the model's working memory: everything it can look at when writing a reply. It is big on current models, but "it fits" is not the same as "it works well" or "it is cheap". This lesson explains what counts toward the window, what happens when you overflow it, why more context can make answers worse, and the practical ways to keep conversations inside it.
Learning objectives
- Define the context window and list everything that counts toward it.
- State the window and output sizes for current models and the overflow behaviour.
- Explain "context rot" and why curating context matters.
- Trim a conversation to a token budget in code.
- Know the server-side options (compaction, context editing) that exist.
Prerequisites
What the context window is
Anthropic defines the context window as all the text a model can reference when generating a response, including the response itself. It is different from the training data: it is a working memory that holds only this request. Everything in the request counts: the system prompt, every message in messages (including tool results, images and documents), and your tool definitions. The output counts too, including extended thinking. If you use prompt caching, the cache-read and cache-write tokens count toward the window as well, because caching changes what you pay, not whether the tokens occupy space.
|<-------------------------- context window (e.g. 1M tokens) -------------------------->|
| system prompt | tool definitions | history (all earlier turns) | new message | REPLY (+thinking) |
|<------------------------------- input -------------------------------->|<--- output --->|
Sizes
On the documentation page checked on 15 November 2026, Claude Fable 5.2, Opus 5.5, Sonnet 5.5 and Haiku 5.5 (and several earlier models) have a 1M-token context window, and a single request can generate up to 128k output tokens. Other models, including some older ones, have a 200k-token window. A single request can include up to 600 images or PDF pages (100 for models with a 200k window). For 1M-window models, long requests are billed at standard pricing, with one exception worth knowing: Claude Haiku 5.5 charges more when the prompt is over 100,000 tokens ($0.50 and $2.50 per million input and output tokens, against $0.10 and $0.50 for shorter prompts, on the pricing page checked).
More context is not automatically better
Anthropic's documentation is direct about this: as token count grows, accuracy and recall degrade, a phenomenon it calls context rot. A model given 800,000 tokens does not use all of them equally well. So the engineering question is not "how much can I fit?" but "what is the least context that contains what the answer needs?" Curating the context matters as much as the size of the window.
Practical consequences:
- Retrieve the relevant passages instead of sending whole manuals (the idea behind RAG, covered later).
- Put long documents at the top of the prompt and your question at the end; Anthropic reports that queries at the end can improve quality by up to 30 percent in tests on complex multi-document inputs.
- Remove stale turns, resolved tool results and boilerplate.
What happens at the limit
| Situation | Result |
| The input alone is larger than the window | 400 invalid_request_error ("prompt is too long") on every model. |
On Claude 4.5 models and newer: input plus max_tokens exceeds the window | The request is accepted. If generation reaches the window limit, it stops with stop_reason: "model_context_window_exceeded". Treat the output as truncated. |
| Earlier models | A validation error, unless you opt in to the newer behaviour with a beta header. |
So there are two different failures to handle: an error before anything runs, and a successful response that was cut short.
Thinking and the window
Thinking tokens count toward the window, are part of max_tokens, and are billed as output. Whether thinking from earlier turns stays in later requests depends on the model. On the current models (Opus, Sonnet and Haiku 5.x and the Fable models) the API keeps previous thinking blocks by default, so they count as input in later turns; on older models the API strips them automatically. If you use tools with thinking, return the unmodified thinking block with the tool result.
Managing long conversations
| Strategy | How | Note |
| Trim | Drop the oldest turns to fit a token budget (code below). | Simple, loses old information. |
| Summarise | Replace old turns with a short summary you generate. | Costs a call; keep key facts. |
| Server-side compaction | The API summarises earlier parts of the conversation for you. | Documented as the primary strategy for long-running conversations; in beta for Claude 4.6 and later. |
| Context editing | Clear old tool results or thinking blocks automatically. | Aimed at agentic workflows. |
| Retrieve, do not paste | Send only the passages that matter. | Often the biggest win. |
Step by step: fit a conversation to a budget
This function drops whole oldest user and assistant pairs until the counted input fits what remains after reserving space for the reply. It takes the counter as a parameter, so in production you pass a function that calls the token counting endpoint, and in tests you pass a fake. It leaves a safety margin because counts are estimates:
from typing import Callable
# The window is shared by everything in the request: system prompt, every message, tool definitions
# AND the reply you ask for. Plan the reply first, then give the input whatever is left.
Counter = Callable[[list[dict]], int]
def fit_history(
messages: list[dict],
count_tokens: Counter,
context_window: int,
reserve_for_output: int,
safety_margin: float = 0.10,
) -> list[dict]:
"""Drop the oldest user+assistant pairs until the input fits.
count_tokens receives a message list and returns its input token count (use the token counting
endpoint in real code). The margin covers the fact that counts are estimates.
"""
budget = int((context_window - reserve_for_output) * (1 - safety_margin))
kept = list(messages)
while len(kept) > 1 and count_tokens(kept) > budget:
del kept[:2] # a whole pair, so the list still starts with a user message
if count_tokens(kept) > budget:
raise ValueError("The newest message alone does not fit. Shorten it or summarise it first.")
return kept
def is_truncated_by_window(message) -> bool:
"""True when generation ran into the context window instead of finishing."""
return message.stop_reason == "model_context_window_exceeded"
Tested with a fake counter (one word equals one token): a 12-message history was reduced to the 6 newest messages, still starting with a user turn and under the budget; a single message too large to fit raised a clear error; and the helper recognised a truncated response. In production, wire the counter to the API like this:
def count_with_api(messages: list[dict]) -> int:
return client.messages.count_tokens(model=MODEL, system=SYSTEM, messages=messages).input_tokens
history = fit_history(history, count_with_api, context_window=1_000_000, reserve_for_output=4_000)
Include the system prompt and tool definitions in the count, because they occupy the window too. Counting once per request costs an extra call; for most apps, trimming by a simple turn limit (lesson 2.3) is enough, and token-based trimming is for long documents and agents.
Real-world use case (illustrative scenario)
This scenario is an invented example to show how the ideas fit together. It is not a case study and its details are not measured results.
A legal-research assistant lets users upload a 300-page contract and ask questions. Pasting the whole contract fits in the window, but answers about clause 41 were sometimes wrong. The team switched to retrieving the few most relevant sections per question and putting them at the top of the prompt with the question last. Input shrinks to a small fraction of the contract, and because there is less irrelevant text, answers get both cheaper and more reliable.
Common errors and solutions
| Symptom | Cause | Fix |
| 400 "prompt is too long" | Input exceeds the window. | Trim, summarise or retrieve; count first. |
Reply cut off with model_context_window_exceeded | Input plus output reached the limit. | Reduce input or max_tokens; treat output as truncated. |
| Answers get worse as the chat grows | Context rot, stale turns. | Curate: trim, summarise or compact. |
| Cost per turn keeps rising | History resent every turn. | Trim, cache stable prefixes (lesson 2.9). |
| Thinking-enabled tool loop errors | Thinking block modified or dropped. | Return the whole unmodified block with tool results. |
Security considerations
- A bigger window means more untrusted text in one place. Documents you retrieve can contain instructions meant for the model (prompt injection); wrap them as data and never grant them authority (lessons 1.6 and module 8).
- Keep one user's data out of another's context. Never build history from a shared store without a user check.
- Do not keep sensitive text in history longer than needed.
Performance and cost considerations
- Input tokens drive both cost and latency. Smaller, relevant context is faster and cheaper.
- Prompt caching lowers the price of a repeated prefix but not its size in the window.
- Check the long-prompt price rule for the model you use (Haiku 5.5 changes price above 100,000 tokens).
Key takeaways
- The window holds the whole request plus the reply; thinking and cached tokens count.
- Current models offer 1M tokens in and up to 128k out, but more context can reduce quality.
- Know both failures: a 400 before generation and a truncated success.
- Trim, summarise, retrieve or compact; put documents first and the question last.
Lesson recap: the window is working memory for the whole request, so curate context instead of filling it.
Knowledge check
- Name four things that count toward the context window.
- What is context rot?
- What
stop_reason signals that generation hit the window limit?
- Why leave a safety margin when trimming to a budget?
- Where should a long document go relative to your question?
Answers and explanations
- System prompt, messages (including tool results, images and documents), tool definitions, and the output including thinking.
- The degradation of accuracy and recall as the amount of context grows, even when it fits.
model_context_window_exceeded. Treat the response as truncated.
- Token counts are estimates, so a margin prevents going slightly over.
- At the top, with the question and instructions after it; Anthropic reports this can improve quality.
Official references and further reading
Related tutorials