02.7 Context Windows

Understand LLMsLesson 7 of 1019,432 words10 parts
Module 02 · 0 of 9 lessons done
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10

Every request you send to an LLM has to fit inside a fixed-size space called the context window: the system prompt, the conversation so far, the documents you attach, the tool definitions, the model's hidden reasoning and the answer it writes, all counted in tokens. The window is the model's entire world for that one request. The model remembers nothing between requests, it gets slower and more expensive as the window fills, and it gets worse at using information as the window grows. This lesson explains what fills the window, how big windows really are, how to manage conversation history, why long contexts degrade, what they cost, and how caching and retrieval change the picture.

What you'll learn

  • What a context window is, and everything that consumes it: system prompt, history, tools, tool results, documents, images, reasoning tokens and the output
  • Current context-window and output limits for OpenAI, Anthropic, Gemini and open models, how to look them up in code, and what each provider does when you exceed them
  • Why the model is stateless, proved with a local model, and what "server-side conversation state" features really do
  • How to manage conversation history: truncation, sliding windows, summarization and compaction, pinning facts, and token budgeting, with a runnable history manager
  • How quality degrades with length: "lost in the middle", context rot, needle-in-a-haystack tests and why they flatter models, and how to order content
  • Why long chats get expensive and slow, with a runnable cost calculator and a prefill-latency measurement
  • How the KV cache and provider prompt caching make repeated prefixes cheaper and faster, and how to design prompts that hit the cache
  • When to put everything in the context and when to retrieve (RAG), and why "memory" features are application code
  • Why context limits exist at all, how context extension works, and the gap between advertised and effective context length

What you don't need

  • The maths of attention. Lesson 04 explains the mechanism; here we only need its consequences.
  • API keys for most of the lesson. The local demos run free on a laptop CPU. Provider samples are included for all four providers, so you can run them when you have keys.

Setup

The local demos need Python 3.11+:

bash
uv add tiktoken httpx torch transformers        # or: pip install tiktoken httpx torch transformers

First time? Create a project with uv init llm-basics && cd llm-basics, then run scripts with uv run python file.py. The outputs in this lesson were produced with PyTorch 2.15.0 and Transformers 5.22.1. Transformers 5.x is a recent major version, so a newer major release may rename things again; if a sample fails after an upgrade, check its changelog.

The first run of the Qwen demos downloads Qwen/Qwen2.5-0.5B-Instruct (about 1 GB) from Hugging Face. It runs on a CPU. The catalogue lookup in 2.5 uses httpx for HTTP (it is in the first uv add line above).

The provider samples need the official SDKs and your API keys in a .env file:

bash
uv add openai anthropic google-genai python-dotenv
# or, without uv: pip install openai anthropic google-genai python-dotenv

The provider samples were checked against openai 3.x, anthropic 2.x and google-genai 2.x as of November 2026 (Module 03 gives the exact releases). An unversioned install gives you the newest release, and google-genai 3.x changes its default Gemini API version and HTTP library (03.1, 4.5), so if a sample does not match, check the SDK's changelog.

bash
# .env  (never commit this file)
OPENAI_API_KEY=...
ANTHROPIC_API_KEY=...
GEMINI_API_KEY=...
OPENROUTER_API_KEY=...

What you must be able to do after this lesson#

  • Explain what the context window holds
  • Explain why the model remembers nothing between calls
  • Manage conversation history within a token budget
  • Explain why a bigger context does not mean better recall
  • Estimate the cost and latency of long contexts
  • Decide between long context and RAG

Why this matters for an AI engineer#

The context window shapes almost every design decision in an LLM product: what you can send, what it costs, how fast it answers and how well it answers.

You'll hear... You'll understand it after...
"This model has a 1M-token context window." 1.1 What a context window is and Part 2
"Our tool definitions alone eat 15K tokens." 1.3 Everything that consumes the window
"The reply got cut off mid-sentence." 2.6 What happens when you exceed a limit
"Why doesn't the bot remember what I said yesterday?" Part 3: The model remembers nothing
"Just use previous_response_id, then the API remembers." 3.5 Server-side conversation state
"Long chats start forgetting the early instructions." Part 4: Managing conversation history and Part 5
"The model ignored the fact buried in the middle of the document." 5.1 Lost in the middle
"It scores 99% on needle-in-a-haystack, so long context is solved." 5.3 Needle-in-a-haystack tests
"Our bill tripled when users started having long chats." Part 6: Cost and latency
"Turn on prompt caching, it's 90% cheaper." Part 7: KV cache and prompt caching
"Do we need RAG if the model takes a million tokens?" Part 8: Long context vs RAG
"How does ChatGPT's memory feature work?" Part 9: Memory features are application code
"It says 10M tokens, but it falls apart after 100K." 10.2 Advertised vs effective context length

Part 1: What the context window is#

1.1 What a context window is#

The context window (also called context length or just context) is the maximum number of tokens a model can process in a single request, counting both the input you send and the output it generates. That's how most providers define it; a few, such as Gemini 2.5 and 3.x, publish separate input and output limits instead (1.2).

An analogy: think of the model as an expert who works at a desk with one sheet of paper of a fixed size. For every request, you write everything they need onto the sheet: the instructions, the background, the conversation so far, your question. They read the whole sheet, then write their answer on the same sheet, in the space that's left. When the request ends, the sheet is thrown away. The next request starts with a blank sheet of the same size.

Three consequences follow directly, and the rest of this lesson unpacks each one:

  1. Input and output share one budget. A long prompt leaves less room for the answer.
  2. Nothing carries over. If the expert needs to know something from an earlier request, it must be written on the new sheet again (Part 3).
  3. A bigger sheet isn't free. More text costs more, takes longer to read, and makes it harder to spot the important line (Parts 5 and 6).

1.2 Input and output share the window#

Every request must satisfy two limits at once:

text
input tokens + output tokens  ≤  context window
               output tokens  ≤  maximum output tokens (a separate, smaller cap)
  • Input tokens (also called prompt tokens) are everything you send.
  • Output tokens (also called completion tokens) are everything the model generates, including hidden reasoning.
  • The maximum output is a separate cap the provider sets per model, usually far smaller than the window (2.3). You choose how much of it to allow per request with a parameter such as max_tokens.

OpenAI's model pages show the arithmetic plainly. As of November 2026, gpt-6-luna lists a 1,050,000-token context window, a 128,000-token maximum output, and a 922,000-token maximum input. 1,050,000 − 128,000 = 922,000: the input limit is simply the window minus the room reserved for the largest possible answer.

Providers don't all define the numbers the same way. Google's token documentation says Gemini 3 and 2.5 models "use separate input (1,048,576 tokens) and output (65,536 tokens) budgets", while gemini-4-argon shares one 1,048,576-token window across input, thinking and output. Anthropic's max_input_tokens field holds the full window (2.5). Always read how a provider defines its limits before you write budgeting code.

1.3 Everything that consumes the window#

Beginners usually think of the context as "my prompt". In a real application, the prompt you type is often a small fraction of what's sent. Everything below counts:

What Where it comes from Typical size Notes
System prompt You (the developer) 200–5,000 tokens; agent prompts 10,000+ Sent on every request
Tool definitions You: names, descriptions and JSON schemas of each tool 100–1,000 tokens per tool 30 tools can cost 10,000+ tokens per request before anyone says anything (Module 08A)
Conversation history Earlier user and assistant turns Grows every turn The model only "remembers" what you re-send (Part 3)
Tool calls and tool results The model's requests, and the data your code returns A search result or file read can be 1,000–50,000 tokens The fastest-growing item in agents. Each result goes back in as a new message, so it costs input tokens on every later request (lesson 05, 4.7)
Retrieved documents RAG: chunks fetched from your knowledge base 2,000–50,000 tokens You choose how many (Module 07)
Files, images, audio, video User uploads Images: hundreds to a few thousand tokens each; PDFs: hundreds per page; audio and video: tokens per second Media is converted into tokens too (see below)
Reasoning (thinking) tokens Generated by reasoning models before the answer Hundreds to tens of thousands Count as output and against the output cap; whether old reasoning stays in later turns depends on the provider (lesson 08)
The output itself The model's answer A few to 128,000 tokens Must fit in what's left
Hidden formatting The provider's chat template, role markers, and text some providers inject (for example tool-use instructions) A few tokens per message, sometimes hundreds per request You pay for it but rarely see it (1.4)

Media is not free. As examples from Google's Gemini documentation (as of November 2026): on Gemini 3 and later models an image costs 1,120 tokens at the default media_resolution and a PDF page 560 tokens, while older Gemini models charged 258 tokens per image tile, and about 263 tokens per second of video. For audio, Google's pages give 25 or 32 tokens per second and disagree with each other (lesson 02, Part 11), so one hour of audio is roughly 90,000 to 115,200 tokens; measure it with count_tokens. Other providers use their own formulas, so always check the provider's vision and audio documentation.

Here is a single request's budget as a picture:

flowchart LR
    subgraph win ["One request's context window (e.g. 1,000,000 tokens)"]
        direction TB
        subgraph inp ["Input: everything you send"]
            direction TB
            S["System prompt<br/>(instructions, persona, rules)"]
            T["Tool definitions<br/>(names, descriptions, JSON schemas)"]
            D["Retrieved documents, files,<br/>images, audio, PDFs"]
            H["Conversation history<br/>(earlier user and assistant turns,<br/>tool calls and tool results)"]
            U["The new user message"]
        end
        subgraph outp ["Output: everything the model generates"]
            direction TB
            R["Reasoning / thinking tokens<br/>(hidden or summarized)"]
            A["The visible answer<br/>(text or tool calls)"]
        end
        F["Free space<br/>(unused this request)"]
    end
    S --> T --> D --> H --> U --> R --> A --> F

1.4 Try it: see the hidden tokens#

Chat models don't read your list of messages directly. Each message is wrapped in special marker tokens by a chat template and joined into one long sequence. Let's look at what a small open model actually receives, and read its context window from its configuration file:

python
from transformers import AutoConfig, AutoTokenizer

MODEL = "Qwen/Qwen2.5-0.5B-Instruct"
tokenizer = AutoTokenizer.from_pretrained(MODEL)
config = AutoConfig.from_pretrained(MODEL)
print("Context window (max_position_embeddings):", config.max_position_embeddings)

messages = [
    {"role": "system", "content": "You are a helpful assistant."},
    {"role": "user", "content": "What is the capital of France?"},
    {"role": "assistant", "content": "Paris."},
    {"role": "user", "content": "And of Japan?"},
]

# What the model actually reads: the messages wrapped in its chat template
prompt = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
print(prompt)

text_only = sum(len(tokenizer.encode(m["content"])) for m in messages)
with_template = len(tokenizer.encode(prompt))
print("Tokens in the message texts alone:", text_only)
print("Tokens the model actually receives:", with_template)
print("Template overhead:", with_template - text_only, "tokens")
Output14 lines
Context window (max_position_embeddings): 32768
<|im_start|>system
You are a helpful assistant.<|im_end|>
<|im_start|>user
What is the capital of France?<|im_end|>
<|im_start|>assistant
Paris.<|im_end|>
<|im_start|>user
And of Japan?<|im_end|>
<|im_start|>assistant

Tokens in the message texts alone: 19
Tokens the model actually receives: 42
Template overhead: 23 tokens

What this shows:

  • The whole conversation is one flat sequence of tokens. "Messages" and "roles" are a convention, marked with special tokens such as <|im_start|> and <|im_end|>. The model sees one long text and predicts what comes after the final <|im_start|>assistant.
  • Formatting costs tokens. Here the template more than doubled the count (19 → 42). In real prompts the overhead is a few tokens per message, which is small relative to long content but adds up over hundreds of messages.
  • The context window is a property of the model. For this open model it's in config.json as max_position_embeddings: 32,768 tokens. Hosted APIs publish the number in their documentation and model endpoints (2.5).

1.5 Context vs training data vs memory#

Three different things get called "what the model knows". Keeping them apart prevents many design mistakes:

Weights (training data) Context window Application memory
What it is Knowledge baked into the parameters during training (lesson 01) The tokens sent in this one request Data your app stores (database, files, vector store)
Lifetime Fixed until the next model version One request As long as you keep it
Size Trillions of training tokens, compressed lossily Thousands to about a million tokens Unlimited
How precise Fuzzy; can be wrong or out of date (knowledge cutoff) Exact text the model can quote Exact, but only useful if you put it into the context
Who controls it The model provider You, per request You

Analogy: the weights are what a professional learned in years of study, the context window is the folder on their desk for today's meeting, and application memory is the filing cabinet down the hall. Information in the filing cabinet helps only if someone fetches it and puts it in the folder. Most of applied AI engineering is deciding what goes into the folder for each request, which is what Module 04 calls context engineering.


Part 2: Sizes and limits#

2.1 Representative limits as of November 2026#

Context windows change with almost every model release, so treat this table as a snapshot and learn how to check the current values (2.5). Every row was re-checked against the providers' own model pages in November 2026.

