Try Bifrost Enterprise free for 14 days.
Request access
[ Context Window ]

What is a context window?

Quick answer

A context window is the total token budget a language model can attend to in a single request. The system prompt, tool definitions, retrieved documents, conversation history, and, on APIs such as Anthropic's, the generated output all have to fit inside it.

Updated 2026-09-07

A context window is the total token budget a language model can attend to in a single request. Everything the model can see has to fit inside it: the system prompt, tool definitions, retrieved documents, the entire conversation so far, and, on APIs such as Anthropic's, the tokens it is about to generate.

"The 'context window' refers to all the text a language model can reference when generating a response, including the response itself."

Source: Anthropic, Context windows

The window constrains cost, latency, and answer quality, and patterns such as retrieval, summarization, and sub-agents exist because it is finite.

The window is measured in tokens rather than words, so tokenization is the prerequisite concept.

Tokenization

Text is split into tokens by a subword tokenizer. Hugging Face describes byte pair encoding (BPE) as the most popular algorithm in Transformers and Unigram, used by T5 among others, as the second. Sennrich et al. brought BPE, originally a compression algorithm, to neural machine translation. Byte-level BPE starts from the 256 byte values and repeatedly merges the most frequent adjacent pair until it reaches a target vocabulary; GPT-2's has 50,257 entries. Frequent words survive as single tokens; rare words fragment.

How tokenizers split text affects every budget:

  • English prose averages roughly four characters per token, about 0.75 words per token (roughly 1.3 tokens per word), per OpenAI's rule of thumb. Treat this as a planning heuristic, not a guarantee.
  • Non-English text costs more. Scripts underrepresented in the tokenizer's training corpus receive fewer merges, so the same meaning can cost several times as many tokens. Petrov et al. found tokenized lengths differ by up to 15 times between languages in some cases, which raises the cost of multilingual products.
  • Measure code and structured data separately. Indentation, punctuation, and JSON delimiters can each become their own tokens, so do not apply prose ratios to a serialized payload.
  • Tokenizers are model-specific. Anthropic notes that Claude Opus 4.7's updated tokenizer can map the same input to roughly 1.0 to 1.35 times as many tokens, depending on content type, which changes both cost estimates and window fit.

Count, do not estimate. Use tiktoken for OpenAI models and the token counting endpoint for Claude.

py

The parts of a request that fill the window

Diagram
[ RENDERING DIAGRAM ]

Two of these are easy to underestimate. Tool definitions are fixed but large. Anthropic's tool search docs put 50 tools at 10,000 to 20,000 tokens, and its advanced tool use post lists the GitHub MCP server at 35 tools and about 26,000 tokens, resent on every turn of an agent loop. Conversation history grows without bound unless something manages it.

Conversation history is re-sent and re-billed every turn. A 20-turn conversation costs the running sum of the transcript, so cumulative input spend grows quadratically with conversation length. Prompt caching reduces the price of those repeated tokens but does not remove them from the window.

Context window vs. max_tokens

Confusing the two causes a specific class of production bug.

Context windowmax_tokens
What it boundsInput plus output combinedOutput only
Set byThe modelYou, per request
Typical size200k or 1M tokens on current Claude modelsYour choice, up to the model's output cap (128k on Claude's 1M-token models)
Failure modeHTTP 400, "prompt is too long" (Anthropic)Response truncated (finish_reason: length on OpenAI; stop_reason: max_tokens on Anthropic)
Can you raise itNo, pick a different modelYes, up to the output cap

The bug is setting max_tokens so that input plus max_tokens exceeds the window. Per Anthropic's docs, Claude models before the 4.5 generation reject the request with a validation error; Claude 4.5 and newer accept it and, if generation reaches the limit, stop with stop_reason: model_context_window_exceeded, which is harder to notice because it looks like a normal short answer. Budget explicitly instead: reserve the output allowance first, then spend what remains on input.

The cost curve of long context

Self-attention compares every token against every other token, so attention compute scales with the square of sequence length, a property of the architecture described in Attention Is All You Need. KV cache memory, by contrast, grows with each token a request holds (Kwon et al.). Together they affect long-context requests in these ways:

  1. Time to first token grows faster than linearly with input length, because prefill is doing the quadratic work. Long-context requests feel slow before a single token appears.
  2. Concurrency collapses. GPU memory is fixed and per-sequence cache grows with length, so a server handling 200k-token requests holds far fewer sequences at once than one handling 4k-token requests. Kwon et al. found that KV cache memory limits batch size in LLM serving.
  3. Some models price long context at a premium above a threshold, so crossing it changes unit economics discontinuously. Anthropic, for example, charges more for Claude Haiku 5.5 prompts over 100,000 tokens.

