AnyLearn
All lessons
AIintermediate

Context windows: tokens, limits, and "lost in the middle"

What the context window actually is, why 1M-token marketing doesn't mean what you think, the cost and accuracy curves that bend as you stuff more in, and the strategies (compaction, caching, retrieval) that keep long-context apps sane.

Not signed in โ€” your progress and quiz score won't be saved.
Lesson progress1 / 8

What the context window actually is

The context window is the maximum number of tokens the model can see in a single forward pass โ€” input tokens plus the tokens it generates. Beyond that limit, the model literally cannot attend to your text; it doesn't exist as far as the math is concerned.

A token isn't a word. In English, 1 token โ‰ˆ 0.75 words. "Hello, world!" is 3 tokens. A 1,000-word essay is ~1,300 tokens. Code, JSON, and non-Latin scripts tokenize less efficiently โ€” JSON often runs 1 token per 2โ€“3 characters because of all the structural punctuation.

For sizing prompts in your head: ~750 words โ‰ˆ 1K tokens, a typical novel โ‰ˆ 100K tokens.

Full lesson text

All 8 steps on one page โ€” for reading, reference, and search.

Show

1. What the context window actually is

The context window is the maximum number of tokens the model can see in a single forward pass โ€” input tokens plus the tokens it generates. Beyond that limit, the model literally cannot attend to your text; it doesn't exist as far as the math is concerned.

A token isn't a word. In English, 1 token โ‰ˆ 0.75 words. "Hello, world!" is 3 tokens. A 1,000-word essay is ~1,300 tokens. Code, JSON, and non-Latin scripts tokenize less efficiently โ€” JSON often runs 1 token per 2โ€“3 characters because of all the structural punctuation.

For sizing prompts in your head: ~750 words โ‰ˆ 1K tokens, a typical novel โ‰ˆ 100K tokens.

2. What "1M context" actually means

Vendors advertise increasingly large windows: 200K, 1M, even 2M tokens. Three important caveats:

  1. The limit is a cap, not a sweet spot. Most models degrade in accuracy well before the advertised maximum. "Supports 1M" โ‰  "performs well at 1M".
  2. Cost scales linearly. A 200K-token prompt costs 200x a 1K prompt. A few of these blow your budget fast.
  3. Latency scales worse than linearly. First-token latency on a 200K input is often 5โ€“15 seconds before the model even starts generating. Attention is roughly O(n2)O(n^2) in sequence length.

Use big windows when the task needs the full content. For most uses, smaller + retrieval beats stuffing-everything-in.

3. Lost in the middle

A well-documented phenomenon: when relevant information sits in the middle of a long context, models retrieve it less accurately than if the same information is at the start or end.

In practice this means:

  • Put critical instructions at the top of the prompt.
  • Put critical retrieval results at the end, just before the user question.
  • If you have to cite many documents, rank them โ€” the most relevant should be first or last, not buried.

The effect varies by model (newer frontier models are noticeably better) but doesn't disappear. Even with 1M tokens of capacity, an attention pattern that overweights start/end is the prior.

4. Where attention concentrates in a long prompt

Recall is highest at the ends, weakest in the middle.

flowchart LR
  Start["Start: high recall"] --> Middle["Middle: weakest recall"]
  Middle --> End["End: high recall"]
  End --> Out["Generated answer"]

5. KV cache and prefix caching

Behind the scenes, models cache the keys and values from attention layers as they process tokens. This KV cache is what makes the second token cheaper than the first.

At the API level, vendors expose prefix caching (Anthropic) or prompt caching (others). If two requests share the same prefix โ€” system prompt + tool definitions + few-shot examples โ€” the model reuses cached computation.

Typical wins:

  • 5โ€“10x input cost reduction on the cached portion
  • 30โ€“50% first-token latency improvement
  • Cache lives for several minutes; identical-prefix requests within that window hit

Design prompts with caching in mind: stable system prompt โ†’ stable tool defs โ†’ stable examples โ†’ varying user input at the end.

6. Compaction: keeping the window from filling

In long-running agents, the conversation history grows every turn. Three strategies to keep it bounded:

  1. Sliding window: only include the last N turns. Loses old context but is dead simple.
  2. Summarisation: when context grows past a threshold, ask the model to summarise the early part and replace it with the summary. Saves space; introduces drift.
  3. Retrieval-over-history: store the conversation in a vector DB, retrieve only relevant chunks for each new turn. Most expensive to implement; preserves the most signal.