Provider Model ID Context window (input limit for Gemini 3.x) Max output Source and notes
OpenAI gpt-6-astra (flagship) 1,050,000 128,000 Max input 922,000. OpenAI model page
OpenAI gpt-6.1-sol (balanced) 1,050,000 128,000 Max input 922,000
OpenAI gpt-6.1-terra (fast) 1,050,000 128,000 Max input 922,000
OpenAI gpt-6-luna (cheapest) 1,050,000 128,000 Max input 922,000
OpenAI gpt-5.4-mini (previous generation) 400,000 128,000 Max input 272,000
Anthropic claude-fable-5-2 (top tier, above Opus) 1,000,000 128,000 Anthropic models overview. The legacy claude-fable-5-1 has the same limits
Anthropic claude-opus-5-5 1,000,000 128,000
Anthropic claude-sonnet-5-5 1,000,000 128,000
Anthropic claude-haiku-5-5 1,000,000 128,000 Prompts over 100,000 tokens cost more (2.7)
Anthropic claude-haiku-4-5 (previous generation) 200,000 64,000
Google gemini-3.1-pro-preview 1,048,576 65,536 Gemini models page
Google gemini-3.8-flash 1,048,576 65,536
Google gemini-3.5-flash-lite 1,048,576 65,536 Gemini 3.x: separate input and output budgets
Google gemini-4-carbon (strongest Gemini 4 model, generally available since 10 November 2026) 1,000,000 as listed 65K by default, up to 1M as listed Gemini models page lists it like Argon (the exact token counts and the non-streaming limit aren't stated there; check the model page before relying on them)
Google gemini-4-argon (efficient frontier model) 1,048,576 shared by input, thinking and output 65,536 per request by default; up to the full 1,048,576-token window with long decode (2.3) Gemini 4 Argon model page; long decode splits one answer across several hops and can take minutes
Open weights openai/gpt-oss-120b 131,072 up to 131,072 OpenAI model page
Open weights meta-llama/Llama-4-Scout 10,000,000 claimed depends on host Meta's launch post; trained at 256K; OpenRouter's host serves 1,310,720 (10.2)
Open weights Qwen/Qwen2.5-0.5B-Instruct 32,768 — Its config.json (1.4)

Three patterns worth noticing:

  • One million tokens is now the standard size for frontier models. The differences between providers are in the output cap, pricing above certain lengths, and how well the model actually uses that much context (Part 5).
  • Output caps vary more than windows. 65,536 on Gemini against 128,000 on current OpenAI and Anthropic models.
  • Open-weight models have two numbers: what the model was built for, and what a given host chooses to serve. A host may cap the window lower to save GPU memory (7.1).

2.2 How big is a million tokens?#

Numbers this large are hard to picture. Rough English equivalents (these figures use about 0.75 words per token, typical of OpenAI's o200k_base tokenizer; current Claude tokenizers fit about 25% fewer words into the same tokens, roughly 35% more tokens for the same text than older Claude tokenizers and about 1.5× o200k_base; see lesson 02, 7.1):

Tokens Roughly Example
1,000 750 words A long email, or 1.5 pages
8,000 6,000 words A detailed technical blog post
32,000 24,000 words A short novella; the whole Qwen 0.5B window
128,000 96,000 words A 300-page book
200,000 150,000 words A long novel, or a mid-sized codebase's key files
1,000,000 750,000 words Ten novels, or a large codebase

Code, JSON, non-English text and numbers usually use more tokens per character, so these figures can shrink by half or more for such content (lesson 02).

2.3 The input limit vs the output limit#

Why is the output cap so much smaller than the window?

  • Generation is sequential. Input is read in one parallel pass (prefill), but output is produced one token at a time (lesson 05). 128,000 output tokens at 100 tokens per second takes over 20 minutes. Providers cap output partly to keep requests within sensible time limits.
  • Training data. Models are trained mostly on examples with modest answer lengths. Very long outputs tend to drift, repeat or lose coherence, so providers cap them at lengths the model handles well.
  • Reasoning tokens eat the output cap. On reasoning models, the hidden thinking counts as output. A 64,000 cap with 50,000 tokens of thinking leaves only 14,000 for the visible answer (lesson 08).

You set the per-request output budget with a parameter whose name differs by provider and API:

Provider / API Parameter Required?
OpenAI Responses API max_output_tokens (includes reasoning tokens) No
OpenAI Chat Completions max_completion_tokens (the older max_tokens is deprecated) No
Anthropic Messages API max_tokens Yes
Gemini generate_content max_output_tokens inside the config No
OpenRouter (Chat Completions format) max_tokens No

Very large output budgets usually require streaming. Anthropic's SDK, for example, refuses non-streaming requests with very large max_tokens values to avoid HTTP timeouts, so the 128,000-token caps in 2.1 are only usable with streaming (lesson 05).

2.4 Context windows of models you run yourself#

For an open-weight model, the window is set by how it was trained (10.1), and recorded in its config (max_position_embeddings or a similar field). But the window you get also depends on your serving setup:

  • Inference servers such as vLLM, llama.cpp and Ollama often default to a smaller window than the model supports, because the KV cache (the memory the model uses to store its working state for every token in the context, 7.1) for a long window needs a lot of GPU memory (7.1). Ollama, for example, uses a modest default that you raise with its context-length setting.
  • Some model cards say "supports 128K with RoPE scaling enabled", meaning the long window only works if you turn on a configuration option (10.1).
  • Running past the trained length doesn't always raise an error. Quality can just collapse into gibberish.

You'll configure these settings when you self-host in Module 11C.

2.5 Checking limits in code#

Hard-coding limits goes stale. Look them up.

OpenRouter publishes a model list with context lengths and prices for hundreds of models from every major provider. It's readable without an API key (OpenRouter's reference docs mark the endpoint as authenticated, but in practice it answers without a key):

python
import httpx

# OpenRouter's model list is readable without an API key
resp = httpx.get("https://openrouter.ai/api/v1/models", timeout=60)
resp.raise_for_status()
models = {m["id"]: m for m in resp.json()["data"]}
print(f"{len(models)} models listed\n")

WANTED = [
    "openai/gpt-6-astra", "openai/gpt-6-luna",
    "anthropic/claude-opus-5.5", "anthropic/claude-haiku-5.5",
    "google/gemini-3.1-pro-preview", "google/gemini-3.8-flash",
    "deepseek/deepseek-v4.1-flash", "qwen/qwen3.8-flash", "meta-llama/llama-4-maverick",
]
print(f"{'model':32s} {'context':>10s} {'max output':>11s} {'$ in/M':>7s} {'$ out/M':>8s}")
for model_id in WANTED:
    m = models.get(model_id)
    if m is None:
        print(f"{model_id:32s} (not listed)")
        continue
    price = m["pricing"]                                  # strings, in USD per token
    print(f"{model_id:32s} {m['context_length']:>10,} "
          f"{m['top_provider']['max_completion_tokens'] or 0:>11,} "
          f"{float(price['prompt']) * 1e6:>7.2f} {float(price['completion']) * 1e6:>8.2f}")

The figures below were read from OpenRouter's public model list on 3 November 2026; your numbers will reflect the day you run it.

Example output · illustrative12 lines
451 models listed

model                               context  max output  $ in/M  $ out/M
openai/gpt-6-astra                1,050,000     128,000   10.00    50.00
openai/gpt-6-luna                 1,050,000     128,000    0.10     0.50
anthropic/claude-opus-5.5         1,000,000     128,000    4.00    20.00
anthropic/claude-haiku-5.5        1,000,000     128,000    0.10     0.50
google/gemini-3.1-pro-preview     1,048,576      65,536    2.00    12.00
google/gemini-3.8-flash           1,048,576      65,536    0.83     4.12
deepseek/deepseek-v4.1-flash      1,048,576     943,718    0.04     0.50
qwen/qwen3.8-flash                1,000,000     131,072    0.15     0.47
meta-llama/llama-4-maverick         524,288      16,384    0.19     0.65

Things to notice:

  • Prices are strings in US dollars per token. Multiply by 1,000,000 to get the familiar "per million tokens" figure.
  • context_length vs top_provider. OpenRouter routes each model to one of several hosting providers. top_provider.max_completion_tokens is the output cap of the preferred host, and OpenRouter notes that it's "a ceiling for max_tokens, not a guaranteed output size". Open models like DeepSeek and Llama can show very different numbers from one host to another.
  • Aggregator data can differ from the provider's own. Google's pricing page lists gemini-3.8-flash at $0.75 input and $3.75 output per million tokens (a dated introductory price that Google has announced will double on 1 January 2027, see lesson 09, 6.8); OpenRouter's listing shows a different figure. For decisions that matter, confirm against the provider's own page.

Each provider's own SDK can also report limits:

python
from dotenv import load_dotenv
import anthropic
from google import genai

load_dotenv()

# Anthropic: the Models API reports the context window and the output cap
claude = anthropic.Anthropic()
info = claude.models.retrieve("claude-haiku-5-5")
print("Claude Haiku 5.5:", info.max_input_tokens, "input |", info.max_tokens, "output")

# Gemini: models.get reports input and output token limits
gemini = genai.Client()
model = gemini.models.get(model="gemini-3.8-flash")
print("Gemini 3.8 Flash:", model.input_token_limit, "input |", model.output_token_limit, "output")

# OpenAI: client.models.list() has no context-window field; use the model's docs page
Example output · illustrative2 lines
Claude Haiku 5.5: 1000000 input | 128000 output
Gemini 3.8 Flash: 1048576 input | 65536 output
Provider Where to find limits in code Field names
OpenAI Not available from client.models.list() (it returns only id, created, owned_by and similar). Use the model's page in the OpenAI docs —
Anthropic client.models.retrieve(id) or client.models.list() max_input_tokens (the window), max_tokens (output cap)
Gemini client.models.get(model=...) input_token_limit, output_token_limit
OpenRouter GET https://openrouter.ai/api/v1/models context_length, top_provider.max_completion_tokens
Self-hosted open model The model's config.json, and your inference server's settings max_position_embeddings (name varies by architecture)

2.6 What happens when you exceed a limit#

There are three different ways to run out of room, and providers handle them differently:

  1. The input alone is too long for the window.
  2. Input + requested output is longer than the window, even though the input fits.
  3. The output reaches the output cap (your max_tokens) before the model is finished.

As of November 2026:

Provider Input too long Input fits, but input + max_tokens > window Output hits the cap
OpenAI Responses API With truncation="disabled" (the default): HTTP 400 error. The older truncation="auto" option silently drops items from the beginning of the conversation to make it fit, but as of November 2026 OpenAI's API reference marks the truncation parameter deprecated, so don't build on it Accepted if the input fits; if generation then fills the window, the response ends "incomplete" with reason max_output_tokens, as in the next column Response status is "incomplete" with incomplete_details.reason = "max_output_tokens"; this can happen during reasoning, before any visible text, and you still pay
OpenAI Chat Completions HTTP 400 error HTTP 400 error finish_reason = "length"
Anthropic Messages API HTTP 400 invalid_request_error ("prompt is too long") on every model On Claude 4.5 and newer models the request is accepted; if generation reaches the window limit it stops with stop_reason = "model_context_window_exceeded". Older models return a validation error stop_reason = "max_tokens"
Gemini API HTTP 400 error (the exact message isn't specified in Google's error reference) Can't happen on Gemini 2.5/3.x (separate input and output budgets). On Gemini 4's shared window, Google's docs don't describe this case separately; expect generation to stop with MAX_TOKENS finish_reason = MAX_TOKENS
OpenRouter An error suggesting you shorten the input or enable context compression. Endpoints with 8,192 tokens of context or less have compression on by default, which removes messages from the middle of the conversation Depends on the underlying provider Passed through as finish_reason = "length"
Self-hosted model Depends on the server: an error, silent truncation of the prompt by the tokenizer, or garbage output past the trained length — Generation stops at the limit you configured

OpenAI's Chat Completions reference and error-code guide don't spell out the two overflow cases, so the two Chat Completions cells above are what to expect, not a documented contract: send an oversized request to your own model once to see the exact error.

Two of these behaviours silently change what the model sees, and both deserve a warning:

What to do when a response hits the output cap:

  • Raise the cap (max_tokens or its equivalent) if the task legitimately needs more room, using streaming for large values (2.3).
  • Split the task: ask for one section at a time, or for an outline first and then each part.
  • Continue in a new turn: append the partial answer to the history as the assistant's turn, then send a new user message such as "Continue exactly where you stopped." Don't rely on the older trick of assistant prefill (sending an unfinished assistant message for the model to complete; not the prefill phase of 6.3): current Claude models reject it with a 400 error, and so do Gemini 3.6 Flash, 3.5 Flash-Lite and later (lesson 05, 4.6).
  • For structured output, retry rather than stitch. Half a JSON object glued to the other half is fragile; re-run with a larger cap or a smaller request.

Here is how the error cases look in code (the exception classes come from each official SDK):

python
from dotenv import load_dotenv
from openai import OpenAI, BadRequestError
import anthropic

load_dotenv()
huge = "lorem ipsum " * 1_000_000          # ~2M tokens (~12 MB): over every window, under request-size limits

# OpenAI Responses API: truncation="disabled" (the default) fails with a 400 ...
client = OpenAI()
try:
    client.responses.create(model="gpt-6-luna", input=huge)
except BadRequestError as e:
    print("OpenAI 400:", e.message[:80])

# ... the deprecated truncation="auto" silently drops the OLDEST conversation items instead
# (shown only to explain the behaviour; don't use it in new code)
# client.responses.create(model="gpt-6-luna", input=history, truncation="auto")

# Anthropic: input over the window is a 400 "prompt is too long"
claude = anthropic.Anthropic()
try:
    claude.messages.create(model="claude-haiku-5-5", max_tokens=1024,
                           messages=[{"role": "user", "content": huge}])
except anthropic.BadRequestError as e:
    print("Anthropic 400:", e.message[:80])
except anthropic.RequestTooLargeError as e:   # 413: a request over the endpoint's byte limit fails on size before tokens are counted
    print("Anthropic 413:", e.message[:80])

# Output limits are NOT errors: check why generation stopped
response = claude.messages.create(model="claude-haiku-5-5", max_tokens=50,
                                  messages=[{"role": "user", "content": "Write a long essay."}])
print("stop_reason:", response.stop_reason)   # "max_tokens" -> the reply was cut off
Example output · illustrative3 lines
OpenAI 400: Your input exceeds the context window of this model. Please adjust your input and try again.
Anthropic 400: prompt is too long: 2000012 tokens > 1000000 maximum
stop_reason: max_tokens

2.7 Long-context pricing tiers#

A large window doesn't mean every token in it costs the same. Some models switch to higher rates for the whole request once a prompt passes a threshold: as of November 2026, for example, OpenAI's GPT-6 models above 272K input tokens and Claude Haiku 5.5 above 100K. So a request that grows from 270,000 to 280,000 tokens on such a model can cost far more than 4% extra. Build these tiers into any cost estimate (Part 6). Lesson 09, 6.6 lists the current tiers for each provider (including how OpenRouter reports them), and lesson 09, Part 6 covers pricing structures in general.


Part 3: The model remembers nothing#

3.1 Every request starts from zero#

A model's weights are frozen while you use it (lesson 01, 7.2, an optional lesson). The other half of the story is that the model also keeps no state between requests. Each API call is a pure function: tokens in, tokens out. When the response is finished, nothing about your request stays inside the model. This property is called statelessness.

An analogy: a brilliant consultant with no memory at all. Every meeting, they greet you as a stranger. They can still help you brilliantly, if you hand them the complete case file at the start of each meeting: who you are, what was discussed before, what was decided. Chat applications work exactly like this. The case file is the conversation history, and your application must assemble and re-send it with every request.

3.2 Try it: prove it with a local model#

Let's prove statelessness on your own machine. We tell a small model our name in one call, then ask for it in a second, independent call, and finally ask again with the history re-sent:

python
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer

MODEL = "Qwen/Qwen2.5-0.5B-Instruct"
tokenizer = AutoTokenizer.from_pretrained(MODEL)
model = AutoModelForCausalLM.from_pretrained(MODEL, dtype=torch.float32)   # full precision: much faster than BF16 on most CPUs

def ask(messages):
    """One 'API call': the model sees ONLY the messages passed in right now."""
    prompt = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
    inputs = tokenizer(prompt, return_tensors="pt")
    output = model.generate(**inputs, max_new_tokens=40, do_sample=False)  # greedy: repeatable
    new_tokens = output[0][inputs["input_ids"].shape[1]:]
    return tokenizer.decode(new_tokens, skip_special_tokens=True).strip()

system = {"role": "system", "content": "You are a helpful assistant. Answer in one short sentence."}

# Call 1: tell the model a fact
turn1 = [system, {"role": "user", "content": "Hi! My name is Priya and I live in Chennai."}]
reply1 = ask(turn1)
print("Call 1 reply:", reply1)

# Call 2: a brand-new request WITHOUT the earlier messages
print("Call 2 (no history):", ask([system, {"role": "user", "content": "What is my name?"}]))

# Call 3: the same question, but WE re-send the whole conversation
history = turn1 + [
    {"role": "assistant", "content": reply1},
    {"role": "user", "content": "What is my name?"},
]
print("Call 3 (history re-sent):", ask(history))
Output3 lines
Call 1 reply: Hello! My name is Priya, and I am from Chennai.
Call 2 (no history): I am an artificial intelligence designed to respond to your questions and provide information on various topics.
Call 3 (history re-sent): Your name is Priya.

What happened:

  • Call 1 is a small-model wobble. A 0.5B model easily mixes up who is who, and here it replies as if it were Priya. Ignore that; the experiment is about calls 2 and 3.
  • Call 2 failed even though it ran on the same model object, in the same Python process, a moment after call 1. Nothing from call 1 survived. The model had no way to know the name, so it described itself instead.
  • Call 3 succeeded only because we put the earlier messages back into the input.
  • do_sample=False (greedy decoding, lesson 05) makes the demo repeatable: the same input gives the same output, which also shows the model is a fixed function of its input.

Hosted APIs behave exactly like this local model. The only difference is that the computation happens on someone else's GPU.

3.3 How chat apps fake memory#

When you chat in ChatGPT, Claude or Gemini, the application stores your conversation and silently re-sends all of it (or a managed version of it, Part 4) with every new message:

sequenceDiagram
    participant User
    participant App as Your application
    participant LLM as Model API
    User->>App: "My name is Priya."
    App->>LLM: [system, user: "My name is Priya."]
    LLM-->>App: "Nice to meet you, Priya!"
    Note over LLM: Request finished.<br/>Nothing is kept.
    User->>App: "What is my name?"
    App->>LLM: [system, user: "My name is Priya.",<br/>assistant: "Nice to meet you, Priya!",<br/>user: "What is my name?"]
    LLM-->>App: "Your name is Priya."
    Note over App: The app stored the history<br/>and re-sent ALL of it.

This has three consequences you'll feel in production:

  1. Every turn is longer than the last. Turn 20 re-sends turns 1–19. That's why long chats get slower and more expensive (Part 6) and eventually hit the window (Part 4).
  2. You can edit the past. Because you send the history, you can change it: remove a message, fix a typo, summarize old turns, or insert facts. The model can't tell the difference between history that really happened and history you constructed. This is powerful (context engineering, Module 04) and dangerous (a user who controls the history can fake earlier turns, Module 12).
  3. The history is your data. You decide where it's stored, for how long, who can see it and when it's deleted.

3.4 Provider code: you re-send the history#

With every provider's standard API, your code keeps a list and sends all of it each turn. Here is the same tiny chat on all four providers:

python
import os
from dotenv import load_dotenv
from openai import OpenAI
import anthropic
from google import genai
from google.genai import types

load_dotenv()
SYSTEM = "You are a helpful assistant. Answer in one short sentence."

# --- OpenAI (Responses API): you keep the list and send all of it every time ---
openai_client = OpenAI()
openai_history = []

def chat_openai(text: str) -> str:
    openai_history.append({"role": "user", "content": text})
    response = openai_client.responses.create(
        model="gpt-6-luna", instructions=SYSTEM, input=openai_history, store=False)
    # simplest form; for reasoning models append response.output instead (see below)
    openai_history.append({"role": "assistant", "content": response.output_text})
    return response.output_text

# --- Anthropic: same idea; the system prompt is a separate parameter ---
claude = anthropic.Anthropic()
claude_history = []

def chat_claude(text: str) -> str:
    claude_history.append({"role": "user", "content": text})
    response = claude.messages.create(
        model="claude-haiku-5-5", max_tokens=1024, system=SYSTEM, messages=claude_history)
    claude_history.append({"role": "assistant", "content": response.content})  # keep every block
    return next((block.text for block in response.content if block.type == "text"), "")

# --- Gemini: history is a list of Content objects ---
gemini = genai.Client()
gemini_history = []

def chat_gemini(text: str) -> str:
    gemini_history.append(types.Content(role="user", parts=[types.Part(text=text)]))
    response = gemini.models.generate_content(
        model="gemini-3.8-flash", contents=gemini_history,
        config=types.GenerateContentConfig(system_instruction=SYSTEM))
    gemini_history.append(response.candidates[0].content)
    return response.text

# --- OpenRouter: OpenAI-compatible Chat Completions, also stateless ---
router = OpenAI(base_url="https://openrouter.ai/api/v1", api_key=os.environ["OPENROUTER_API_KEY"])
router_history = [{"role": "system", "content": SYSTEM}]

def chat_openrouter(text: str) -> str:
    router_history.append({"role": "user", "content": text})
    response = router.chat.completions.create(model="anthropic/claude-haiku-5.5", messages=router_history)
    reply = response.choices[0].message.content
    router_history.append({"role": "assistant", "content": reply})
    return reply

for chat in (chat_openai, chat_claude, chat_gemini, chat_openrouter):
    chat("My name is Priya.")
    print(f"{chat.__name__:16s}", chat("What is my name?"))
Example output · illustrative4 lines
chat_openai      Your name is Priya.
chat_claude      Your name is Priya.
chat_gemini      Your name is Priya.
chat_openrouter  Your name is Priya.

Details worth noticing:

  • Each provider shapes the request differently. OpenAI's Responses API takes instructions plus an input list; Anthropic takes a separate system parameter plus messages; Gemini takes contents plus a system_instruction in the config; OpenRouter uses the Chat Completions format with a system message in the list. Module 03 covers these APIs in depth.
  • Append the assistant's full reply. For Claude we append response.content (all content blocks), not just the text, because current Claude models return thinking blocks that the API expects back in later turns. (A thinking block is the part of a reasoning model's reply that holds its hidden or summarized reasoning, plus a signature you must send back unchanged; lesson 08, 3.2.) Gemini's response.candidates[0].content likewise preserves everything the model produced. For OpenAI reasoning models, the equivalent is passing back the response's output items (with store=False, the reasoning items come back with an encrypted_content field by default, so you pass them back as they are; the older include=["reasoning.encrypted_content"] value is legacy but still accepted, lesson 08, 3.1) rather than only output_text. Dropping parts of the reply can break reasoning continuity (lesson 08).
  • store=False on the OpenAI call asks OpenAI not to keep the response on its servers. In the Responses API, store defaults to true (3.5).
  • SDK chat helpers are the same thing. Gemini's SDK offers client.chats.create(...), which keeps this list for you inside a Python object. Google's docs are explicit that "the full conversation history is sent to the model with each follow-up turn", and its Interactions migration guide describes this as a "client-side chat helper". It's convenience, not memory.
  • Google labels generate_content as legacy and recommends the Interactions API for new projects (3.5). Both are stateless when you send the full history; we use generate_content here because it mirrors the other providers' message lists.