A large window is not uniformly usable

Advertised context length is capacity, not competence. Where information sits inside the window changes whether the model uses it.

Liu et al., in Lost in the Middle, showed that multi-document question answering follows a U-shaped curve: accuracy is highest when the relevant passage sits at the very start or the very end of the input and measurably worse when it is buried in the middle. Longer windows were not exempt.

Needle-in-a-haystack testing plants a distinctive sentence at varying depths and asks the model to recall it. The RULER authors note that models score nearly perfectly on the vanilla test, which makes it a weak benchmark, because exact-match retrieval of an unusual string is far easier than reasoning over dispersed information. RULER extends the test with multiple needles, multi-hop tracing, and aggregation, and found that only about half of the models claiming 32k or more of context kept satisfactory performance at 32k. Anthropic calls the broader pattern context rot: as token count grows, accuracy and recall degrade. Its context engineering post links the term to Chroma's research, which found that model performance consistently degrades with increasing input length.

Put the operative instruction after long reference material, not before it. Anthropic reports that queries at the end can improve response quality by up to 30 percent in its tests. Prefer fewer, more relevant retrieved chunks, because precision beats recall once the model must reason rather than quote. And evaluate at the context length you actually run at.

Context management strategies

StrategyMechanismMain trade-offBest for
TruncationDrop the oldest messages when a threshold is hitSilent loss of early context, and it breaks prompt cache prefixesShort, near-stateless chat
Sliding windowKeep the last N turns plus a pinned system promptSame recall loss, but bounded and predictableSupport and Q&A bots
Summarization / compactionSummarize old turns into a compact note and restart the windowOne extra model call, and summaries are lossyLong-running agent sessions
RetrievalKeep everything external, fetch only what the turn needsOnly as good as the retriever; adds infrastructureLarge or private corpora
Sub-agent offloadingDelegate a subtask to a fresh context, return only the resultCoordination complexity and more model callsDeep research, multi-step work

Truncation also has a cost beyond recall loss. Cache hits require 100 percent identical prompt segments up to the cache breakpoint (Anthropic prompt caching), so trimming from the front of a prompt invalidates the cache and can raise cost even as it lowers token count. Anchor the stable prefix and remove from the middle instead. Retrieval-augmented generation decouples corpus size from window size entirely.

Context engineering

Context engineering is what Anthropic calls "the natural progression of prompt engineering." Prompt engineering optimizes the wording of one instruction. Context engineering treats the window as a managed resource across a whole run: what enters it, when it is compacted, what is written to external memory, and which tools are even visible on a given turn. Anthropic's advice is to find "the smallest possible set of high-signal tokens" that maximizes the likelihood of the outcome you want.

In practice, that means loading tool definitions just in time instead of declaring every tool every turn, writing intermediate state to files or a store instead of carrying it in the transcript, compacting on a threshold rather than waiting for an error, and giving retrieved content a hard token cap.

Enforcing token budgets in production

Two limits get conflated. The context window is a per-request ceiling enforced by the model. Token rate limits are enforced by the provider at the organization level, per model class (Anthropic splits them into requests, input tokens, and output tokens per minute, per its rate limits docs), and at scale they can bind before the window does, because a handful of long-context requests can exhaust a quota that thousands of short requests would not.

A gateway is a natural enforcement point, since it sees every request before it reaches a provider and records token usage from each response (Budget and Limits). Bifrost lets you set budgets and token and request rate limits per model, scoped globally or to a single virtual key (Model Limits). It also layers budgets and rate limits across provider configs, virtual keys, teams, and customers (Budget and Limits). That way one team's long-context workload hits its own cap rather than draining a shared provider quota. These limits reset per configured period, and the worked example in the Budget and Limits docs shows a request admitted with budget remaining pushing usage past the cap, after which further requests are blocked.

Key takeaways

  • max_tokens bounds output only; setting it so input plus max_tokens exceeds the window causes rejected requests or truncated responses.
  • Attention compute scales quadratically while KV cache memory scales linearly, so long context degrades time to first token and concurrency together.
  • Conversation history is re-sent and re-billed every turn, so compaction and retrieval cut cost as well as freeing capacity.

Sources and further reading