Claude Code, ChatGPT's long-conversation handling, and Cursor's agent mode all use variants of (2) โ€” auto-compaction. The art is detecting which parts of history are still load-bearing.

7. When to retrieve instead of stuffing

If your context need is "answer questions over a 500-page manual", you have a choice:

  • Stuff it all in: feed the whole manual on every call. Works in a 1M-token window. Costs roughly 200K tokens ร— $price per call.
  • Retrieve: embed once, retrieve top-k relevant chunks per question. Costs ~3K tokens per call.

For 100 questions, retrieval is ~100x cheaper and often more accurate (the model isn't distracted by 199,500 irrelevant tokens).

Long context wins when the task needs holistic understanding โ€” "summarise the whole document", "find inconsistencies across chapters". Retrieval wins for lookup-shaped questions, which is the vast majority of real-world Q&A.

8. Estimating tokens before you send

Don't guess. Estimate.

import anthropic
client = anthropic.Anthropic()

result = client.messages.count_tokens(
    model="claude-opus-4-7",
    messages=[{"role": "user", "content": long_doc_here}],
)
print(result.input_tokens)

Most providers expose a count_tokens or equivalent. Use it before sending anything large โ€” it's free and prevents "oh, that was 180K tokens" surprises.

For rough mental math: copy your input into the OpenAI tokenizer or [Anthropic's playground]. Tokenizers vary slightly between models but counts are within ~10% across the frontier.

Check your understanding

The lesson ends with a 5-question quiz. Take it in the player above to see your score.

  1. Roughly how many tokens are in a 1,000-word English document?
    • About 300
    • About 750
    • About 1,300
    • About 4,000
  2. A vendor markets a 1M-token context window. What's the most accurate framing?
    • The model performs equally well at all input sizes up to 1M
    • 1M is a hard cap; quality, cost, and latency all degrade well before reaching it
    • Anything past 200K is technically impossible
    • Latency is constant regardless of input size
  3. You have 10 RAG-retrieved documents to include in a prompt. Where should you put them for best recall?
    • Sort by length, longest first
    • Random order โ€” modern models attend uniformly
    • Rank by relevance and place the most relevant near the start or end of the prompt
    • Always put them in the middle so the model focuses on instructions at the edges
  4. Your system prompt + tool definitions + few-shot examples never change between calls. What's the obvious optimisation?
    • Compress them into shorter text
    • Use prefix / prompt caching so the stable portion isn't reprocessed
    • Move them after the user's question
    • Switch to a smaller model
  5. You're answering many lookup-shaped questions over a 500-page manual. The model supports 1M-token context. What's usually the better architecture?
    • Send the entire manual on every call to maximise context
    • Retrieve top-k relevant chunks per question, send only those
    • Train a custom model on the manual
    • Summarise the manual once and only send the summary

Related lessons

AI
intermediate

LLM Inference Internals: KV Cache, Sampling, and Serving at Scale

A deep dive into how large language models actually run in production โ€” why prefill is fast and decode is slow, how the KV cache works, sampling strategies like temperature and top-p, speculative decoding, and continuous batching with vLLM.

12 stepsยท~18 minยทaudio
AI
intermediate

Comparing LLM Capabilities: Reasoning, Code, Math, Multimodal

A capability-by-capability tour of frontier LLMs in 2026 โ€” which models are strong at reasoning, code, math, long-context, multilingual, multimodal, and tool use, with hedged comparisons instead of point-estimate benchmark wars.

11 stepsยท~17 minยทaudio
AI
advanced

Loop engineering: verification, orchestration, and anti-patterns

Make loops trustworthy. Adversarial verification panels, sub-agent orchestration, loop-until-dry for unbounded discovery, loop-until-budget for paid depth, multi-modal sweeps with diverse prompts, eval-driven cap selection, and the five anti-patterns โ€” silent caps, infinite plans, drift, premature termination, thrashing โ€” that ship to prod more than they should.

9 stepsยท~14 min
AI
intermediate

Loop engineering in production: state, errors, and budgets

Once an agent loop runs past a few iterations the failure surface shifts: state bloats, tool calls fail in three distinct ways, retries multiply if you stack them wrong, and unbounded budgets rack up four-figure bills overnight. The state, errors, and budgets you need to make the loop survive contact with reality.

8 stepsยท~12 min