3.5 Server-side conversation state: what it really does#

Some providers now offer to store the conversation for you, so you send only the new message plus an ID:

Provider Feature How you use it Retention (as of November 2026)
OpenAI Responses API previous_response_id Pass the previous response's ID; the API retrieves the earlier turns Stored responses are kept at least 30 days by default (store defaults to true in the Responses API; OpenAI's reference says "at least 30 days, subject to the data retention exceptions")
OpenAI Conversations API client.conversations.create(), then pass conversation=conversation.id on each request (can't be combined with previous_response_id) Conversation items aren't subject to the 30-day limit
Gemini Interactions API (Google's recommended API for new projects since June 2026) Pass previous_interaction_id; requests are stored by default, opt out with store=False 55 days on the paid tier, 1 day on the free tier
Anthropic None by default: the Messages API is stateless. An opt-in message-threads beta (header message-threads-2026-08-12) can hold a conversation server-side Re-send the history, or, with the beta, send only the new messages (lesson 03.2, 7.7). Anthropic's separate Managed Agents product also runs server-side sessions for agents Beta threads are best-effort: they expire 5 minutes after the last request, are deleted within 1 hour of last use, and aren't eligible for zero data retention
OpenRouter None: stateless OpenRouter's Responses-compatible endpoint rejects store: true and previous_response_id with a 400 error —
flowchart LR
    subgraph client ["Client-managed (Chat Completions, Messages, generateContent)"]
        A1["Your app stores the history"] --> A2["Sends ALL of it<br/>each turn"]
    end
    subgraph server ["Server-managed (previous_response_id, conversations, interactions)"]
        B1["Your app sends only<br/>the new message + an ID"] --> B2["Provider looks up the stored history<br/>and feeds ALL of it to the model"]
    end
    A2 --> M["Model reads the full history<br/>(billed as input tokens)"]
    B2 --> M
python
from dotenv import load_dotenv
from openai import OpenAI
from google import genai

load_dotenv()

# --- OpenAI: chain responses with previous_response_id (needs store=True, the default) ---
client = OpenAI()
first = client.responses.create(model="gpt-6-luna", input="My name is Priya.")
second = client.responses.create(
    model="gpt-6-luna", previous_response_id=first.id, input="What is my name?")
print("OpenAI:", second.output_text)
print("  input tokens billed for turn 2:", second.usage.input_tokens)   # includes turn 1

# --- OpenAI: a long-lived Conversation object holds the items instead ---
conversation = client.conversations.create()
client.responses.create(model="gpt-6-luna", conversation=conversation.id, input="My name is Priya.")
reply = client.responses.create(model="gpt-6-luna", conversation=conversation.id, input="What is my name?")
print("OpenAI (conversation):", reply.output_text)

# --- Gemini: the Interactions API can chain turns on the server too ---
gemini = genai.Client()
turn1 = gemini.interactions.create(model="gemini-3.8-flash", input="My name is Priya.")
turn2 = gemini.interactions.create(
    model="gemini-3.8-flash", input="What is my name?", previous_interaction_id=turn1.id)
print("Gemini:", turn2.output_text)
Example output · illustrative4 lines
OpenAI: Your name is Priya.
  input tokens billed for turn 2: 31
OpenAI (conversation): Your name is Priya.
Gemini: Your name is Priya.

What these features really do: they move the storage of the history from your database to the provider's. They do not give the model memory. On every request, the provider looks up the stored turns, assembles the full history and runs the model over all of it, exactly as if you had sent it. So:

  • You still pay for the history on every turn. OpenAI's documentation says so in bold: "Even when using previous_response_id, all previous input tokens for responses in the chain are billed as input tokens in the API." Google's Interactions docs say chaining helps the system apply implicit caching to the history, which lowers the price of those repeated tokens (Part 7) but doesn't make them free.
  • The window still fills up. A chained conversation can exceed the context window just like a re-sent one. You still need a strategy: OpenAI's compaction feature (4.5) exists for exactly this reason (its older, now deprecated truncation parameter was another answer).
  • You give up control and portability. You can't easily edit or trim stored history, the history lives under the provider's retention rules, and switching providers means migrating conversations.

When are they worth it? They reduce bandwidth and code for long agent sessions with large tool outputs, they let the provider keep reasoning items and tool state in the exact format it expects, and they make implicit caching more likely. When are they not? When you need multi-provider support, strict data residency or deletion guarantees (check zero data retention options, under which the provider stores nothing after responding; see lesson 09, 9.1 and Module 12), or fine control over what the model sees.

3.6 What statelessness means for you as an engineer#

  • You own the conversation. Design a schema for storing messages (with IDs, roles, timestamps, token counts and tool-call links) from day one. Module 11A covers storage in production.
  • Every turn is a fresh, full-price read. Plan for history growth in cost and latency (Part 6).
  • Statelessness is a feature. It makes requests reproducible, makes it easy to retry, replay and test a conversation offline, lets you switch models mid-conversation, and means one user's chat can't leak into another's through the model.
  • "It forgot" usually means "we didn't send it". When a bot forgets an earlier fact, first check what your app actually sent: the fact may have been truncated away (Part 4). If it was sent, the model may have failed to use it (Part 5).

Part 4: Managing conversation history#

4.1 Why you need a strategy#

If you re-send everything forever, four things go wrong, usually in this order:

  1. Cost grows with every turn, roughly with the square of the number of turns (6.1).
  2. Latency grows, because the model must read more input before writing its first token (6.3).
  3. Quality drops, because long, noisy contexts dilute attention (Part 5).
  4. The window overflows, and you get an error or silent truncation (2.6).

With million-token windows, item 4 often comes last, so teams discover the problem through the bill or through quality complaints long before an error appears. History management is therefore not just about "fitting". It's about sending the smallest set of tokens that lets the model do the job well.

4.2 The strategies#

Strategy How it works Pros Cons Good for
Send everything Re-send the full history Simplest; nothing lost Cost and latency grow every turn; eventually overflows Short chats, prototypes
Truncation (drop oldest) When over budget, remove the oldest messages Simple, predictable Loses the start of the conversation, often where the goal was stated Casual chat
Sliding window of recent turns (last N turns) Always keep only the last N turns (not the sliding-window attention of lesson 04, 12.3) Constant cost per turn Forgets everything older; N turns can still be huge with big tool results Support bots, small talk
Token-budget window Keep the newest messages that fit a token budget Uses the budget fully; adapts to message size Same forgetting problem as above The default building block
Summarization (rolling summary) Replace old turns with a short summary written by an LLM Keeps the gist of a long conversation An extra LLM call; summaries lose details and can drift or introduce errors Long conversations, assistants
Compaction (provider-managed) The provider summarizes old context for you when a threshold is reached Little code to write Provider-specific; less control over what's kept Long-running agents
Pinning (pinned context) Keep critical facts (user's name, goal, constraints, decisions) in a fixed pinned context block that's never dropped (4.6) Important facts survive any trimming You must decide what to pin and keep it updated Any long-lived conversation
Clearing tool results Replace old, bulky tool outputs with a stub such as "[file contents removed]" Huge savings in agents The model can't re-read old results unless it calls the tool again Agents (Module 08A)
Retrieval over history Store all turns; retrieve only the relevant old ones for each new message Scales to unlimited history Retrieval can miss things; more infrastructure Long-term memory (Part 9)
Just-in-time retrieval Keep lightweight references (file paths, record IDs, URLs) in the context and let the model load the content through tools only when it needs it Big documents never sit in the history unless they're used Extra tool calls and latency; the model must know what to fetch Agents working over files, databases or the web (Module 08A)
Sub-agents (context isolation) Hand a focused sub-task to a separate model call or agent with its own fresh context; it returns only a short summary The main conversation stays small; each sub-task gets a clean window More calls and orchestration; details not in the summary are lost to the main agent Research, large codebases, long-horizon agents (Module 08A)

Real applications combine several: a pinned facts block, a rolling summary of older turns, the most recent turns verbatim, and old tool results cleared. Anthropic's context-engineering guidance highlights the last two rows for long-running agents: agents that "maintain lightweight identifiers (file paths, stored queries, web links, etc.)" and load data at runtime, and sub-agents that each explore with a clean context window and return "a condensed, distilled summary of its work (often 1,000-2,000 tokens)".

4.3 Token budgeting before you send#

Don't wait for a 400 error. Compute a budget and check it before every request:

text
input budget = context window
             − max output tokens (your max_tokens)
             − reasoning allowance (for reasoning models, if it isn't already inside max_tokens)
             − safety margin (5–10%, because local estimates are approximate)

Then count what you're about to send. Token counting is covered fully in lesson 02; the short version:

Provider Exact count before sending
OpenAI client.responses.input_tokens.count(model=..., input=...) returns .input_tokens
Anthropic client.messages.count_tokens(model=..., messages=..., system=..., tools=...) returns .input_tokens
Gemini client.models.count_tokens(model=..., contents=...) returns .total_tokens (on the Developer API, google-genai counts contents only, not a system instruction or tools: lesson 03.7, 2.4)
Open models The model's own tokenizer and chat template (1.4)
python
from dotenv import load_dotenv
from openai import OpenAI
import anthropic
from google import genai

load_dotenv()
messages = [{"role": "user", "content": "Summarize our refund policy: ..." }]

openai_count = OpenAI().responses.input_tokens.count(model="gpt-6-luna", input=messages)
print("OpenAI:", openai_count.input_tokens)

claude_count = anthropic.Anthropic().messages.count_tokens(model="claude-haiku-5-5", messages=messages)
print("Anthropic:", claude_count.input_tokens)

gemini = genai.Client()   # keep the client in a variable; a throwaway genai.Client() is garbage-collected and closes
gemini_count = gemini.models.count_tokens(
    model="gemini-3.8-flash", contents=messages[0]["content"])
print("Gemini:", gemini_count.total_tokens)
Example output · illustrative3 lines
OpenAI: 14
Anthropic: 17
Gemini: 10

4.4 Try it: a history manager#

Here is a provider-neutral function that keeps a conversation under a token budget. It always keeps the system prompt, a block of pinned facts and the new message; then it adds history from the newest message backwards until the budget is full; and it can optionally replace what it dropped with a summary:

python
import tiktoken

enc = tiktoken.get_encoding("o200k_base")   # an estimate; use your provider's counter for exact numbers
PER_MESSAGE_OVERHEAD = 4                     # rough allowance for role markers and formatting

def count_tokens(message: dict) -> int:
    return PER_MESSAGE_OVERHEAD + len(enc.encode(message["content"]))

def fit_history(system: str, pinned_facts: list[str], history: list[dict], new_message: str,
                context_window: int, max_output: int, safety_margin: float = 0.05,
                summarizer=None, summary_allowance: int = 500):
    """Return the messages to send, keeping the newest turns that fit the token budget."""
    # 1. The input budget: the window minus room for the reply minus a safety margin
    budget = context_window - max_output - int(context_window * safety_margin)

    # 2. Things that are always sent: system prompt (with pinned facts) and the new message
    facts = "\n".join(f"- {fact}" for fact in pinned_facts)
    system_msg = {"role": "system", "content": f"{system}\n\nFacts to remember:\n{facts}"}
    user_msg = {"role": "user", "content": new_message}
    used = count_tokens(system_msg) + count_tokens(user_msg)
    if used > budget:
        raise ValueError(f"System prompt + new message ({used} tokens) exceed the budget ({budget})")

    # 3. Walk backwards from the newest turn, keeping messages while they fit
    #    (if we'll summarize, leave room for the summary up front)
    history_budget = budget - (summary_allowance if summarizer else 0)
    kept = []
    for message in reversed(history):
        cost = count_tokens(message)
        if used + cost > history_budget:
            break
        kept.insert(0, message)
        used += cost

    # 4. Never start the kept history with an orphaned assistant reply
    while kept and kept[0]["role"] == "assistant":
        used -= count_tokens(kept.pop(0))

    dropped = history[: len(history) - len(kept)]

    # 5. Optionally replace exactly what was dropped with a summary, cut to its allowance
    if dropped and summarizer:
        text = "Summary of earlier conversation: " + summarizer(dropped)
        text = enc.decode(enc.encode(text)[: summary_allowance - PER_MESSAGE_OVERHEAD])
        summary = {"role": "system", "content": text}
        kept.insert(0, summary)
        used += count_tokens(summary)

    return [system_msg] + kept + [user_msg], used, budget, len(dropped)


# --- Demo: a long support chat squeezed into a tiny 600-token window ---
history = []
for i in range(1, 9):
    history.append({"role": "user", "content": f"Question {i}: " + "Can you explain the refund rules again? " * 6})
    history.append({"role": "assistant", "content": f"Answer {i}: " + "Refunds are allowed within 30 days of purchase. " * 6})

def toy_summarizer(messages):   # in a real app this would be a cheap LLM call
    return f"{len(messages)} earlier messages about refund rules (30-day window)."

for summarizer in (None, toy_summarizer):
    messages, used, budget, n_dropped = fit_history(
        system="You are a support assistant for Acme.",
        pinned_facts=["Customer name: Priya", "Plan: Pro (annual)"],
        history=history,
        new_message="So can I still get a refund for last week's order?",
        context_window=600, max_output=150, summarizer=summarizer, summary_allowance=40,
    )
    print(f"summarizer={'yes' if summarizer else 'no '} | budget {budget} | used {used} | "
          f"sent {len(messages)} messages | dropped {n_dropped} of {len(history)}")
    for m in messages:
        print(f"   {m['role']:9s} {count_tokens(m):4d} tokens | {m['content'][:48]!r}")
Output15 lines
summarizer=no  | budget 420 | used 311 | sent 6 messages | dropped 12 of 16
   system      31 tokens | 'You are a support assistant for Acme.\n\nFacts to '
   user        57 tokens | 'Question 7: Can you explain the refund rules aga'
   assistant   75 tokens | 'Answer 7: Refunds are allowed within 30 days of '
   user        57 tokens | 'Question 8: Can you explain the refund rules aga'
   assistant   75 tokens | 'Answer 8: Refunds are allowed within 30 days of '
   user        16 tokens | "So can I still get a refund for last week's orde"
summarizer=yes | budget 420 | used 332 | sent 7 messages | dropped 12 of 16
   system      31 tokens | 'You are a support assistant for Acme.\n\nFacts to '
   system      21 tokens | 'Summary of earlier conversation: 12 earlier mess'
   user        57 tokens | 'Question 7: Can you explain the refund rules aga'
   assistant   75 tokens | 'Answer 7: Refunds are allowed within 30 days of '
   user        57 tokens | 'Question 8: Can you explain the refund rules aga'
   assistant   75 tokens | 'Answer 8: Refunds are allowed within 30 days of '
   user        16 tokens | "So can I still get a refund for last week's orde"

Reading the output:

  • The budget is 420, not 600: 600 − 150 reserved for the answer − 30 (5% margin).
  • Only the last two exchanges survived. Answer 6 (75 tokens) would have fitted, but its question (57 tokens) would not. Step 4 then removed the orphaned Answer 6, because a history that starts with an assistant reply to a missing question confuses models, and some APIs reject a conversation that doesn't start with a user turn. That's why "used" (311) is well below the budget.
  • The pinned facts survived everything. However much history is dropped, the customer's name and plan are always sent.
  • The summary kept a trace of the 12 dropped messages for 21 tokens.

Adapting this to real providers takes a few changes: Anthropic and Gemini take the system prompt as a separate parameter; tool calls must stay paired with their results; on Claude, strip thinking blocks from the turns you keep whenever you trim or summarize (see the warning in 4.2); and you should count with the provider's counter when close to the limit. Where the pinned facts and summary go also affects caching (4.6). The flow looks like this:

flowchart TB
    A["New user message arrives"] --> B["Load stored history<br/>and pinned facts"]
    B --> C["Count tokens:<br/>system + facts + history + new message"]
    C --> D{"Fits the input budget?<br/>(window - max output - reasoning - margin)"}
    D -- "yes" --> G["Send the request"]
    D -- "no" --> E["Drop or summarize the oldest turns<br/>(keep tool calls with their results)"]
    E --> C
    G --> H["Store the reply<br/>(and update pinned facts)"]

4.5 Summarization and compaction#

Summarization (also called compaction when done automatically) replaces older turns with a condensed version. A good summary prompt asks for exactly what later turns will need:

  • The user's goal and any constraints or preferences they stated
  • Decisions made and their reasons
  • Facts established (names, IDs, numbers, dates), copied exactly
  • Open questions and the next steps
  • For agents: which files were changed, which tools were tried, what failed

Practical rules:

  • Summarize in chunks, not every turn. Re-summarizing every turn costs an LLM call per message and, worse, changes the start of the prompt every time, which defeats prompt caching (7.4). A common pattern is: when history passes, say, 70% of the budget, summarize the oldest half in one go.
  • Use a cheaper model for summaries if quality holds on your evaluation set.
  • Keep the raw history in your database. The summary is what you send, not what you store, so you can re-summarize later or show the user the full transcript.
  • Watch for summary drift. Each summary of a summary loses detail and can introduce errors. Copy critical facts into the pinned block instead of trusting the summary to carry them.

Several providers now offer this as a built-in feature (all details as of November 2026; check the docs before relying on them):

Provider Built-in compaction Notes
OpenAI Server-side compaction in the Responses API via context_management=[{"type": "compaction", "compact_threshold": 200000}], and a standalone client.responses.compact(...) endpoint Compaction runs automatically when the context crosses the threshold
Anthropic Compaction (beta): either on demand (you request a summary and swap it in) or at a token threshold (the API summarizes when input reaches a trigger you set). Also context editing (beta), which clears old tool results or thinking blocks instead of summarizing You must pass back the compaction block the API returns
Gemini Only in agent products: Google's Managed Agents API has a native compaction step at around 135,000 tokens, automatically. No compaction is documented for ordinary generateContent or Interactions calls as of November 2026 For ordinary model calls, summarize yourself
OpenRouter Its context compression plugin (middle-out) removes messages from the middle when a prompt is too long; it's on by default only for endpoints with 8,192 tokens of context or less It truncates rather than summarizes

4.6 Pinning and structured state#

Instead of hoping important facts survive in prose, keep them in a small structured pinned context block that your code maintains, and inject it near the top of every request, after the stable instructions:

text
<session_facts>
customer_name: Priya
plan: Pro (annual), renews 2027-01-14
open_ticket: #48213 (refund for order 7731)
agreed: refund approved pending return label
</session_facts>
  • Who updates it? Your code (from database fields), or the model itself through a tool such as update_facts(...) that your code validates (Module 08A).
  • Placement is a trade-off with caching. Pinned facts and rolling summaries are per-user and change during a session, so anything placed after them can't be served from the prompt cache once they change (7.4), and on current Claude models editing them also invalidates replayed thinking blocks (4.2). Keep the stable system prompt first (cacheable across all users), put the facts block and summary immediately after it, and update them only at the moments you compact anyway, not every turn, accepting one cache miss per update. Alternatively, leave the top untouched and append updated facts as a new late message, for example a mid-conversation system message where the provider supports one (Anthropic does on its current models).
  • Agents do the same thing with "scratchpads" or progress files: a short document listing the plan, what's done and what's next, which survives when old turns are cleared. Anthropic's long-running-agent guidance recommends designing such state so a fresh session can recover quickly.

4.7 Rules that prevent subtle bugs#

Rule Why
Never separate a tool call from its result. Drop or keep them together APIs reject a tool result whose call is missing (and vice versa); the model gets confused by half-pairs
Keep the conversation starting with a user turn Some APIs require it, and an orphaned assistant message reads like nonsense
Handle reasoning/thinking blocks the way your provider requires Some providers require the latest thinking block to be sent back unchanged with tool results; some strip old ones automatically, others keep them in the window (lesson 08)
On Claude, never replay a thinking block after editing what came before it Current Claude models bind each thinking block to its prefix; for new accounts, an edited prefix plus a replayed thinking block is a 400 error (4.2)
Trim from the front in big chunks, not one message per turn Removing one old message every turn changes the prompt prefix every turn, so prompt caching never hits (7.4)
Budget images and files separately One image or PDF can cost more than dozens of text messages; old attachments are often the best thing to drop
Log what you actually sent When the model "forgets", you need to see the exact context to tell a truncation bug from a model failure
Test with long conversations Bugs in history management only appear after many turns; include long transcripts in your evaluation set (Module 10A; 10A.11, Part 6 for compaction and long-conversation tests)

Part 5: Long-context performance: bigger is not better#

Deep-dive

A model that accepts a million tokens does not use a million tokens equally well. This is the most important practical fact about context windows, and the one marketing numbers hide.

5.1 Lost in the middle#

In 2023, researchers at Stanford and elsewhere (Liu et al., "Lost in the Middle: How Language Models Use Long Contexts", published in TACL in 2024) gave models a question plus 10, 20 or 30 retrieved documents, exactly one of which contained the answer, and moved that document from the first position to the last.

The result was a U-shaped curve:

  • Accuracy was highest when the relevant document was at the very start or the very end of the context.
  • Accuracy was lowest when it was in the middle.
  • In the 20- and 30-document settings, GPT-3.5-Turbo's accuracy dropped by more than 20 percentage points between the best and worst positions, and with the answer in the middle it scored below its closed-book score: the model did worse with the right document in its context than with no documents at all.
text
accuracy
  high |█                         █
       | █                       █
       |  ██                   ██
       |    ███             ███
   low |       █████████████
       +-------------------------------
        start     middle      end
          position of the relevant document

Why does this happen? Two effects are commonly cited. Models learn from training data where the most important information tends to be at the beginning (titles, introductions, instructions) and at the end (the most recent text, right before what comes next), so they learn to weight those positions heavily. And the way positional information is encoded tends to favour nearby tokens, so the end of the context, closest to where the answer is being written, gets extra attention (lesson 04 explains attention and positional encoding).

5.2 Context rot: degradation with length#

"Lost in the middle" is about position. A second, broader effect is about length: as the context grows, models get less reliable even when the task stays the same.

  • Chroma's "Context Rot" report (2025) tested 18 models while holding task difficulty fixed and only adding length. It found that "performance grows increasingly unreliable as input length grows". It also found that performance drops faster when the question and the relevant text share fewer words (they're related by meaning rather than wording), that "even a single distractor reduces performance", and that on a long-conversation memory benchmark, a focused prompt of about 300 tokens scored well above the full 113,000-token conversation containing the same facts.
  • "Same Task, More Tokens" (Levy, Jacoby and Goldberg, ACL 2024) padded simple reasoning tasks with irrelevant text. Average accuracy fell from 0.92 to 0.68 at only about 3,000 tokens of input, far below the models' maximum context.
  • Anthropic's own documentation now names the effect: "As token count grows, accuracy and recall degrade, a phenomenon known as context rot. This makes curating what's in context just as important as how much space is available." Its engineering blog describes the model as having an attention budget: "Every new token introduced depletes this budget."

The term context rot has stuck: every extra token you add is a small tax on the model's ability to focus on the tokens that matter. One proposed cause is attention dilution: attention weight gets spread across many more tokens, so the few that matter receive a smaller share (lesson 04, 4.4).

5.3 Needle-in-a-haystack tests and why they flatter models#

The most famous long-context test is needle in a haystack (NIAH), popularized by Greg Kamradt in 2023. You hide a single sentence (the "needle", for example "The best thing to do in San Francisco is eat a sandwich and sit in Dolores Park on a sunny day") at some depth inside a long filler text (the "haystack"), ask the model to retrieve it, and repeat across a grid of context lengths and depths. The results are shown as a heatmap, and today's frontier models typically score near-perfectly. Google's Gemini documentation, for example, reports around 99% single-needle accuracy.

That near-perfect score is real, but it overstates long-context ability, for several reasons:

Weakness of NIAH Why it inflates scores What research shows
Literal matching The question repeats the needle's exact words, so the model just has to spot matching text, an easy pattern for attention NoLiMa (2025) rewrote needles so question and answer share no keywords. At 32K tokens, 11 of 13 models fell below 50% of their short-context scores; GPT-4o dropped from 99.3% to 69.7%
One needle Real tasks need many facts combined Google's own docs note that with multiple needles "the model does not perform with the same accuracy". OpenAI's GPT-4.1 prompting guide notes performance "can degrade as more items are required to be retrieved"
The haystack is irrelevant Filler text is obviously unrelated, so the needle stands out Chroma found that topically similar distractors sharply reduce accuracy
Retrieval is not reasoning Finding a sentence differs from understanding a whole document, tracking state or reconciling contradictions RULER (NVIDIA, 2024) added multi-hop tracing, aggregation and question answering: although all tested models claimed 32K+ windows, "only half of them can maintain satisfactory performance at the length of 32K"

RULER introduced a useful idea: a model's effective context length is the longest input at which it still performs above a fixed quality bar. In RULER's results, for example, GPT-4 (gpt-4-1106-preview) claimed 128K but was effective to 64K, and Yi-34B claimed 200K but was effective to 32K. Effective lengths for current models are much longer, but the gap between claimed and effective remains (10.2).

5.4 Try it: a mini needle-in-a-haystack test#

Let's run a tiny NIAH test on the 0.5B model, so you can see the method and adapt it to your own models and data. We hide a secret code at five depths in haystacks of 500, 2,000 and 8,000 tokens, kept small enough to finish in about a minute on a laptop CPU; add larger sizes to the list when you have time:

python
import random
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer

MODEL = "Qwen/Qwen2.5-0.5B-Instruct"
tokenizer = AutoTokenizer.from_pretrained(MODEL)
model = AutoModelForCausalLM.from_pretrained(MODEL, dtype=torch.float32)   # full precision: much faster than BF16 on most CPUs
model.eval()

random.seed(42)
TOPICS = ["The harbour", "The old library", "A local bakery", "The night train", "The city council",
          "A mountain trail", "The science museum", "A small vineyard", "The river ferry", "The weather station"]
VERBS = ["opened a new wing", "changed its schedule", "hired three volunteers", "published a report",
         "repainted the entrance", "hosted a festival", "upgraded its equipment", "won a regional award"]

def haystack(n_tokens):
    sentences, total = [], 0
    while total < n_tokens:                                    # count tokens as we go
        s = f"{random.choice(TOPICS)} {random.choice(VERBS)} in {random.randint(1990, 2024)}."
        sentences.append(s)
        total += len(tokenizer.encode(" " + s))
    return sentences

NEEDLE = "The secret code for the blue door is 7314."
QUESTION = "What is the secret code for the blue door? Reply with the number only."

def run(n_tokens, depth):
    sentences = haystack(n_tokens)
    sentences.insert(int(len(sentences) * depth), NEEDLE)      # hide the needle at this depth
    messages = [{"role": "user", "content": " ".join(sentences) + "\n\n" + QUESTION}]
    prompt = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
    ids = tokenizer(prompt, return_tensors="pt")
    with torch.no_grad():
        out = model.generate(**ids, max_new_tokens=8, do_sample=False)
    answer = tokenizer.decode(out[0][ids["input_ids"].shape[1]:], skip_special_tokens=True)
    return "7314" in answer

depths = [0.0, 0.25, 0.5, 0.75, 1.0]
print("haystack size | " + " | ".join(f"depth {d:.0%}" for d in depths))
for n in [500, 2000, 8000]:   # add 16000 and 32000 if you have time
    results = ["found" if run(n, d) else "MISSED" for d in depths]
    print(f"{n:10,d} tok | " + " | ".join(f"{r:>9s}" for r in results))
Output4 lines
haystack size | depth 0% | depth 25% | depth 50% | depth 75% | depth 100%
       500 tok |     found |     found |     found |     found |     found
     2,000 tok |     found |    MISSED |     found |    MISSED |     found
     8,000 tok |     found |    MISSED |    MISSED |     found |     found

How to read it:

  • Each row is a haystack size and each column a needle position. Real NIAH reports show the same grid as a heatmap, with sizes up to the full window.
  • At 500 tokens the model found every needle. The question repeats the needle's distinctive words ("secret code for the blue door"), the filler is obviously unrelated, and there's only one fact to find: exactly the conditions that make NIAH easy (5.3).
  • At 2,000 and 8,000 tokens it missed two of five in each row. 2,000 tokens is only 6% of this model's 32,768-token window. A small model's effective context is far shorter than its advertised one (10.2).
  • The needles at the very start and the very end were always found; every miss was somewhere in between. That's consistent with the position effects in 5.1, but it isn't proof of a U-shape: the 2,000-token row found the 50% needle and missed 25% and 75%.
  • One trial per cell is a tiny sample. A single run like this is noisy: a different random haystack (change the seed) can move the misses around. Real evaluations repeat each cell many times and report rates, not single outcomes (Module 10A). Treat this as a demonstration of the method, not a measurement of the model.
  • Scale it up. This model's window is 32,768 tokens, so add 16,000 and 32,000 to the list. Expect each cell to take longer as the haystack grows, because prefill grows faster than the input (6.3): on a laptop CPU the whole grid above takes about a minute, while a 32,000-token cell alone can take a minute or more.
  • Then make it realistic. Exercise 5 removes the crutches one at a time: no shared keywords, a distractor needle, two needles. Frontier models pass the easy version at enormous lengths; these harder versions are where they too start to fail.

5.5 Position effects: where to put instructions and documents#

Position matters, and the providers publish guidance (as of November 2026):

Source Guidance
Anthropic (prompting best practices, for prompts of 20K+ tokens) "Place your long documents and inputs near the top of your prompt, above your query, instructions, and examples." It adds: "Queries at the end can improve response quality by up to 30 percent in tests, especially with complex, multidocument inputs."
Google Gemini (long-context guide) "the model's performance will be better if you put your query / question at the end of the prompt"
OpenAI (GPT-4.1 prompting guide) For long context, "ideally place your instructions at both the beginning and end of the provided context". If only once, "above the provided context works better than below"

These agree more than they appear to. Combined into one practical layout:

  1. Put stable instructions first, in the system prompt: role, rules, output format.
  2. Then the long material: documents, code, transcripts, each clearly delimited and labelled (for example with XML-style tags such as <document source="refund_policy.pdf">).
  3. Put the specific question last, right before the model starts writing.
  4. For very long contexts, repeat the critical instructions briefly at the end ("Answer only from the documents above; cite the document name").
flowchart TB
    subgraph stable ["Stable prefix: identical on every request (cacheable)"]
        direction TB
        A["1. Tool definitions (fixed order)"]
        B["2. System prompt: role, rules, output format"]
        C["3. Long reference material<br/>(policies, manuals, codebase)"]
    end
    subgraph grows ["Grows turn by turn (append only)"]
        D["4. Conversation history"]
    end
    subgraph changes ["Changes every request"]
        direction TB
        E["5. Retrieved snippets for this question"]
        F["6. The question, plus a one-line<br/>reminder of the key instructions"]
    end
    A --> B --> C --> D --> E --> F

This order is also the one that works best with prompt caching: everything that never changes comes first, everything that changes comes last (7.4).

More ordering advice that follows from Parts 5.1–5.3:

  • Put the most relevant material at the edges. If you retrieve ten chunks, place the best ones at the start and end of the block, not in the middle. Some RAG systems deliberately reorder chunks this way (Module 07).
  • Remove what isn't needed. Every irrelevant document is a potential distractor. Fewer, better chunks usually beat more chunks.
  • Ask the model to quote first. For long documents, asking the model to first extract the relevant quotes, then answer from them, helps it focus. Anthropic's documentation recommends this technique.
  • Label everything. Clear tags and headings let the model (and you, when debugging) tell sources apart.

Module 04 turns these into a full method for prompt and context engineering.

5.6 Test it on your own task#

Published benchmarks tell you what a model can do on someone else's task. To know how it behaves on yours:

  1. Take real examples from your application.
  2. Run them at the context sizes you'll actually use (for example 10K, 50K, 200K tokens of realistic surrounding material, not filler).
  3. Move the critical information to different positions.
  4. Measure quality with an evaluation set (Module 10A), and compare against a short-context baseline (only the relevant material). 10A.11, 2.2 shows published evidence for exactly this, with focused prompts beating full-history ones, and 2.1 lists the baselines to run.

If the short-context baseline wins, which it often does, you've learned that curating context (retrieval, summarization, trimming) is worth more than a bigger window.


Part 6: Cost and latency#

6.1 You pay for the history on every turn#

LLM APIs bill per token, for input and output separately, and input is re-billed on every request (3.5). In a chat, turn n re-sends the system prompt plus all n − 1 earlier turns. The total input you pay for therefore grows roughly with the square of the number of turns: twice as many turns costs about four times as much input.

Let's compute it. This calculator takes the price per million tokens as a parameter, so you can plug in any model's current price:

python
def chat_cost(turns: int, system_tokens: int, user_tokens: int, reply_tokens: int,
              input_price_per_m: float, output_price_per_m: float,
              cached_input_price_per_m: float | None = None):
    """Cost of a chat where the full history is re-sent every turn.

    If cached_input_price_per_m is given, assume everything sent in the previous
    turn is a cache hit this turn (the best case for prompt caching).
    """
    total_cost = total_input = 0
    history = 0                                   # tokens of earlier turns
    rows = []
    for turn in range(1, turns + 1):
        input_tokens = system_tokens + history + user_tokens
        if cached_input_price_per_m is None:
            input_cost = input_tokens * input_price_per_m / 1e6
        else:
            # Only last turn's INPUT can be cached; its reply was generated, never cached
            cached = system_tokens + history - reply_tokens if turn > 1 else 0
            fresh = input_tokens - cached
            input_cost = (cached * cached_input_price_per_m + fresh * input_price_per_m) / 1e6
        cost = input_cost + reply_tokens * output_price_per_m / 1e6
        total_cost += cost
        total_input += input_tokens
        rows.append((turn, input_tokens, cost, total_cost))
        history += user_tokens + reply_tokens     # this turn becomes history for the next
    return rows, total_input

# Example prices in USD per 1M tokens. Look up current prices for your model!
PRICE_IN, PRICE_OUT, PRICE_CACHED = 2.00, 10.00, 0.20

rows, total_in = chat_cost(turns=50, system_tokens=1500, user_tokens=100, reply_tokens=400,
                           input_price_per_m=PRICE_IN, output_price_per_m=PRICE_OUT)
print("turn | input tokens sent | cost of this turn | running total")
for turn, inp, cost, running in rows:
    if turn in (1, 2, 5, 10, 20, 30, 40, 50):
        print(f"{turn:4d} | {inp:17,d} | ${cost:16.4f} | ${running:.4f}")

new_tokens = 1500 + 50 * (100 + 400)
print(f"\nTokens actually typed or generated: {new_tokens:,}")
print(f"Input tokens billed over 50 turns:  {total_in:,}  ({total_in / new_tokens:.0f}x)")

cached_rows, _ = chat_cost(turns=50, system_tokens=1500, user_tokens=100, reply_tokens=400,
                           input_price_per_m=PRICE_IN, output_price_per_m=PRICE_OUT,
                           cached_input_price_per_m=PRICE_CACHED)
print(f"\n50-turn total without caching: ${rows[-1][3]:.4f}")
print(f"50-turn total with caching:    ${cached_rows[-1][3]:.4f}  (best case, cache writes ignored)")
print(f"Cost per 1,000 such chats:     ${rows[-1][3] * 1000:,.2f} vs ${cached_rows[-1][3] * 1000:,.2f}")
Output16 lines
turn | input tokens sent | cost of this turn | running total
   1 |             1,600 | $          0.0072 | $0.0072
   2 |             2,100 | $          0.0082 | $0.0154
   5 |             3,600 | $          0.0112 | $0.0460
  10 |             6,100 | $          0.0162 | $0.1170
  20 |            11,100 | $          0.0262 | $0.3340
  30 |            16,100 | $          0.0362 | $0.6510
  40 |            21,100 | $          0.0462 | $1.0680
  50 |            26,100 | $          0.0562 | $1.5850

Tokens actually typed or generated: 26,500
Input tokens billed over 50 turns:  692,500  (26x)

50-turn total without caching: $1.5850
50-turn total with caching:    $0.3855  (best case, cache writes ignored)
Cost per 1,000 such chats:     $1,585.00 vs $385.48

What the numbers show:

  • Turn 50 costs almost 8× turn 1 ($0.0562 vs $0.0072), even though the user typed the same amount.
  • The conversation contains 26,500 tokens, but you're billed for 692,500 input tokens, 26 times as many, because the history is re-read on every turn.
  • Input dominates. Output was 400 tokens per turn throughout; the growth is entirely re-sent history.
  • Caching changes the economics. Billing the repeated prefix at a cached rate (here 10% of the normal input price) cuts the total by about 76% in this best case. Only the previous turn's input can be a cache hit: the previous reply was generated output, never part of a cached prompt, so it's billed once at the full input price when it's re-sent as history (that's the - reply_tokens in the code). Real savings are lower: providers may charge extra to write the cache, and the cache expires between slow turns (7.3).

6.2 Agents make it worse#

Agents (Module 08A) call the model in a loop: think, call a tool, read the result, think again. Each loop iteration is a new request that re-sends the whole history, including every earlier tool result. An agent that reads ten 5,000-token files during a task carries 50,000 tokens of file contents into every later step. A 40-step agent run can easily process millions of input tokens. This is why tool-result clearing, compaction and caching (4.5, Part 7) matter most for agents.

6.3 Latency: prefill time grows with input#

Generating a response happens in two phases (lesson 05):

  1. Prefill: the model reads the entire input in one parallel pass and builds its internal representation of it, the KV cache (7.1). Nothing is shown to the user yet.
  2. Decode: the model generates the output one token at a time, reusing the KV cache.

The time from sending the request to receiving the first output token is the time to first token (TTFT), and it's dominated by prefill. Prefill work grows with input length (and attention's share of it grows faster than linearly, 10.1). Let's measure it on the local model:

python
import time
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer

MODEL = "Qwen/Qwen2.5-0.5B-Instruct"
tokenizer = AutoTokenizer.from_pretrained(MODEL)
model = AutoModelForCausalLM.from_pretrained(MODEL, dtype=torch.float32)   # full precision: much faster than BF16 on most CPUs
model.eval()
torch.manual_seed(0)

filler_ids = tokenizer.encode("The quick brown fox jumps over the lazy dog. " * 2000)

def timed_forward(input_ids, past=None):
    start = time.perf_counter()
    with torch.no_grad():
        out = model(input_ids=input_ids, past_key_values=past, use_cache=True)
    return out, time.perf_counter() - start

timed_forward(torch.tensor([filler_ids[:64]]))          # warm-up run, not measured

print("input tokens | prefill (reading the prompt) | one new token afterwards")
for n in [256, 512, 1024, 2048, 4096, 8192]:
    ids = torch.tensor([filler_ids[:n]])
    prefills, decodes = [], []
    for _ in range(3):                                   # best of 3 runs, to reduce noise
        out, prefill = timed_forward(ids)
        next_id = out.logits[:, -1:].argmax(-1)          # the first generated token
        _, decode = timed_forward(next_id, out.past_key_values)  # reuses the KV cache
        prefills.append(prefill); decodes.append(decode)
    print(f"{n:12,d} | {min(prefills) * 1000:24,.0f} ms | {min(decodes) * 1000:20.0f} ms")

Output (best of three runs on a laptop CPU; yours will differ, and a GPU is orders of magnitude faster):

text
input tokens | prefill (reading the prompt) | one new token afterwards
         256 |                      207 ms |                   28 ms
         512 |                      428 ms |                   34 ms
       1,024 |                      871 ms |                   76 ms
       2,048 |                    1,535 ms |                   31 ms
       4,096 |                    4,164 ms |                   76 ms
       8,192 |                   11,347 ms |                  327 ms

What the numbers show:

  • Prefill time grows with input, and faster than the input does at long lengths. From 256 to 2,048 tokens (8× more) prefill took about 7× longer; from 2,048 to 8,192 tokens (only 4× more) it also took about 7× longer. At short lengths the work is dominated by parts of the model that grow linearly; as the prompt grows, attention, whose work grows with the square of the length (10.1), takes a larger share.
  • Generating one more token stays cheap by comparison, because the KV cache means only the new token is computed. It grows slowly with the length of the cache it has to read (327 ms at 8,192 tokens), and millisecond-scale timings are noisy (note the 2,048 row), but even at 8,192 tokens one new token is about 35× cheaper than the prefill.
  • Lesson 05 compared prefill and decode per token on the same model; here we look at how prefill grows with length. The dtype=torch.float32 line matters: transformers otherwise loads this model in BF16, which is much slower on most CPUs.

On hosted APIs the hardware is far faster, but the shape is the same: a 500,000-token prompt can take many seconds, or more, before the first token appears, while a 2,000-token prompt starts almost instantly. What this means for you:

  • Long contexts hurt interactive UX. Users notice a TTFT of several seconds. Stream responses (lesson 05) and keep chat contexts lean.
  • Prompt caching also cuts latency, because cached prefixes skip prefill (7.2).
  • Output length still matters for total time. Prefill sets the time to the first token; the number of output tokens sets how long the rest takes.

6.4 Rate limits count tokens too#

Providers limit how many tokens per minute (TPM) you can send, as well as requests per minute. Long contexts consume TPM quickly: at 200,000 tokens per request, a limit of 2,000,000 TPM allows only 10 requests a minute, however small the answers. When you plan capacity, multiply your expected context size by your request rate.

Caching affects this differently by provider (as of November 2026). OpenAI's prompt-caching guide says: "Cached input tokens still count toward tokens-per-minute limits." Anthropic limits input tokens per minute (ITPM) and output tokens per minute separately, and its rate-limit documentation says that "for most Claude models, only uncached input tokens count toward your ITPM rate limits": cache reads don't count, while cache writes and uncached input do. So on Anthropic, caching is also a throughput lever (with an 80% cache-hit rate, a 2,000,000 ITPM limit can process about 10,000,000 total input tokens a minute), while on OpenAI it saves money and latency but not rate-limit headroom. Rate limits and how to handle them are covered in Module 03 and Module 11C.

6.5 The levers, in order#

To reduce context cost and latency, roughly in order of effort:

  1. Send less: trim history, clear old tool results, retrieve fewer and better chunks, shorten the system prompt and tool descriptions, and load tools on demand instead of sending dozens of definitions on every request (for example Anthropic's tool search tool with deferred loading, or routing each task to a smaller tool set, Module 08A).
  2. Cache what you repeat: put stable content first and turn on or verify prompt caching (Part 7).
  3. Summarize periodically instead of carrying full history (4.5).
  4. Use a smaller, cheaper model for sub-tasks such as summarization, routing and extraction (lesson 09).
  5. Use batch APIs for non-interactive work, which providers typically discount (Module 03).
  6. Retrieve instead of stuffing large corpora (Part 8).

Part 7: KV cache and prompt caching#

Deep-dive

7.1 The KV cache in one paragraph#

When a transformer processes a token, each attention layer computes a key vector and a value vector for it: roughly, a "label" other tokens can search for and the "content" they retrieve. Later tokens look back at the keys and values of every earlier token. During generation, recomputing these for the whole sequence at every new token would be wasteful, so the model stores them: this store is the KV cache (lesson 04, Part 11 explains the mechanism). Prefill fills it with the input's keys and values; each decode step adds one token's worth and reads all the rest. That's why, in the 6.3 measurement, a new token costs a small time that grows only slowly with the context, while reading the prompt costs more and more.

The KV cache has a price: memory, which grows linearly with the number of tokens in each conversation and with the number of conversations a server holds at once. Lesson 04, 11.4 computes it for real models: about 43 GB for a single 128K-token conversation on Llama 3.1 70B (roughly 328 KB per token at BF16). Scale the same arithmetic to the windows in this lesson and a model of that shape would need about 328 GB of KV cache for one user with a 1M-token context, and over 6.5 TB for twenty such users at once. What this means for you:

  • Long context is expensive to serve, because GPU memory spent on your KV cache can't serve anyone else. That's a major reason some providers charge more for long prompts (2.7).
  • Self-hosted servers default to small windows for the same reason (2.4); raising the window lowers how many users each GPU can serve.
  • Architecture matters. Designs such as grouped-query attention, sliding-window layers and KV-cache quantization shrink the cache several-fold, which is part of why some models serve long contexts more cheaply than others (lesson 04).

7.2 From KV cache to prompt caching#

Within one request, the KV cache saves recomputing tokens during generation. Prompt caching extends the idea across requests: if many requests start with the same tokens (the same system prompt, tool definitions or document), the provider can keep the KV cache for that shared prefix and reuse it, skipping its prefill entirely.

flowchart TB
    subgraph r1 ["Request 1"]
        P1["Prefix: system + policy document<br/>(12,000 tokens)"] --> Q1["Question A<br/>(30 tokens)"]
    end
    subgraph prov ["Provider"]
        K[("Stored KV cache<br/>for the prefix")]
    end
    subgraph r2 ["Request 2 (a few minutes later)"]
        P2["Same prefix, byte for byte"] --> Q2["Question B<br/>(25 tokens)"]
    end
    P1 -- "computed once,<br/>then saved" --> K
    K -- "reused: no recompute,<br/>discounted price" --> P2
    Q2 -- "only the new tokens<br/>are computed" --> OUT["Answer B"]

Two properties follow from how it works:

  • It must be an exact prefix. A token's key and value depend on every token before it (that's what attention does). Change one token near the start, even a timestamp or a space, and every key and value after that point is different, so nothing after the change can be reused. Caching only ever reuses an identical beginning of the prompt.
  • It saves both money and time. Reused tokens skip prefill, so providers charge less for them and the first token arrives sooner.

Let's see prefix reuse locally. We compute the KV cache for a long document once, then answer two different questions by running only the question tokens on top of a copy of that cache:

python
import copy, time
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer

MODEL = "Qwen/Qwen2.5-0.5B-Instruct"
tokenizer = AutoTokenizer.from_pretrained(MODEL)
model = AutoModelForCausalLM.from_pretrained(MODEL, dtype=torch.float32)   # full precision: much faster than BF16 on most CPUs
model.eval()

# A long, unchanging prefix (think: system prompt + a policy document) ...
document = "Acme refund policy. " + " ".join(
    f"Rule {i}: orders in category {i % 7} may be returned within {10 + i % 20} days." for i in range(150))
prefix_ids = tokenizer.encode(document)
# ... followed by a short question that changes on every request
questions = ["\nQuestion: how long for category 3?", "\nQuestion: can I return a gift?"]

def forward(ids, past=None):
    start = time.perf_counter()
    with torch.no_grad():
        out = model(input_ids=torch.tensor([ids]), past_key_values=past, use_cache=True)
    return out, time.perf_counter() - start

forward(prefix_ids[:32])                                  # warm-up run, not measured
print(f"Prefix: {len(prefix_ids):,} tokens")

# Compute the prefix's KV cache ONCE (this is what a provider stores when it caches a prompt)
prefix_out, t_prefix = forward(prefix_ids)
print(f"Building the prefix KV cache: {t_prefix * 1000:,.0f} ms (paid once)\n")

for q in questions:
    q_ids = tokenizer.encode(q)
    full_out, t_full = forward(prefix_ids + q_ids)                          # no caching
    cache = copy.deepcopy(prefix_out.past_key_values)                       # reuse the stored prefix
    cached_out, t_cached = forward(q_ids, cache)
    same = full_out.logits[0, -1].argmax() == cached_out.logits[0, -1].argmax()
    print(f"{q.strip()!r}")
    print(f"   full prompt every time: {t_full * 1000:6,.0f} ms | with cached prefix: {t_cached * 1000:4,.0f} ms"
          f" | same next token: {bool(same)}")
Output · timings from a laptop CPU; yours will differ7 lines
Prefix: 2,895 tokens
Building the prefix KV cache: 2,521 ms (paid once)

'Question: how long for category 3?'
   full prompt every time:  3,438 ms | with cached prefix:  401 ms | same next token: True
'Question: can I return a gift?'
   full prompt every time:  3,320 ms | with cached prefix:  294 ms | same next token: True

What happened:

  • Re-reading the whole prompt cost about 3.3–3.4 seconds per question, because the model re-did the prefill of all 2,895 prefix tokens every time.
  • With the stored prefix, each question took 0.3–0.4 seconds, because only the question's handful of tokens had to be computed. That's roughly a 9–11× speed-up here, and the saving grows with the length of the prefix.
  • same next token: True: reusing the cache gives the same result as recomputing from scratch. Caching is an optimization, not an approximation.
  • The prefix cost was paid once (2.5 seconds) and then reused. That's exactly the economics of provider prompt caching: the first request writes the cache, later requests read it at a fraction of the cost and time.

Notice also why the prefix must be exact: the cache stores the keys and values for those specific 2,895 tokens in that order. If the document changed by one token near the start, the stored cache would be useless from that point on.

7.3 Provider prompt caching as of November 2026#

All four providers support caching, with different defaults and prices. This table is the module's single reference for caching rules and prices; other lessons link here. The read and write multipliers were re-checked against the providers' pricing pages in November 2026, and the exact dollar figures live in Module 03's price table (03.7, Part 4). Details change often, so verify on each provider's prompt-caching page before relying on a number. "Base price" means the model's normal input price.

OpenAI Anthropic Google Gemini OpenRouter
On by default? Yes, automatic for supported models; GPT-5.6 and later also offer an explicit mode (prompt_cache_options.mode: "explicit") that caches only the breakpoints you mark No, opt-in: a top-level cache_control (automatic placement, best for growing conversations) or cache_control on specific blocks (best for a shared prefix with a varying ending) Yes: implicit caching on Gemini 2.5 and newer. Explicit caching (an explicit context cache: a cache object you create; Google calls the whole feature "context caching") is also available, but "is not supported in the Interactions API, or for Gemini 4 Argon and onward" Passes through each provider's behaviour. Automatic for most; Anthropic (and Alibaba Qwen) models need cache_control
Minimum cacheable prefix 1,024 visible input tokens on GPT-5.6 and later (OpenAI's hidden system content doesn't count); on earlier models the minimum varies with tools, images and output schema 512 tokens on the current Claude 5.x models (1,024–4,096 on older models); shorter prompts are silently not cached Implicit: 4,096 tokens on current models (2,048 on Gemini 2.5); on Gemini 4, "Gemini caches the full previous request only if the new request adds at least 2,050 tokens", so short chat turns may not extend the cache. Explicit: varies by model Per provider
Price of a cache read GPT-5.6 and later: 0.1× base (0.05× on GPT-6.1 Sol and Terra). Older models: discounted, varies by model 0.1× base; 0.05× on Opus 5.5 and Sonnet 5.5; 0.025× on Fable 5.2 and 5.1 Implicit: discounted automatically (95% off on gemini-4-argon and gemini-4-carbon; roughly 90% off on other current models, judging by the pricing page). Explicit: discounted, plus storage per hour Per provider; the response's cache_discount field reports the saving
Price of a cache write GPT-5.6 and later: 1.25× base (30-minute lifetime) or 2.5× (12-hour, where offered). Older models: no write charge 1.25× base (5-minute lifetime) or 2× (1-hour) Implicit: none. Explicit: normal input price to create, plus storage Per provider
Lifetime GPT-5.6 and later: 30 minutes by default. Older models: about 5–10 minutes of inactivity, up to an hour, or up to 24 hours with extended retention 5 minutes by default, refreshed free on every hit; 1 hour optional Implicit: managed by Google. Explicit: you set a TTL (default 1 hour) Per provider
How to check it worked Reads: usage.input_tokens_details.cached_tokens (Responses) or usage.prompt_tokens_details.cached_tokens (Chat Completions). Writes (GPT-5.6 and later): usage.input_tokens_details.cache_write_tokens usage.cache_read_input_tokens and usage.cache_creation_input_tokens usage.total_cached_tokens (Interactions API) or usage_metadata.cached_content_token_count (generate_content) usage.prompt_tokens_details.cached_tokens

Here's what caching looks like in code on the two providers with the most different designs: Anthropic, where you opt in, and OpenAI, where it's automatic and you only read the usage. The traffic shape is "same document, different question", so on Anthropic we mark the end of the shared part explicitly:

python
from dotenv import load_dotenv
from openai import OpenAI
import anthropic

load_dotenv()
POLICY = "Acme refund policy. " + " ".join(                # a long, unchanging document
    f"Rule {i}: orders in category {i % 7} may be returned within {10 + i % 20} days." for i in range(600))

# Anthropic: caching is opt-in. An explicit breakpoint marks the end of the shared prefix;
# the varying question comes after it, so request 2 can read what request 1 wrote.
claude = anthropic.Anthropic()
for question in ["How long do I have to return shoes?", "Are gift cards refundable?"]:
    response = claude.messages.create(
        model="claude-haiku-5-5", max_tokens=512,
        system=[{"type": "text", "text": f"Answer using this policy:\n{POLICY}",
                 "cache_control": {"type": "ephemeral"}}],   # cache the shared prefix only (5 minutes)
        messages=[{"role": "user", "content": question}])
    u = response.usage
    print(f"Claude  written: {u.cache_creation_input_tokens:6d} | read: {u.cache_read_input_tokens:6d}"
          f" | uncached: {u.input_tokens}")

# OpenAI: caching is automatic for prompts of 1,024+ tokens; you just read the usage
client = OpenAI()
for question in ["How long do I have to return shoes?", "Are gift cards refundable?"]:
    response = client.responses.create(
        model="gpt-6-luna", instructions=f"Answer using this policy:\n{POLICY}", input=question)
    print("OpenAI  cached input tokens:", response.usage.input_tokens_details.cached_tokens,
          "of", response.usage.input_tokens)
Example output · illustrative4 lines
Claude  written:  11236 | read:      0 | uncached: 14
Claude  written:      0 | read:  11236 | uncached: 12
OpenAI  cached input tokens: 0 of 10224
OpenAI  cached input tokens: 10112 of 10222

The first request writes the cache, the second reads it. On Anthropic, the explicit breakpoint matters: top-level automatic caching (cache_control on the request itself) places the breakpoint on the last cacheable block, which here would be the varying question, so every request would write a new entry and none would be read back. Anthropic's docs recommend automatic caching for multi-turn chats, where the conversation grows by appending, and an explicit marker at the end of the shared portion for traffic like this. On Anthropic, input_tokens counts only the tokens after the cached prefix, so total input = cache_read_input_tokens + cache_creation_input_tokens + input_tokens. On OpenAI, cached_tokens is the part of input_tokens that was served from cache. Explicit Gemini caches (client.caches.create(...)) and per-provider details are covered in Module 03.

7.4 Designing prompts that hit the cache#

Because caching reuses only an identical prefix, prompt structure decides your hit rate:

Do Don't
Put stable content first: tools, system prompt, reference documents (5.5) Put a timestamp, request ID or user name at the top of the system prompt
Keep tool definitions in a fixed, deterministic order Build the tool list from an unordered set, or add and remove tools per request
Serialize JSON with sorted keys Let key order vary between requests
Append new turns to the end of the history Rewrite, re-summarize or trim the start of the history on every turn
Trim or summarize in occasional large steps (4.5) Drop one old message per turn in a sliding window: the prefix changes every turn and the cache never hits
Keep the same model and settings within a conversation Switch models (caches are per model) or change settings that providers render into the prompt (for example thinking or effort settings on Anthropic)
Check the usage fields in your logs and dashboards Assume caching works because you enabled it

Part 8: Long context vs RAG#

8.1 Two ways to give a model knowledge#

When a model needs information that isn't in its weights, you have two ways to get it into the context:

  • Long context ("context stuffing"): put all the material in the prompt and let the model find what it needs.
  • Retrieval-augmented generation (RAG): store the material outside the model, retrieve only the chunks relevant to each question, and put just those in the prompt (Module 07).

Million-token windows led many people to declare RAG obsolete. It isn't, but the trade-off has shifted:

Long context RAG
Setup effort Minimal: concatenate and send Ingestion, chunking, embeddings, a vector or search index (Modules 05–07)
Corpus size Limited by the window (about 550,000–750,000 words at most, depending on the tokenizer) Effectively unlimited
Cost per question High: every question pays for the whole corpus (lower with caching) Low: only a few thousand tokens per question
Latency Higher prefill time (lower with caching) Retrieval adds a little; prompts stay short
Quality on lookups Suffers from lost-in-the-middle and distractors at large sizes Good if retrieval finds the right chunks; fails if it misses them
Quality on "whole-document" tasks (summarize, compare, find contradictions, trace through code) Strong: the model sees everything Weak: chunks lose the big picture
Freshness Re-send the updated material Update the index
Access control Hard: everything in the prompt is visible to the model Natural: filter retrieval by the user's permissions
Citations and debugging Harder to see what the model used Easy to log which chunks were used

8.2 How to choose#

flowchart TB
    Q["How much material could the model need?"] --> S{"Does all of it fit comfortably,<br/>well under the window?"}
    S -- "no" --> RAG["Retrieve (RAG):<br/>send only the relevant chunks"]
    S -- "yes" --> V{"Is it reused across many requests,<br/>and stable enough to cache?"}
    V -- "yes" --> LC["Long context + prompt caching"]
    V -- "no, it's a one-off" --> W{"Does the task need the whole thing<br/>(compare, summarize, find conflicts)?"}
    W -- "yes" --> LC2["Long context for this request"]
    W -- "no, it's a lookup" --> RAG
    RAG --> M["Measure both on your own<br/>eval set before deciding"]
    LC --> M
    LC2 --> M

Rules of thumb:

  • Small, stable corpus, many questions (a 30-page policy manual, a product's documentation): long context with prompt caching is often simplest and best.
  • Large or growing corpus (a company wiki, millions of support tickets): RAG, because it doesn't fit and paying for all of it per question would be absurd.
  • One-off deep analysis (review this contract, summarize these ten reports, explain this codebase): long context.
  • Per-user permissions (each user may see different documents): RAG with filtering.
  • In practice, combine them: retrieve generously (say the 50 most relevant chunks instead of 5) into a long-context model. Retrieval narrows the haystack; the large window gives room for enough evidence.

A back-of-envelope comparison makes the cost difference concrete. Suppose a 400,000-token corpus, 10,000 questions a month, and an example input price of $2 per million tokens:

  • Stuff everything, no caching: 400,000 × 10,000 = 4 billion input tokens → $8,000 a month, and every answer waits for a 400K-token prefill.
  • Stuff everything, all cache hits at 0.1×: about $800 a month, before cache-write costs, plus the context-rot risk at 400K tokens.
  • RAG with 5,000 tokens of retrieved context per question: 50 million input tokens → $100 a month, plus the cost of running retrieval.
  • Watch for long-context surcharges (2.7). On a model that bills prompts above 272K input tokens at double the input price, every one of these 400K-token requests falls into the higher tier: about $16,000 a month without caching.

The right answer depends on quality, which only your evaluation set can measure (Module 10A).

8.3 Context engineering#

Both approaches are special cases of a bigger discipline. Context engineering is the practice of deciding, for every request, exactly which tokens the model should see: which instructions, which examples, which documents, which parts of the history, which tool results, in what order and in what format. Anthropic's engineering guidance frames the goal as finding "the smallest possible set of high-signal tokens" that gets the job done. Everything in this lesson (budgets, history management, ordering, caching, retrieval) feeds into it. Module 04 teaches it as a full skill.


Part 9: Memory features are application code#

Deep-dive

9.1 How "the bot remembers me" works#

Products such as ChatGPT, Claude and Gemini offer memory features: they remember your name, your preferences or a project across separate conversations. After Part 3, you know this can't be the model remembering. It's the application:

flowchart LR
    U["User message"] --> R["Retrieve relevant memories<br/>(database / vector search)"]
    R --> P["Build the prompt:<br/>system + memories + history + message"]
    P --> M["Model API<br/>(stateless)"]
    M --> A["Answer to the user"]
    M --> X["Extract new facts worth keeping<br/>(LLM call or tool call)"]
    X --> DB[("Memory store<br/>owned by YOUR app")]
    DB --> R
  1. Extract: after (or during) a conversation, the app identifies facts worth keeping ("prefers metric units", "is building a Django app"), often with an LLM call or a tool the model can call.
  2. Store: the facts go into a database, often with embeddings so they can be searched by meaning (Module 06).
  3. Retrieve and inject: at the start of each new request, the app fetches relevant memories and puts them into the context, usually in or near the system prompt.

Every "memory" the model shows is just text your app put into the context window, so it consumes tokens, it can be wrong or stale, and it's subject to everything in Part 5.

9.2 Design questions for your own memory feature#

Question Why it matters
What is worth remembering? Storing everything creates noise and privacy risk; storing too little makes the feature useless
How are memories updated or corrected? Users change jobs, preferences and projects; stale memories cause wrong answers
How many tokens of memory per request? Memories compete with everything else for the window and add cost to every request
Can users see and delete them? Transparency and data-protection law (for example the right to erasure) usually require it (Module 12)
Can memories be poisoned? Text that ends up in memory is re-injected into future prompts; a malicious document or message could plant instructions there (a form of prompt injection, Module 12)

Provider tooling exists here too. Anthropic, for example, offers a memory tool (memory_20250818) through which Claude can read and write files that your code stores, and OpenAI's Conversations API stores conversation items on its servers. Both still come down to text being put back into the context. You'll build memory for agents in Module 08B.


Part 10: Going deeper: why context limits exist#

Deep-dive

This part is for readers who want to know why windows are finite and why "effective" context is shorter than advertised. It's not needed to use LLMs well, but it helps you judge claims about new models.

10.1 Why context windows are finite#

Three constraints set the limit. Lesson 04 explains each mechanism in depth; here is what they mean for context windows:

Constraint In one sentence Consequence for you Mechanism
Attention cost grows with the square of the length Every token is compared with every earlier token, so 10× more tokens means about 100× more attention work Long prompts are slow to prefill (6.3) and expensive to serve Lesson 04, Part 10
KV-cache memory grows linearly with length Every token in the context keeps its keys and values in GPU memory for the whole request Providers cap windows and price long prompts higher; self-hosted servers default to small windows (7.1) Lesson 04, Part 11
Positions beyond the trained range are unfamiliar Models learn to interpret positions (usually encoded with rotary position embeddings, RoPE) only up to the lengths they were trained on Past the trained length, quality usually collapses into repetition or gibberish rather than raising an error Lesson 04, 5.6

Long-context models get past the third constraint with context extension: they are pretrained at a moderate length and then extended with techniques such as Position Interpolation, NTK-aware scaling or YaRN, followed by continued training on long documents. Lesson 04, 5.4 and 5.6 cover these, including how to read a rope_scaling entry in a model's config. (ALiBi, another positional scheme in lesson 04, is chosen at pretraining rather than applied afterwards as an extension.) For you as an engineer, two points follow. A model card's long window may depend on a setting you must enable when you self-host (2.4). And an extended window is a capability the model was stretched to, which is exactly why the next section matters.

10.2 Advertised vs effective context length#

Put Part 5 and 10.1 together and you get the most useful scepticism in this lesson: the advertised context window is the longest input the model accepts; the effective context length is the longest input at which it still does your task well. They can differ a lot.

A concrete example: Meta's Llama 4 launch post described Llama 4 Scout as having "an industry-leading context window of 10M" tokens, while also stating that it was "pre-trained and post-trained with a 256K context length", with the rest coming from length-generalization techniques. In November 2026 OpenRouter's listing for the model shows its host serving 1,310,720 tokens. Three different numbers for one model: what it was trained on, what it was claimed to handle, and what a host actually serves. None of them tells you how well it works on your 300K-token task.

What to do as an engineer:

  • Treat window size as a ceiling, not a promise. Plan to use a fraction of it for tasks that need precise reasoning over the whole context.
  • Read long-context benchmarks critically. Single-needle retrieval near 100% says little; look for multi-needle, reasoning and real-task results (RULER, NoLiMa-style tests, your own evals).
  • Measure on your own data, at your real lengths (5.6).
  • Prefer less, better context. The best long-context strategy is usually to need less of it.

Common misconceptions#

Misconception Reality
"A 1M-token model can take a 1M-token prompt." On shared-window models the output (including reasoning) must fit too, and some providers publish a lower maximum input, such as 922,000 on a 1,050,000-token OpenAI model. Gemini 2.5 and 3.x are the exception: separate input and output budgets.
"The model remembers our earlier conversation." It's stateless. Your app (or the provider's storage feature) re-sends the history on every request.
"previous_response_id means I stop paying for the history." The provider re-assembles the history and the model reads all of it; OpenAI bills it as input tokens. You save bandwidth, not tokens. Caching may reduce the price.
"If it fits in the window, the model will use it." Accuracy degrades with length (context rot) and with position (lost in the middle), especially for anything harder than finding one literal fact.
"99% on needle-in-a-haystack means long context is solved." NIAH tests literal, single-fact retrieval from irrelevant filler. Harder tests (multi-needle, no keyword overlap, distractors, reasoning) show much larger drops.
"Bigger context windows make RAG obsolete." Long context is expensive per question, slower, weaker on large corpora and lacks access control. Many systems combine both.
"Prompt caching shrinks my prompt." It changes price and latency for repeated prefixes. The tokens still fill the window and still affect quality.
"Caching is on, so I'm saving money." Only exact, repeated prefixes above a minimum length hit the cache, and some providers charge extra for writes. A timestamp at the top of the prompt can silently disable it. Check the usage fields.
"A cut-off answer raises an error." Hitting the output cap returns a normal response with a length / max_tokens / MAX_TOKENS stop reason. Check it every time.
"Token counts are the same everywhere." Each model family has its own tokenizer and message formatting. Count with the provider's counter when it matters.
"The bigger the context window, the better the model." Window size says nothing about how well the model reasons over it. Measure effective context on your task.

Key takeaways#

  • The context window is the maximum number of tokens in one request, input plus output on most providers (Gemini 2.5 and 3.x publish separate input and output budgets instead). A separate, smaller maximum output caps the reply, and reasoning tokens count as output.
  • Everything consumes the window: the system prompt, tool definitions, history, tool results, retrieved documents, files and media, reasoning tokens, the output, and hidden template tokens.
  • As of November 2026, frontier models from OpenAI, Anthropic and Google offer about 1M-token windows with 64K–128K output caps. Look limits up in code (OpenRouter's model list, Anthropic's Models API, Gemini's models.get) rather than hard-coding them.
  • Exceeding limits behaves differently per provider: 400 errors, silent truncation (OpenAI's deprecated truncation="auto", OpenRouter's middle-out compression) or a stop reason for output caps. Check stop reasons, and count tokens before sending.
  • The model is stateless. Chat "memory" is your app re-sending history. Server-side state features store the history for you but still feed and bill all of it.
  • Manage history deliberately: budget tokens, keep recent turns, pin key facts, summarize or compact older turns in chunks, clear bulky tool results, and keep tool calls paired with their results.
  • Longer contexts are worse contexts: lost in the middle, context rot and distractors reduce accuracy. Put long material first and the question last, keep the most relevant content at the edges, and send less.
  • Cost grows roughly with the square of the number of turns because history is re-billed every turn; latency (time to first token) grows with input because of prefill.
  • The KV cache makes generation efficient within a request but uses memory linearly with length. Prompt caching reuses the KV cache of an identical prefix across requests, cutting cost and latency, so put stable content first and append rather than rewrite.
  • Long context vs RAG is a trade-off of corpus size, cost, latency, task type and access control; many systems retrieve generously into a long context. Choose with your own evaluations.
  • Memory features are application code: extract, store, retrieve, inject.
  • Limits exist because of quadratic attention cost, KV-cache memory and trained positional range. Advertised windows exceed effective context length, so test at your real lengths.

Terms introduced in this lesson#

Term One-line definition
Context window (context length) The maximum number of tokens a model can process in one request, usually input plus output
Input tokens / prompt tokens Everything sent to the model in a request
Output tokens / completion tokens Everything the model generates, including reasoning tokens
Maximum output tokens (max output) A separate cap on how many tokens a model can generate in one response; the "output cap" in this lesson
Chat template The model-specific format that wraps messages in special tokens before the model reads them (see also lesson 02)
Statelessness The model keeps nothing between requests; each request must contain everything needed
Conversation history The earlier turns your application re-sends so the model can follow a conversation
Server-side conversation state A provider feature that stores history and re-assembles it for you (for example previous_response_id)
Truncation Dropping part of the input (usually the oldest messages) to fit a limit
Sliding window (of recent turns) Keeping only the most recent N turns or tokens of a conversation (not sliding-window attention)
Summarization / compaction Replacing older context with a condensed summary to save tokens
Pinning (pinned context) Keeping critical facts in a pinned context block that is sent with every request and never trimmed (not the same as model pinning, lesson 09)
Token budget The number of input tokens you allow after reserving room for output, reasoning and a safety margin
Lost in the middle The tendency of models to use information at the start and end of a long context better than in the middle
Context rot Degradation of a model's accuracy and recall as the context grows longer
Needle in a haystack (NIAH) A test that hides one fact in long filler text and asks the model to retrieve it
Effective context length The longest input at which a model still meets a quality bar, often far below the advertised window
Prefill, time to first token (TTFT) Defined in lesson 05; used here for how input length drives latency
KV cache Defined in lesson 04; used here for its memory cost and for prompt caching
Prompt caching The provider feature that reuses the KV cache of an identical prompt prefix across requests, at a lower price and latency. Self-hosted engines call it prefix caching; Google calls it context caching
Cache write / cache read Storing a prefix in the cache (sometimes charged extra) / reusing it (discounted)
Implicit vs explicit caching Caching the provider applies automatically vs caching you request or configure
Context stuffing Putting all available material into the prompt instead of retrieving selectively
Context engineering Deciding exactly which tokens the model sees for each request, in what order and format
Memory (application memory) Facts an application stores and re-injects into future prompts
RoPE, context extension Defined in lesson 04; summarized in 10.1
Thinking block The part of a reasoning model's reply that holds its hidden or summarized reasoning, plus a signature you send back unchanged (preview; defined in lesson 08)
Preserved thinking Current Claude models bind each thinking block to everything before it, so edited history plus replayed thinking is rejected (preview; full rules in lesson 08, 8.2)
Long decode A Gemini 4 Argon feature that writes one answer longer than the per-request output cap in several sequential hops
Input tokens per minute (ITPM) Anthropic's rate limit on input tokens; cache reads don't count towards it on most Claude models
Just-in-time retrieval Keeping references (paths, IDs) in context and loading content through tools only when needed
Sub-agent (context isolation) A separate model call or agent with its own fresh context that returns only a short summary

All terms are also collected in the glossary.


Exercises#

Run the code from this lesson and experiment:

  1. Hidden tokens (1.4): add a tool-call-style message, a long system prompt and ten short turns to the message list. How does the template overhead grow per message? Then remove the system message entirely and print the prompt again: Qwen2.5's template injects its own default system prompt ("You are Qwen, created by Alibaba Cloud. You are a helpful assistant."), a local example of the "text some providers inject" row in 1.3. Finally, load a different chat model's tokenizer (for example HuggingFaceTB/SmolLM2-135M-Instruct) and compare its template.
  2. Statelessness (3.2): change call 3 so the history contains a false earlier exchange (for example the assistant "said" your name is Arjun). What does the model answer, and what does this tell you about who controls the history?
  3. History manager (4.4): add support for tool calls: messages with role: "tool" must stay attached to the assistant message that requested them. Write a test conversation that proves your version never sends an orphaned tool result.
  4. History manager (4.4): replace toy_summarizer with a real summarizer using the provider of your choice and a cheap model. Write the summary prompt so it preserves names, numbers and decisions exactly, then test it on a 40-turn conversation.
  5. Needle test (5.4): make the test harder: phrase the question with no words in common with the needle (for example ask for "the number needed to unlock the azure entrance"), add a distractor ("The secret code for the red door is 9051."), or hide two needles and ask for both. How do the results change?
  6. Cost calculator (6.1): plug in the current prices of two real models from their pricing pages. At how many turns does a conversation cost 10× its first turn? Add a sliding window of 10 turns: how much does it save, and what does it do to caching?
  7. Prefill (6.3): extend the measurement to 16K tokens (and 32K if your machine has plenty of memory). Plot prefill time against input length. Is the growth closer to linear or quadratic at these sizes, and why?
  8. KV cache (7.1): look up the config.json of an open model you might deploy (layers, num_key_value_heads, head dimension) and use the formula in lesson 04, 11.4. How much KV cache would 50 concurrent users with 32K-token contexts need?
  9. Long context vs RAG (8.2): for a product idea of your own, write down the corpus size, question volume and task type, then use the back-of-envelope method in 8.2 to estimate monthly cost for both approaches.
Hints and what you should see
  1. Each message adds about five template tokens here (start marker, role name, newline, end marker, newline), plus a few for the final assistant prompt: with four messages the lesson's overhead was 23 tokens. Without a system message, the printed prompt starts with Qwen's default system block. Other tokenizers use other markers, so compare the rendered strings.
  2. A 0.5B model is likely to go along with the invented history and answer "Arjun" (small models are easily steered; try it and see). The model cannot tell real history from constructed history, so whoever builds the message list controls what the model "remembers". That is also a security point: never let user-supplied text decide which turns appear as assistant turns.
  3. Treat an assistant message with tool calls and the tool results that answer it as one unit, and keep or drop whole units. Your test should include a conversation where the budget falls exactly between a tool call and its result, and assert that no tool message comes first in the output.
  4. Ask the summarizer to copy names, numbers, IDs and decisions verbatim, to list open questions, and to state what it was unsure about. Check the result against the pinned facts and against two or three questions that only the early turns can answer.
  5. Expect more misses than in the easy test, and expect the distractor and two-needle variants to be the hardest. One run per cell is noisy: repeat with several seeds before drawing conclusions.
  6. With the lesson's example numbers (1,500 system tokens, 100 user, 400 reply, $2 / $10 per million), turn n costs about $0.0072 + $0.001 × (n − 1), so a turn reaches 10× the first turn at about turn 66. A 10-turn window caps the history at about 5,000 tokens, so the per-turn cost flattens near $0.017, but because the start of the history changes every turn only the fixed system prompt can still be cached.
  7. At these sizes expect a curve between linear and quadratic: the lesson's measurements grew about 7× for each 8× or 4× step in length. Attention's quadratic share grows with length, so the exponent creeps up as you go to 16K and 32K.
  8. KV bytes per token = 2 × layers × KV heads × head dimension × bytes per value. For Llama 3.1 70B in BF16 (80 layers, 8 KV heads, head dimension 128) that is 327,680 bytes, so 50 users × 32,768 tokens ≈ 1.64 million tokens needs about 537 GB just for the cache. Use your chosen model's config.json for your own answer.
  9. There is no single answer. Show your arithmetic, include the long-context surcharge if your corpus passes the provider's threshold, and say which quality risks you would test.

Check yourself#

  1. What does a model's context window count, exactly?
  2. A model has a 1,000,000-token window and you set the output budget to 64,000 tokens. Roughly how much input can you send? What else might reduce it?
  3. Name six things besides the user's message that consume the context window.
  4. Why did call 2 in the statelessness demo fail, even though it ran in the same process as call 1?
  5. Your app uses OpenAI's previous_response_id. Do you still pay for earlier turns? What does the feature actually save you?
  6. What's the difference between hitting the context window and hitting the output cap, in terms of how the API responds?
  7. Why is OpenAI's (now deprecated) truncation="auto" risky?
  8. Why should a history manager never keep an assistant message whose user question was dropped, or a tool result whose tool call was dropped?
  9. What is the "lost in the middle" effect, and how should it change where you place a long document and your question?
  10. Why does a near-perfect needle-in-a-haystack score overstate a model's long-context ability? Give two reasons.
  11. A 50-turn chat re-sends its history every turn. Why does total cost grow faster than the number of turns?
  12. What is prefill, and why does it make long prompts slow to start answering?
  13. Why must a prompt prefix be exactly identical for prompt caching to work?
  14. Your system prompt starts with "Current time: 14:32:07". What does this do to caching, and how would you fix it?
  15. You have a 2,000-page knowledge base that changes daily, with per-user access rules. Long context or RAG? Why?

Further resources#


← 02.6 — How LLMs Are Trained | Module 02 overview | 02.8 — Reasoning Models →

Esc
02.2Tokens and TokenizationHow LLMs Work · 21k wordsLesson
02.3EmbeddingsHow LLMs Work · 18k wordsLesson
07Retrieval-Augmented Generation (RAG)11 lessons · Everyone who will build LLM features that must answer from knowledge the model doesn't have in its weights: internal handbooks and help centres, contracts, ticket histories, product docs, or any corpus that changes faster than a training run. The module covers the full RAG stack — architecture, retrieval strategy, query understanding, grounded generation, citations, conversation, managed services, advanced patterns, evaluation, debugging and production operation — and shows where each major provider's managed retrieval and citation features fit (OpenAI, Anthropic, Google Gemini and OpenRouter). All code is Python.Overview
08E.1The Model Context Protocol (MCP)Protocols and Extensibility · 12k wordsLesson
↑ ↓ navigate↵ openesc close