The model only knows what you show it.
One guide from "what is a context window" to running context pipelines for a million people. How the window really works, every layer that goes into it, instructions, tools, retrieval, memory and history, the four strategies (write, select, compress, isolate), caching, the ways contexts fail, evaluation, security, system design, cost, scaling, and the trade-offs.
Pick where you are starting
Every chapter is tagged with a level. Choosing a path highlights the chapters to read first. Nothing is hidden.
What context engineering actually is
Context engineering is deciding what goes into the model's context window on every call: instructions, tools, examples, retrieved knowledge, memory, history and state. The goal is the smallest set of high-signal tokens that makes the right output likely. Prompt engineering is one part of it: writing the instructions well.
A language model has no memory between calls and no view of your systems. Everything it "knows" about your task on a given call is the text you send: the context. If the answer needs a fact that isn't in the context, the model guesses. If the context is full of noise, the model gets distracted. If two parts of the context disagree, the model picks one, and not always the one you meant.
In mid-2025 the industry started calling this job context engineering. Shopify's CEO Tobi Lütke described it as "the art of providing all the context for the task to be plausibly solvable by the LLM." Andrej Karpathy added that in real applications it is "the delicate art and science of filling the context window with just the right information for the next step." Anthropic's engineering team defines it as finding "the smallest possible set of high-signal tokens that maximize the likelihood of some desired outcome."
The word changed because the work changed. A 2023 chatbot sent one hand-written prompt. A 2026 agent builds a new context on every step of a loop, from a dozen sources, under a token budget, while keeping a cache warm and an attacker's text out of its instructions. That is engineering, not wordsmithing.
Prompt engineering versus context engineering
Prompt engineering versus context engineering
| Aspect | Prompt engineering | Context engineering |
|---|---|---|
| Unit of work | A prompt string | A pipeline that assembles context per call |
| Time scale | One call or one turn | Many calls, sessions, days; agents with 50–500 steps |
| Main skill | Clear writing, examples, structure | Information selection, budgeting, retrieval, memory, caching, systems design |
| Sources | Mostly static text | Instructions, tool schemas, RAG, memory stores, history, environment state, other agents |
| Failure looks like | Wrong tone, format drift | Missing facts, stale memory, distraction, contradictions, injection, runaway cost |
| Measured by | Output quality on examples | Task success, tokens per success, cache hit rate, latency, safety |
| Owner | Whoever writes the prompt | Engineering team, like any other data pipeline |
The mental model: the model is a CPU, the window is RAM
Karpathy's "LLM operating system" picture is the most useful one. The model is a processor that can only work on what is loaded into working memory. The context window is that memory: small, fast, and wiped after every call. Your job is the operating system: decide what to load, what to page out to disk, and what to keep resident.
The model
Fixed weights. Brilliant at using what it can see; cannot see anything else. Trained knowledge is old, generic and unverifiable.
The context window
Everything in the current call. Typically 128k to 1M+ tokens on frontier models in 2026, but quality and cost both get worse as it fills.
External stores
Files, databases, vector indexes, memory stores, logs. Unlimited, cheap, durable. Brought into the window only when needed.
The harness
Your code: the loop that builds the context, calls the model, runs tools and decides what to keep. This is where context engineering lives.
Prompt / KV cache
Providers reuse computation for an unchanged prefix. Stable content first means cheaper, faster calls.
Trust boundaries
Everything in context can steer the model. Untrusted text (web pages, emails, tool output) must be marked and contained.
When an LLM application fails, the cause is usually not that the model is too weak. It is that the model did not have the right information, had too much irrelevant information, or had it in a confusing shape. Before changing models, read the exact context the model saw on the failing call.
A short history, so the term makes sense
- 2020 · In-context learningGPT-3 shows that a few examples in the prompt can teach a task without training ("few-shot"). The prompt becomes a programming surface.
- 2022 · Prompt engineeringChain-of-thought, role prompts and templates. Windows are 2k–8k tokens, so every word is fought over.
- 2023 · Retrieval and memoryRAG goes mainstream. "Lost in the Middle" (Liu et al.) shows models miss facts buried mid-context. MemGPT treats context like virtual memory with paging. Windows grow to 32k–200k.
- 2024 · Long context and caching1M–2M token windows arrive. Gemini, Anthropic and OpenAI launch prompt or context caching. RULER and similar benchmarks show "effective" length is far below advertised length. MCP launches in November, making tools a new source of context.
- 2025 · "Context engineering" gets its nameThe term spreads in June. LangChain frames four strategies: write, select, compress, isolate. Drew Breunig names the ways long contexts fail. Manus publishes KV-cache-first lessons. Chroma's "Context Rot" report shows degradation across 18 models. Anthropic publishes "Effective context engineering for AI agents" and ships context editing, a memory tool and Agent Skills. Stanford's ACE paper treats context as an evolving playbook.
- 2026 · Context as infrastructureServer-side compaction, tool search and memory are standard in major SDKs. AGENTS.md-style project files are everywhere. Teams track cache hit rate and tokens per successful task as first-class metrics, and treat the context builder as a service with versioning, tests and owners.
The vocabulary you need
| Term | Plain meaning | Chapter |
|---|---|---|
| Token | The unit models read and bill by. About ¾ of an English word. | 2 |
| Context window | The maximum tokens (input + output) a model handles in one call. | 2 |
| Context rot | Quality dropping as the context gets longer, even below the limit. | 2, 15 |
| Effective context | The length at which a model still performs well on your task. | 2 |
| System prompt | Standing instructions at the start of the context. | 5 |
| Just-in-time context | Keeping references (paths, IDs) and loading content only when needed. | 7 |
| Memory | Information saved outside the window and brought back later. | 8 |
| Compaction | Summarising history so work can continue in a smaller context. | 12 |
| Context isolation | Giving a sub-task its own clean context (sub-agent, sandbox). | 13 |
| Prompt caching | Provider reuse of an unchanged prefix, billed at a discount. | 14 |
| Context poisoning | A wrong fact enters the context and is repeated as truth. | 15 |
| Prompt injection | Instructions hidden in content that the model treats as commands. | 18 |
How the context window really works
A context window is a budget, not a bucket. Every token costs money and time, every token competes for the model's attention, and models get measurably worse as context grows, well before the advertised limit. Bigger windows make more things possible, but they don't remove the need to choose.
Tokens: what the model actually reads
Models don't see characters or words. A tokenizer splits text into tokens: common words are one token, rare words are several, and spaces and punctuation count too. Everything is measured in tokens: the window size, the price, the speed.
| Content | Rough tokens | Notes |
|---|---|---|
| 1 English word | ≈ 1.3 | ~4 characters per token is a fair rule of thumb |
| 1 page of prose (500 words) | ≈ 650–700 | |
| Source code, 100 lines | ≈ 1,000–1,500 | Symbols, indentation and identifiers tokenise poorly |
| JSON record with 20 fields | ≈ 150–300 | Keys and quotes repeat on every record |
| Non-English text | 1.5–3× English | Varies a lot by language and tokenizer |
| One image | ≈ 500–2,000+ | Depends on resolution and provider |
| A 300-page book | ≈ 150,000–200,000 | Fits in many 2026 windows, which doesn't mean it should go in |
Always measure with the provider's token-counting endpoint or tokenizer. Tokenizers differ between model families, so the same text can vary by 10–30%.
What happens inside one call
In attention, every token looks at every earlier token to decide what matters. That is why models can connect a question at the end with a fact at the start. It is also why long contexts are expensive: prefill compute grows roughly with the square of input length, and the memory for the KV cache grows linearly with it. Providers pass those costs on through per-token pricing, long-context surcharges on some models, and slower responses.
Example, a 70B-class model (80 layers, 8 KV heads, head_dim 128, fp16): 2 × 80 × 8 × 128 × 2 B ≈ 320 KB per token
128k tokens ≈ 40 GB of GPU memory for one sequence. This is why long contexts are scarce and priced accordingly.
Context rot: longer is worse, even below the limit
Three findings should shape every design decision:
- Lost in the middle (Liu et al., 2023): when the answer sits in the middle of a long input, accuracy drops sharply compared with the start or the end. Performance plots as a U-shape.
- Effective length is shorter than advertised: benchmarks like RULER (NVIDIA, 2024) and NoLiMa (2025) found many models that claim 128k+ tokens fall well below their short-context scores by 32k–64k, especially when the question and the answer don't share obvious keywords.
- Context rot (Chroma, 2025): across 18 frontier models, performance on even simple tasks degraded as input length grew. Distractors that look similar to the answer hurt most, and coherent, well-structured haystacks sometimes hurt more than shuffled ones.
Anthropic calls this the attention budget: each new token depletes it a little. "Needle in a haystack" tests, where a single odd sentence is hidden in filler, are easy for modern models and can be misleading. Real tasks need several facts, connected by reasoning, among plausible distractors.
Live demo · position and length versus recall
An illustrative model of the shape reported in long-context studies: a U-curve by position that deepens as total length grows. Move the sliders to see where a key fact is safest. Real numbers depend on the model and the task; measure your own.
Why models degrade with length
Attention spreads thin
Attention weights over all tokens sum to one. More tokens means each relevant token gets a smaller share, and similar-looking distractors steal attention.
Less training at long lengths
Most training text is short. Models see far fewer examples of reasoning across 500k tokens, so long-range skills are weaker.
Position encoding stretched
Long windows are often reached by extending position schemes (for example RoPE scaling) beyond what the model was pre-trained on. It works, but with some loss in precision.
Primacy and recency
Models attend most to the start (instructions) and the end (the latest turn). The middle is where details go missing.
Treat roughly the first quarter to half of an advertised window as the comfortable working zone for multi-step reasoning, then test on your own tasks. Put what matters most at the start (stable instructions) and the end (the current question and a short goal reminder).
Windows, limits and the fine print
The numbers on the model card don't tell the whole story.
Input and output share the window limits
A 200k window with a 32k maximum output means your input must leave room for the output you ask for. Reasoning models also spend "thinking" tokens, which are output tokens and may count against the window during the call. Reserve output space explicitly in your budget (Ch 3 and 16), or long contexts will fail with truncated answers.
Long-context pricing tiers cost
Some providers charge a higher per-token rate once a request passes a threshold (for example above 200k tokens) or offer the largest windows only on certain tiers. A request that crosses the threshold can cost roughly double per token. Check your provider's pricing page and budget for it.
Why "needle in a haystack" scores mislead evaluation
The classic test hides one sentence that doesn't fit its surroundings, and asks for it by its own words. That is literal matching. Real tasks need semantic matching ("which customer is at risk?" when the text says "considering switching vendors"), multi-hop reasoning, and resistance to distractors. Build your own tests from your data (Ch 17).
Reasoning models and long context 2026
Thinking models do better at multi-hop questions over long inputs because they can restate and locate facts before answering. They don't remove context rot. They also add their own long outputs, which compete for the same budget across multi-turn conversations. Most APIs drop previous thinking blocks from history automatically, so check what your SDK keeps.
Anatomy of a context
A production context has about nine layers: system instructions, tool definitions, examples, long-term memory, retrieved knowledge, conversation history, tool results, current state, and the user's request, plus space reserved for the output. Each layer has its own size, change rate, owner and failure mode. Engineering the context means giving each a budget and a place.
The layers of one model call, from most stable to most volatile
Every layer, and what it forces you to decide
| Layer | Typical size | Changes | Key decisions | Common mistake |
|---|---|---|---|---|
| System instructions | 500–5,000 | Per release | Altitude, structure, priorities, escalation | A wall of rules with no priorities (Ch 5) |
| Tool definitions | 100–800 per tool | Per release or per task | How many tools, loaded when, described how | 50 tools always loaded, 30k tokens per call (Ch 6) |
| Examples | 200–3,000 | Per release | Which cases; how diverse | Ten near-identical examples the model copies |
| Long-term memory | 100–3,000 | Per session | What to load always vs on demand | Stale or wrong facts loaded forever (Ch 8) |
| Retrieved knowledge | 1,000–50,000 | Per turn | Top-k, reranking, chunk size, citations | Twenty loosely related chunks (Ch 7) |
| Conversation history | 0–100,000+ | Every turn | Window, summarise, or structured state | Appending forever until it breaks (Ch 9) |
| Tool results | 100–50,000 each | Every step | Shape, truncate, clear old ones | Raw 40k-token API dumps (Ch 12) |
| Current state | 50–1,000 | Every step | Plan, to-dos, goal reminder near the end | Putting a timestamp at the top, which breaks caching (Ch 14) |
| User request | 10–5,000 | Every turn | Place last; rewrite if vague | Burying the question above a long document |
| Reserved output | 1,000–64,000 | Per task | Max tokens, thinking budget | No headroom, so answers get cut off |
Live demo · compose a context and check the budget
Set the size of each layer. The bar shows how the window fills, the dashed line marks the "comfortable" zone, and the checks flag common budget problems.
The six questions for every model call
- What must the model know?Facts, documents, user details, current state. If a human expert would need it to do the task, the model needs it too.
- What can it do?Which tools, with what permissions. Only those relevant to this step.
- What has already happened?Decisions made, actions taken, errors seen. Summarised if old, verbatim if recent.
- What should it avoid?Constraints, policies, things already ruled out. Stated once, clearly, with the reason.
- What should it produce?Format, length, schema, audience. Shown with an example if it matters.
- What can be left out?Everything else. The most underused question: every irrelevant token is cost, latency and distraction.
How the shape differs by application
Same layers, very different proportions.
Chat assistant profile
Mostly system prompt, memory and history. The main problem is long conversations: history dominates after 30–50 turns. Use summary-plus-recent history and a small, curated memory profile.
RAG question answering profile
Retrieved knowledge is 60–90% of the context. Quality depends on retrieval precision, chunk ordering and citations. History is short. See the RAG Guide.
Tool-using agent profile
Tool definitions and tool results dominate, and context grows every step. Input-to-output token ratios of around 100:1 are common (Manus reported this). Caching, result shaping, clearing and compaction matter most.
Coding agent profile
Project instructions file (CLAUDE.md, AGENTS.md), file contents loaded just in time through search and read tools, test output, a to-do list. Sessions can run for hours, so compaction and notes to files are essential.
Voice agent profile
Strict latency (under about a second to first audio) means small contexts: short instructions, a compact customer record, a few tools. Retrieval must be fast or pre-fetched before the turn.
When context engineering matters most
A single-turn call with a short, fixed prompt needs good prompt writing and little else. Context engineering becomes the main job when you have many sources, many turns or steps, many users with different data, or untrusted content entering the window. Invest in the level of maturity your product actually needs.
The maturity ladder
| Level | What it looks like | Good enough for | Next problem you'll hit |
|---|---|---|---|
| 0 · Static prompt | One hand-written prompt string, maybe with a variable or two | Classification, extraction, simple rewriting | The model lacks facts about your business |
| 1 · Template + retrieval | Prompt template, top-k RAG chunks, last few turns | Document Q&A, support FAQ bots | Long chats, wrong chunks, no memory of the user |
| 2 · Managed session | History policy (summary + recent), user memory, tool definitions, prompt caching | Assistants, copilots, simple agents | Agents that run 30+ steps fill and rot the window |
| 3 · Dynamic per-step assembly | A context builder with per-layer budgets, just-in-time retrieval, result shaping, clearing, compaction, sub-agents | Production agents, coding agents, research agents | Knowing which change helped; cost at scale |
| 4 · Measured and self-improving | Context versions with evals, ablations, cost per success, playbooks the agent updates from experience | Platforms serving many teams and millions of users | Governance, multi-tenant isolation, drift |
Where it pays off the most
High leverage
- Agents with long loops: context grows every step; without management cost grows with the square of the steps and quality drops.
- Multi-source assistants: CRM + docs + tickets + email, where picking the right three facts is the whole job.
- Personalised products: memory and profile decide whether the answer fits this user.
- Regulated domains: you must show exactly what the model saw and why.
- High volume: at a million calls a day, 2,000 wasted tokens per call is real money.
Lower leverage
- One-shot tasks with all input provided (translate this, classify this).
- Prototypes where you don't yet know the task; get the use case right first.
- Tasks where a fine-tuned small model with a tiny prompt works better and cheaper.
- Workflows where code can compute the answer; don't make the model read what code can decide.
Signs you have a context problem, not a model problem
- It works in the playground but not in productionThe playground had a clean, short context. Production adds history, retrieval noise and tool output.
- Quality drops later in a conversation or runClassic context rot or history bloat (Ch 15).
- The model ignores an instruction it follows elsewhereThe instruction is buried, contradicted, or outweighed by examples.
- It confidently uses an outdated or wrong factStale memory, poisoned history, or a retrieved document from the wrong version.
- It calls the wrong tool, or invents oneToo many similar tools, vague descriptions, or tools removed mid-conversation.
- Costs climb faster than usageContexts are growing per call, or caching is silently broken (Ch 14).
The single most useful debugging habit: log the exact rendered context for every call (with redaction), and read it for failing cases. Most context bugs are obvious once you look. Chapter 19 shows how.
Instructions: system prompts at the right altitude
Good instructions sit at the right altitude: specific enough to guide behaviour, general enough to let the model use judgement. Too low and you get brittle if-else rules. Too high and you get vague advice the model can't act on. Organise them into clear sections, give a few diverse examples, and say why a rule exists.
The system prompt is the most stable and most cacheable part of the context, and the one the model gives the most weight to. It is also where most teams pile up years of patches: "ALWAYS do X", "NEVER do Y", "IMPORTANT: if the user says Z…". Each patch fixes one failure and quietly causes two others. Anthropic's guidance describes the target as the "right altitude": a zone between hard-coded logic and vague direction.
Live demo · the altitude of an instruction
The same refund policy written three ways. Pick one to see how a model tends to behave with it.
A structure that scales
Split instructions into labelled sections. XML-style tags or Markdown headings both work; what matters is that each section has one job and the model can tell where it starts and ends. Keep the order stable across releases so caching keeps working.
<role>
You are the billing assistant for Acme Cloud. You help account admins
understand invoices and fix billing problems.
</role>
<goal>
Resolve the admin's billing question in as few turns as possible, using
account data from tools. Accuracy beats speed: never guess an amount.
</goal>
<how_to_work>
- Look up the account and the relevant invoice before answering.
- Refunds up to $200 that match the policy below: issue them, then confirm.
- Above $200, or anything unusual: draft the refund and ask a human to approve,
because large refunds need finance sign-off.
- If you are unsure what the admin means, ask one short question.
</how_to_work>
<policy>
{refund_policy_v7} <!-- stable text, versioned -->
</policy>
<output>
Plain language, 2-5 sentences, amounts with currency. Cite invoice IDs.
</output>
<examples>
<example> … a duplicate-charge refund handled end to end … </example>
<example> … an ambiguous request where the assistant asks first … </example>
<example> … a $900 request routed for approval … </example>
</examples>Rules that hold up in production
| Do | Instead of | Why |
|---|---|---|
| Explain the reason: "keep replies short because users read on mobile" | "BE CONCISE!!!" | A reason lets the model generalise to cases you didn't list |
| Say what to do: "write in flowing paragraphs" | "Don't use bullet points" | Negative instructions name the thing you don't want and can prime it |
| State priorities: "safety, then accuracy, then speed" | Twenty rules of equal weight | Rules conflict; the model needs to know which wins |
| Use normal emphasis; reserve strong words for real hard limits | CRITICAL, MUST, ALWAYS in every line | Newer models follow instructions closely; shouting causes over-application |
| Give an escape hatch: "if unsure, ask" or "say you don't know" | Forcing an answer every time | Without one, the model invents to comply |
| Show 3–5 diverse, canonical examples | A long list of edge cases, or 10 near-identical examples | Examples are "pictures worth a thousand words"; similar ones get copied verbatim |
| Keep facts out of instructions; load them as data | Pasting prices and product lists into the system prompt | Facts change; instructions shouldn't need a release to update a price |
| Start minimal, add rules for observed failures | Writing every rule you can imagine up front | Each rule costs attention; add only what evals show you need |
The instruction hierarchy
Context contains text from different parties with different authority. Models are trained to follow an instruction hierarchy (OpenAI published the idea in 2024, and all major providers train for it): platform and system instructions outrank developer instructions, which outrank the user, which outrank anything that arrives as data (tool results, documents, web pages). Your context builder should make these boundaries obvious: separate roles, clear tags, and a stated rule that content inside data tags is information, not instructions. This helps, but it is not a security boundary on its own (Ch 18).
Live demo · system prompt linter
Paste a system prompt. The linter applies simple, explainable heuristics from this chapter. It runs in your browser and nothing is sent anywhere.
Instructions that live outside the system prompt
Context files, skills and reminders.
Project context files: CLAUDE.md, AGENTS.md, copilot-instructions.md pattern
Coding agents load a project file at the start of each session: build and test commands, conventions, architecture notes, gotchas. AGENTS.md became a cross-tool convention in 2025; Claude Code reads CLAUDE.md; GitHub Copilot reads .github/copilot-instructions.md and path-scoped *.instructions.md; Cursor reads rules files. Keep them short (a few hundred lines at most), specific ("run pnpm test --filter api", not "write good tests"), layered (global, repo, folder) and reviewed like code. Bloated context files are a top cause of agents ignoring instructions.
Skills: instructions loaded only when relevant progressive disclosure
Agent Skills (Anthropic, 2025, now supported by several tools) are folders with a SKILL.md file and optional scripts and references. Only each skill's name and one-line description sit in context. When a task matches, the agent reads the full instructions, and then any referenced files. Hundreds of skills cost only a few thousand tokens until used. This is just-in-time context applied to instructions.
Reminders near the end of long contexts attention
After 50k tokens of tool output, the system prompt is a long way back. A short reminder appended near the end ("Goal: X. Constraints: Y. Next: Z.") pulls the essentials into recent attention. Manus does this with a todo.md it rewrites each step ("recitation"). Keep reminders short and put them after the cached prefix so they don't break caching.
Treat prompts as code ops
- Store prompts in version control, not in a database edited by hand.
- Give each version an ID and log it with every call.
- Run the eval suite on every change (Ch 17).
- Roll out with a flag or canary, like any other release.
- Model upgrades are prompt changes too: re-run evals and remove rules the new model no longer needs.
Tools are context too
Every tool you expose costs tokens on every call, and every tool result lands in the context. Fewer, clearer tools beat many overlapping ones. Load tools on demand, shape results before the model sees them, and keep heavy data out of the window with handles and code execution.
Tools enter the context twice. First as definitions: a name, a description and a JSON schema for each one, sent with every request. Second as results: whatever the tool returns is appended and re-sent on every later step. In tool-heavy agents these two are usually the largest parts of the context.
Shape tool output before it enters the context
Definitions: how many tools, and when
| Technique | How it works | Use when | Watch out for |
|---|---|---|---|
| Small static tool set | 5–20 task-shaped tools always loaded | Most agents | Pressure to keep adding "just one more" |
| Tool search | A search tool finds and loads definitions on demand from a large catalog | Dozens to thousands of tools (big MCP setups) | An extra step; search quality now matters |
| Tool loadout (RAG over tools) | Your code retrieves relevant tools for each request before calling the model | Many tools, predictable per-request needs | Changing tools per call breaks the cache |
| Mask, don't remove | Keep all definitions stable; restrict choices with tool_choice, allow-lists or constrained decoding | State machines where available actions change | Needs provider support for forcing or restricting tools |
| Namespacing | Prefix related tools (browser_, crm_) so the model and masks can treat them as groups | Multiple MCP servers | Similar names across servers confuse the model |
| Agents as tools | Wrap a specialist agent with its own tools behind one tool | Broad domains | More tokens overall; less visibility |
Tool definitions usually sit near the start of the context. Adding or removing one changes the prefix, which invalidates the cache for everything after it. And if earlier history refers to a tool that's no longer defined, models get confused and may call tools that don't exist. Manus's advice: keep definitions stable and mask what's unavailable instead.
Results: shape them for a reader with limited attention
- Return meaning, not plumbing. Names and short readable IDs instead of UUIDs, MIME types and internal flags.
- Offer a response format. A
detail: "concise" | "full"parameter lets the agent ask for more only when needed. - Cap and paginate. Default to a sensible limit and say how to get more. Truncated output should say it was truncated.
- Errors that teach. "date must be YYYY-MM-DD; you sent 03/04" beats a stack trace.
- Return handles for big things. Write large outputs to a file or store, and return the path and a summary. The agent can read parts later.
- Count what matters. "Found 1,240 matches, showing 10" stops the model assuming it saw everything.
Code execution: keep intermediate data out of the window
When an agent calls tools one by one, every intermediate result passes through the context. Moving a 10,000-row spreadsheet from one tool to another means 10,000 rows in context, twice. With code execution the model writes a short script that calls tools as functions inside a sandbox, filters and joins the data there, and prints only the final result. Anthropic reported one example where this cut a workflow from about 150,000 tokens to about 2,000. Providers now offer "programmatic tool calling" for this; you can also build it with any sandbox.
Σ def_tokens × calls. 40 tools × 400 tokens × 30 calls = 480k input tokens (mostly cached, but still attention). Tool search with 5 loaded: ≈ 5/40 of that.- Provider SDKs (anthropic, openai, google-genai)Tool use, tool_choice to force or restrict, strict schemas; tool search and programmatic tool calling where offered.
- pydanticOne model for schema, validation and concise descriptions.
- mcp SDKExpose tools; set output limits and pagination in the server.
- tiktoken / count_tokensMeasure definition and result sizes in CI.
MAX_RESULT_TOKENS = 1500
def shape(rows, fields, total, next_hint):
"""Turn a raw API payload into something an LLM can use."""
slim = [{f: r.get(f) for f in fields} for r in rows[:10]]
out = {"showing": len(slim), "total": total, "rows": slim}
if total > len(slim):
out["more"] = next_hint # e.g. "call again with page=2"
text = to_compact_yaml(out)
if count_tokens(text) > MAX_RESULT_TOKENS:
ref = blob_store.put(rows) # keep the full data outside context
text = summarize_table(rows) + f"\n[full result saved as {ref}]"
return text- Foundry Agent Service tools + MCPAttach tools per agent; keep sets small per agent.
- Azure API Management (AI gateway)Front APIs as MCP tools with response transformation policies.
- Container Apps dynamic sessionsSandboxed code execution for programmatic tool use.
- Bedrock AgentCore GatewayTurns APIs and Lambdas into MCP tools; semantic tool search across large catalogs.
- AgentCore Code InterpreterSandbox to process data outside the context.
- LambdaLightweight result shapers in front of noisy APIs.
- Vertex AI function callingFunction declarations with modes to force or restrict calls.
- ADK tools + Agent Engine code executionBuilt-in sandboxed execution.
- Apigee / API hubGovern and shape APIs exposed to agents.
- FastMCPBuild MCP servers with typed tools and output limits.
- smolagents CodeAgentAgents that act through code.
- E2B · Daytona · ModalSandboxes for code execution.
- LangGraph ToolNodeWrap tools with post-processing.
Cloud product names and features change often. Treat these as pointers and confirm current availability, regions and pricing in each provider's docs.
Tool descriptions are prompts
The model picks tools by reading their descriptions.
Write descriptions like onboarding notes for a new colleague quality
Say what the tool does, when to use it and when not to, what the parameters mean (with formats), and what comes back. Unambiguous parameter names (user_id, not user) remove a whole class of errors. Anthropic's tool-writing guidance found small description changes produced large accuracy gains on benchmarks.
Overlap is the enemy confusion
If a human engineer can't say which of two tools to use, neither can the model. Merge overlapping tools, or make the boundary explicit in both descriptions. Studies of tool selection found smaller models in particular degrade sharply past a few dozen tools, and even frontier models make more wrong calls as the catalog grows.
MCP servers and context bloat MCP
Connecting five MCP servers can add 50–100 tools and tens of thousands of tokens before the user types anything. Enable servers per project or task, use tool search where available, and audit definition size. See the MCP Guide.
Retrieval and just-in-time context
There are two ways to bring knowledge in. Up-front retrieval (classic RAG) fetches likely-relevant chunks before the model runs. Just-in-time retrieval keeps lightweight references (paths, IDs, URLs) and lets the agent load content with tools when it decides it needs it. Most strong systems use both: a small up-front set, then exploration.
Up-front versus just-in-time
Coding agents showed the power of just-in-time context. Instead of indexing a codebase into vectors, tools like Claude Code give the model glob, grep, and a file reader with line ranges, plus a short project file. The agent navigates like an engineer: list folders, search for a symbol, read the 60 relevant lines. Folder names, file names and timestamps are themselves signals. Anthropic calls this progressive disclosure: each step reveals the context needed for the next.
Choose a retrieval mode
| Mode | Best for | Latency | Main risk |
|---|---|---|---|
| Up-front RAG (top-k chunks) | Q&A over documents; single-turn; latency-sensitive | Low | Irrelevant or missing chunks |
| Up-front + rerank + compress | Large corpora where precision matters | Medium | Reranker cost; over-aggressive compression |
| Agentic search (tools) | Codebases, investigations, multi-hop research | Higher | Wandering; many steps |
| Hybrid: small up-front set + tools | Most assistants and agents | Medium | Two systems to tune |
| Whole-corpus in context (CAG) | Small, stable corpora under ~100k tokens with caching | Low (cached) | Context rot; costs if cache misses |
| Structured lookup (SQL, APIs, graph) | Facts with exact answers: balances, statuses, relationships | Low | Query errors look plausible |
Making retrieved context high-signal
Fewer, better chunks
Retrieve wide (30–100 candidates), rerank, then keep the 3–8 best. Precision in the final context matters more than recall in the first search.
Contextualise chunks
A chunk that says "revenue grew 3%" is useless without the company and quarter. Anthropic's contextual retrieval (2024) prepends a short, generated description to each chunk before indexing and reported 49% fewer failed retrievals (67% with reranking).
Deduplicate and diversify
Five copies of the same paragraph from different pages waste budget and look like strong evidence. Remove near-duplicates; prefer coverage.
Order deliberately
Put the strongest evidence at the start or end of the retrieved block, not in the middle. Put the question after the documents.
Label everything
Wrap each chunk with source, title, date and an ID the model can cite: <doc id="7" source="policy.pdf" updated="2026-08">.
Filter by permission and freshness first
Apply access control and version filters before ranking, so the model never sees what the user can't, or a superseded policy.
k × chunk_tokens. Reciprocal rank fusion for hybrid search: score(d) = Σ 1 / (60 + rank_i(d)).- LlamaIndex · LangChain retrievers · HaystackHybrid retrieval, rerankers, node post-processors.
- Cohere / Voyage / Jina rerankers · bge-rerankerCross-encoder reranking.
- pgvector · Qdrant · Weaviate · Elasticsearch/OpenSearchVector and keyword search with filters.
def retrieved_block(query, user, budget=6000):
cands = hybrid_search(query, k=60, filters=acl_filter(user) & latest_only())
ranked = rerank(query, cands)[:12]
picked, used = [], 0
for c in dedupe(ranked, threshold=0.92):
t = count_tokens(c.text)
if used + t > budget:
break
picked.append(c); used += t
picked = strongest_at_edges(picked) # avoid burying the best evidence
return "\n".join(
f'<doc id="{i}" source="{c.source}" updated="{c.updated}">\n{c.text}\n</doc>'
for i, c in enumerate(picked, 1))- Azure AI SearchHybrid search, semantic ranker, security trimming, agentic retrieval.
- Foundry IQ / knowledge sourcesManaged knowledge for agents.
- Bedrock Knowledge BasesManaged ingestion, hybrid search, reranking, metadata filters.
- OpenSearch Serverless · KendraSearch back-ends.
- Vertex AI Search · RAG EngineManaged retrieval with grounding.
- Vertex ranking API · AlloyDB / BigQuery vector searchReranking and vector stores.
- ripgrep + file toolsThe agentic-search baseline for code and text.
- Qdrant · Milvus · Weaviate · pgvectorOpen vector stores.
- ColBERT / RAGatouille · bge-rerankerLate-interaction retrieval and rerankers.
Cloud product names and features change often. Treat these as pointers and confirm current availability, regions and pricing in each provider's docs.
Chunking, embeddings, vector stores, hybrid search and RAG evaluation are covered end to end in the RAG Guide. This chapter covers only what changes when retrieval is one layer of a larger context.
Memory: context that outlives the window
Memory is information written outside the context and read back later. It's how an assistant remembers a user across sessions and how an agent keeps its place across compactions. The hard parts aren't storage: they are what to write, when to read it, and when to forget.
Kinds of memory
| Kind | Holds | Example | Typical store | Loaded |
|---|---|---|---|---|
| Working | The current context | This conversation, this step's tool results | The context window | Always |
| Session / short-term | State of one task or conversation | Plan, to-do list, scratchpad notes | Session store, files | Every step of the session |
| Semantic | Facts and preferences | "Prefers metric units", "Account is on the Enterprise plan" | Key-value, vector, graph | Profile always; details retrieved |
| Episodic | Past events and outcomes | "Last migration failed on step 4 because of a lock" | Vector store, logs | Retrieved by similarity |
| Procedural | How to do things | Project instructions, skills, learned playbooks | Files (CLAUDE.md, SKILL.md), prompt store | Always (short) or on demand |
The memory lifecycle
Writing memory: hot path or background
The agent writes as it works
A memory tool (remember, or file edits to a /memories folder) the model calls when it learns something. Immediate and transparent, but adds latency and depends on the model's judgement. Good for explicit "remember that…" requests and agent notes.
A separate process extracts
After a session, a job reads the transcript, extracts candidate facts, and reconciles them with existing memory (add, update, delete, ignore). No user-facing latency and easier to curate, but memories appear later. Good default for user profiles.
Reading memory: three patterns
- Always loadedA short profile or project file (a few hundred tokens) in the stable prefix. Cheap, cacheable, and used every turn. Keep it small and current.
- Retrieved per turnYour code searches memory with the current request and injects the top few items, labelled with their date and source.
- Agent-directedThe agent has a memory tool and decides when to look things up, like Anthropic's file-based memory tool or Letta-style archival memory. Most flexible; needs good tool descriptions.
score = α · similarity(query, memory) + β · e−age/τ + γ · importance
- Anthropic memory tool + context editingFile-based memory the agent manages; old tool results cleared automatically.
- OpenAI Agents SDK sessionsSession history storage and trimming.
- Mem0 · Zep (Graphiti) · LangMem · LettaExtraction, consolidation and retrieval layers.
def memory_block(user_id, query, budget=800):
profile = kv.get(f"profile:{user_id}") # always loaded, small
hits = mem.search(query, user_id=user_id, k=8) # semantic + episodic
hits = [h for h in hits if not h.expired and h.confidence >= 0.6]
lines, used = [], count_tokens(profile)
for h in sorted(hits, key=lambda h: h.score, reverse=True):
line = f"- {h.text} (noted {h.date:%Y-%m}, source: {h.source})"
if used + count_tokens(line) > budget:
break
lines.append(line); used += count_tokens(line)
return (f"<user_profile>\n{profile}\n</user_profile>\n"
f"<relevant_memories>\n" + "\n".join(lines) + "\n</relevant_memories>")- Foundry Agent Service memory / threadsManaged conversation state and memory features.
- Cosmos DB (vector + document)Profiles, episodes and vectors in one store.
- Bedrock AgentCore MemoryShort-term events and long-term extracted memories with strategies.
- DynamoDB · OpenSearchProfile and episodic stores.
- Vertex AI Agent Engine Memory BankManaged long-term memory generation and retrieval.
- Firestore · AlloyDBProfiles and vectors.
- Mem0 · Graphiti · Letta · LangMemOpen-source memory layers.
- Postgres + pgvector · RedisSimple, durable building blocks.
Cloud product names and features change often. Treat these as pointers and confirm current availability, regions and pricing in each provider's docs.
Memory that helps instead of haunts
The failure modes are subtle and often reported by users, not tests.
Unwanted recall product
A remembered detail shows up where it doesn't belong: an old location in an unrelated image request, a past project in a new client's draft. Users find this creepy. Scope memories by purpose, show users what's remembered, and let them edit or turn it off.
Conflicts and staleness quality
"Works at Acme" (2024) and "Joined Globex" (2026) can both be stored. Store dates and validity periods, prefer newer facts, and let consolidation mark old facts as superseded instead of deleting history. Temporal knowledge graphs (Zep/Graphiti) model this directly.
Memory poisoning security
If a web page or email can get the agent to "remember" an instruction, that instruction comes back in every future session. Never let untrusted content write memory directly; validate writes, keep provenance, and separate user-stated facts from inferred ones (Ch 18).
Evolving playbooks (ACE) research
The ACE paper (Agentic Context Engineering, 2025) treats procedural memory as a playbook that grows by small, itemised updates from a generate-reflect-curate loop. It warns about brevity bias (summaries that drop domain detail) and context collapse (repeated full rewrites that erode knowledge), and recommends delta edits over rewrites.
Conversation history and agent state
History is the layer that grows without limit, so it needs a policy, not a default. Store the full record outside the model as an event log, and render a purpose-built view of it into each context: recent turns verbatim, older ones summarised, and current state (plan, to-dos, decisions) as a structured block near the end.
History policies compared
| Policy | What the model sees | Good for | Loses |
|---|---|---|---|
| Full history | Every message and tool result | Short sessions | Nothing, until it overflows or rots |
| Sliding window | The last N turns or tokens | Casual chat | Early goals and decisions |
| Summary + recent | A running summary, plus the last few turns verbatim | Long chats, assistants | Details the summary dropped |
| Tool-result clearing | All turns, but old bulky tool outputs replaced by a placeholder | Agents | Old raw data (re-fetchable) |
| Structured state | A state object (goal, plan, facts, open questions) instead of raw turns | Workflows and long agents | Nuance not captured in the schema |
| Event log → custom render | Your own compact rendering of typed events | Production agents | Whatever you choose not to render |
Own your context window: event log in, rendered view out
This idea comes from the "12-Factor Agents" principles ("own your context window") and from teams like Manus: the transcript your framework keeps by default is just one possible rendering. Typed events let you choose per type: keep errors (so the model doesn't repeat a failed action), drop chatter, collapse ten similar tool calls into one line, and always re-render the state block last.
RENDER = {
"user_message": lambda e: f"User: {e.text}",
"tool_call": lambda e: f"→ {e.name}({short_args(e.args)})",
"tool_result": lambda e: e.shaped if e.recent else f"[{e.name} result cleared; re-run if needed]",
"error": lambda e: f"✗ {e.name} failed: {e.message}", # keep errors in view
"decision": lambda e: f"Decision: {e.text} (because {e.reason})",
"human_approval": lambda e: f"Human {e.verdict}: {e.note}",
}
def render_history(events, budget):
recent_from = max(0, len(events) - 30)
for i, e in enumerate(events):
e.recent = i >= recent_from
old, new = events[:recent_from], events[recent_from:]
parts = [summary_of(old)] if old else [] # cached summary, refreshed rarely
parts += [RENDER[e.type](e) for e in new]
parts.append(render_state()) # plan + to-dos, always last
return fit_to_budget(parts, budget) # drop oldest recent items firstThree tricks from production agents
Rewrite the plan at the end
Re-render the to-do list as the last block each step. It keeps the goal in recent attention after long tool outputs and reduces drift on 50+ step tasks.
Leave the wrong turns in
Removing failed attempts makes the model try them again. A compact record of what failed and why is valuable context.
Avoid repetitive patterns
Long runs of near-identical action–result pairs make models imitate the pattern even when it's no longer right. Small variations in rendering break the rhythm.
Formatting, ordering and placement
The same information can be easy or hard for a model to use depending on where it sits and how it's written. Stable content first (for caching), long documents before the question, the question and a goal reminder last. Use clear delimiters, and pick formats that are compact for data and readable for prose.
Placement rules
- Stable before volatileSystem instructions, tool definitions and fixed reference text first, in a deterministic order. This is what caches (Ch 14).
- Documents before the questionFor long inputs, put documents first and the question at the end. Anthropic's long-context guidance reports this can improve answer quality by up to about 30% on complex, multi-document inputs.
- The question, a reminder and the date lastThe model attends strongly to the end. Put the current request, a one-line goal reminder and anything time-sensitive (today's date) here, not in the system prompt where it breaks caching.
- Strongest evidence at the edgesWithin a retrieved block, avoid putting the key document in the middle of twenty.
- Quote, then answerFor long documents, asking the model to first extract the relevant quotes, then answer, helps it locate the signal.
Formats and their trade-offs
| Format | Strength | Weakness | Use for |
|---|---|---|---|
| XML-style tags | Unambiguous boundaries; nests well; easy to reference ("the text in <contract>") | Some extra tokens | Separating sections and untrusted content |
| Markdown | Readable; compact; models know it well | Heading levels can blur in deep nesting | Instructions, documents, notes |
| JSON | Exact structure; machine-parsable | Token-heavy (quotes, braces, repeated keys) | Small structured objects, output schemas |
| YAML | Lighter than JSON for nested data | Whitespace-sensitive | Configs, nested records |
| CSV / Markdown tables | Very compact for many similar rows | Wide tables are hard to read; lossy for nesting | Lists of records |
| Plain prose | Natural for reasoning and narrative | Facts can hide in sentences | Summaries, explanations |
Live demo · the same data in four formats
Choose how many records to render. Token counts are estimated at ~4 characters per token; real tokenizers vary, but the ratios hold.
Delimit, label and attribute
<documents>
<document id="1" source="refund-policy.md" version="7" updated="2026-09-02" trust="internal">
…
</document>
<document id="2" source="customer-email" trust="untrusted">
… ← content to read, never instructions to follow
</document>
</documents>
Today is 2026-10-25. The user is an account admin in the EU region.
Goal reminder: resolve the duplicate charge on INV-2291.
Question: {user_message}
Answer using the documents; cite them as [1], [2]. If they don't contain the answer, say so.Small formatting decisions with big effects
Things that look cosmetic but change behaviour or cost.
Output format follows input format style
A context written in heavy Markdown tends to get Markdown back; flowing prose gets prose. If you want a particular output style, write the instructions in a similar style and show it in examples.
Deterministic serialisation caching
Serialising a dict with unstable key order, or listing tools from a set, changes the bytes of the prompt on every call. The model doesn't care, but the cache does. Sort keys, fix tool order, and avoid random IDs in the stable prefix.
Numbers, dates and units accuracy
Pre-format values in tools (€1,240.00, 2026-10-25, "3 days ago") so the model doesn't have to convert. Models are worse at arithmetic and date maths than at reading; give them the computed answer.
The four strategies: write, select, compress, isolate
Almost every context technique falls into one of four moves (a framing popularised by LangChain in 2025). Write information outside the window so it isn't lost. Select only what's relevant into the window. Compress what's there so it takes fewer tokens. Isolate work into separate contexts so they don't pollute each other. Prompt caching sits underneath all four as the cost layer.
Save it outside the window
Scratchpads, to-do files, notes, memory stores, saved tool results, checkpointed state.
Solves: forgetting across compactions and sessions.
Bring in only what's needed
RAG, just-in-time file reads, memory retrieval, tool search and loadouts, skills.
Solves: missing facts and irrelevant noise.
Use fewer tokens for the same meaning
Compaction, summaries, tool-result clearing, trimming, result shaping, prompt compression.
Solves: window overflow, cost and context rot.
Split work into separate contexts
Sub-agents, sandboxes and code execution, state objects with fields hidden from the model.
Solves: one task's clutter degrading another.
Technique explorer
Every technique in this guide, with how it works, when to use it, its costs and how to implement it. Filter by strategy or search; the table below compares them all.
From symptom to strategy
| Symptom | Likely strategy | First technique to try |
|---|---|---|
| Agent forgets the goal after a long run | Write + compress | To-do file with recitation; compaction that keeps the goal |
| Answers miss facts that exist in your data | Select | Better retrieval (rerank, contextual chunks) or a search tool |
| Cost per task grows faster than steps | Compress + cache | Tool-result clearing; fix cache breakers |
| Wrong tool chosen among many | Select | Tool search or a smaller task-shaped tool set |
| Research sub-tasks pollute each other | Isolate | Parallel sub-agents that return condensed findings |
| Huge data passes through the model | Isolate | Code execution in a sandbox; return handles |
| Assistant doesn't remember the user | Write + select | Background memory extraction + small profile in prefix |
Compression: compaction, clearing and summaries
Start with the cheapest, safest compression: shape tool results and clear old ones. Add compaction (summarise and restart from the summary) when runs outgrow the window. Trigger it early, at 50–80% of the window, and test what survives, because a summary that drops one key fact can sink the rest of the task.
The compression ladder, cheapest first
| Technique | How | Typical saving | Information risk | Cost |
|---|---|---|---|---|
| Result shaping | Return only needed fields and rows from tools | 50–95% per result | Low | Code only |
| Tool-result clearing | Replace old tool outputs with a placeholder; keep the call record | 40–80% of agent context | Low (re-fetchable) | Code only |
| Observation masking | Hide old observations but keep the agent's reasoning and actions | Similar to clearing | Low | Code only |
| Trimming | Drop oldest turns beyond a token limit | Bounded | High (early goals) | Code only |
| Running summary | Summarise turns older than N into one block, updated incrementally | 70–90% of old history | Medium | One small model call |
| Compaction | At a threshold, summarise everything into a brief and restart the context from it | 80–95% at each compaction | Medium | One model call |
| Token-level prompt compression | Drop low-information tokens with a small model (LLMLingua family) | 2–20× | Medium; text becomes terse | Small model pass |
A 2025 study of software-engineering agents ("The Complexity Trap", JetBrains Research and others) found that simply masking old observations matched or beat LLM summarisation on cost and solve rate in most settings. Anthropic reported that automatic tool-result clearing plus a memory tool cut token use by 84% on a long agentic evaluation. Try clearing before you build clever summarisers.
Live demo · compaction simulator
An agent adds tokens every step. Watch the context size per step with and without management. The red line is the window; the green band is the comfortable zone.
What a compaction must keep
You are compacting the working context of an agent so it can continue in a fresh window.
Write a brief that lets a capable engineer who has NOT seen the history continue the task.
Keep, precisely:
1. The original goal, success criteria and constraints (verbatim where given).
2. Decisions made and the reason for each.
3. Current plan with status of each step (done / in progress / not started).
4. Facts discovered that are still needed: names, IDs, file paths, line numbers, values.
5. Things tried that failed, and why (so they are not retried).
6. Open questions and anything waiting on the user.
7. The exact next action.
Drop: raw tool output already summarised above, superseded drafts, pleasantries.
Do not invent progress. If something is uncertain, say so.
Output under {budget} tokens, using the headings above.Compaction in practice
- Write notes as you goAsk the agent to keep a progress file or memory updated. Compaction then has a reliable source, and the notes survive even a bad summary.
- Trigger earlyCompact at 50–80% of the window, so the summariser has room and the agent never works in the worst-quality zone.
- Keep the recent tailCarry the last few steps verbatim after the summary. The model needs fresh, concrete context to continue smoothly.
- Re-attach what's re-fetchable as handlesInstead of summarising a file's content, keep its path. The agent can re-read it.
- Prefer incremental updatesRepeatedly rewriting a summary from scratch erodes detail ("context collapse"). Append and edit items instead.
- Test survivalBuild eval cases that ask, after compaction, about facts established before it (Ch 17).
n·P + a·n(n+1)/2. With compaction every m steps back to size S: roughly n·(P + S) + a·n·m/2, linear in n.- Anthropic API context managementAutomatic tool-result clearing (context editing) and server-side compaction options; memory tool for notes.
- Claude Agent SDK · OpenAI Agents SDKBuilt-in compaction and session trimming.
- LangGraph trim_messages / SummarizationNodeTrimming and summary nodes.
- LLMLingua-2Token-level prompt compression.
def manage(ctx, window=200_000, at=0.6, keep_recent=8):
# 1. cheap: clear stale bulky tool results
for m in ctx.messages[:-keep_recent]:
if m.kind == "tool_result" and m.tokens > 500 and not m.cleared:
m.content = f"[{m.tool} result cleared. Re-run {m.tool} if needed.]"
m.cleared = True
# 2. expensive: compact only when still too big
if ctx.tokens() > at * window:
notes = read_file("progress.md") # agent-maintained notes
brief = llm(COMPACT_PROMPT, history=ctx.messages, notes=notes, budget=4000)
ctx.messages = [user_msg(f"<brief>\n{brief}\n</brief>")] + ctx.messages[-keep_recent:]
log_event("compaction", before=ctx.prev_tokens, after=ctx.tokens())
return ctx- Foundry Agent Service threadsTruncation strategy settings for managed threads.
- Microsoft Agent FrameworkChat history reducers (truncation and summarisation).
- Bedrock AgentCore MemoryStore full events; rebuild compact context from summaries.
- Strands Agents conversation managersSliding-window and summarising managers.
- ADK sessions and context compactionEvent history with compaction options.
- Agent Engine SessionsManaged history storage.
- LangGraph / LangMem summarisationRunning summaries.
- LettaAutomatic context window management with recall memory.
- LLMLingua (Microsoft)Open-source prompt compression.
Cloud product names and features change often. Treat these as pointers and confirm current availability, regions and pricing in each provider's docs.
Isolation: sub-agents, sandboxes and quarantine
Isolation gives a sub-task its own clean context. A sub-agent can read 50,000 tokens of search results and return a 1,500-token finding, keeping the lead agent's context focused. The price is more total tokens and lost nuance at the handoff. Isolate work that is independent and read-heavy; keep tightly coupled decisions in one context.
Context isolation with sub-agents
Anthropic's multi-agent research system is the best-documented example. A lead agent plans, spawns sub-agents in parallel, each with its own context and tools, and synthesises their condensed results. It beat a single agent by about 90% on their internal research evaluation, but used roughly 15× the tokens of a chat interaction. They found token usage alone explained most of the performance difference on a browsing benchmark: isolation works partly because it lets the system spend more tokens in parallel without any single context rotting.
Cognition (the team behind Devin) argued the opposite for coding in "Don't Build Multi-Agents" (2025): actions carry implicit decisions, and sub-agents that don't share full context make conflicting assumptions (one builds a Mario-style background, another a non-matching bird). Both are right for their domains. Research is broad and parallel; editing one codebase is deep and coupled.
When to isolate, when to share
| Isolate when | Share one context when |
|---|---|
| Sub-tasks are independent (search different sources, review different files) | Steps depend tightly on each other's choices |
| Work is read-heavy and the useful output is small | The output of each step is a change others must build on |
| Parallelism saves wall-clock time | Coherence of style or design matters |
| A sub-task handles untrusted content you want quarantined | The task fits comfortably in one window |
| Different tools or permissions are needed per sub-task | Budget is tight; you can't afford 3–15× tokens |
Other forms of isolation
Sandboxes and code
Keep data frames, images and large files in a sandbox; the model sees variables and printed summaries. Hugging Face's CodeAgent and programmatic tool calling work this way.
Hidden state fields
A state object with many fields, only some of which are rendered for the model at each step. The rest are for your code.
Quarantined reader
A model with no tools reads untrusted content and returns structured data; a privileged model acts on it (the dual-LLM and CaMeL patterns, Ch 18).
Writing a good sub-agent brief
Objective: Find current list prices for the three competitors below (EU, monthly, per seat).
Why it matters: feeds a pricing recommendation; accuracy over completeness.
Scope: official pricing pages and docs only; ignore reseller sites; prices valid after 2026-06.
Do not: estimate missing prices; visit more than 15 pages.
Tools: web_search, fetch_page.
Return (max 300 words): a table competitor | plan | price | currency | URL | date seen,
then 3 bullets of caveats. Mark anything uncertain.lead + Σ subagent_i; lead context ≈ own work + Σ condensed_i. Isolation trades total cost for a small, sharp lead context and parallel speed.- Claude Agent SDK sub-agentsEach with its own prompt, tools and context window.
- OpenAI Agents SDK agents-as-toolsCall a specialist and get back its final output only.
- LangGraph sub-graphs · ADK sub-agents · CrewAIIsolated state per node or agent.
import asyncio
async def research(question):
plan = await lead.plan(question) # list of briefs
results = await asyncio.gather(*[
run_subagent(brief, tools=brief.tools, max_tokens_out=1500)
for brief in plan.briefs])
# only condensed results enter the lead's context
findings = "\n\n".join(f"<finding task='{b.name}'>\n{r}\n</finding>"
for b, r in zip(plan.briefs, results))
return await lead.synthesize(question, findings)- Foundry connected agentsA main agent delegates to sub-agents.
- Microsoft Agent Framework orchestrationsConcurrent, sequential and handoff patterns.
- Bedrock multi-agent collaborationSupervisor with collaborator agents.
- Strands agents-as-toolsNested agents with separate contexts.
- ADK multi-agent (sub_agents, AgentTool, ParallelAgent)Isolated contexts with shared session state where needed.
- LangGraph supervisorPrebuilt orchestration.
- smolagents managed agentsAgents called by other agents.
- A2ADelegate to remote agents with their own context.
Cloud product names and features change often. Treat these as pointers and confirm current availability, regions and pricing in each provider's docs.
Prompt caching and the KV cache
When the start of your prompt is byte-for-byte the same as a recent call, providers can reuse the computation and charge a fraction of the price, often around 10% of the normal input rate for cached reads, with much faster time to first token. For agents, the cache hit rate is one of the most important production metrics. Design the context as a stable, append-only prefix.
How a prefix cache works across agent steps
How the major providers do it
| Provider | How you enable it | Cached-read price | Lifetime | Notes |
|---|---|---|---|---|
| Anthropic (API, Bedrock, Vertex) | Explicit cache_control breakpoints (up to 4), or automatic in some SDKs | ≈ 0.1× input | 5 minutes (refreshed on use); 1 hour option | Cache writes cost more (≈1.25× for 5 min, 2× for 1 h); minimum cacheable length applies |
| OpenAI | Automatic for prompts over ~1,024 tokens | Discount varies by model, roughly 50–90% off | Minutes, longer off-peak; extended options on some models | Optional prompt_cache_key improves routing to the same cache |
| Google Gemini | Implicit caching on recent models, plus explicit cached content with a TTL | Large discount on cached tokens | Implicit: short; explicit: you set the TTL | Explicit caches bill storage per hour |
| Self-hosted (vLLM, SGLang) | Automatic prefix caching / RadixAttention | Saves your GPU time | Until evicted from GPU memory | LMCache and similar can offload KV to CPU or disk |
Prices and limits change often; check current pricing pages. The design rules below hold regardless of provider.
Live demo · caching calculator and cache breakers
Set your traffic, then switch on common mistakes to see how they destroy the hit rate.
Rules for a cache-friendly context
- Stable first, volatile lastSystem prompt, tools, fixed reference docs, then session memory, then history, then the new turn.
- Append-only historyDon't edit or re-order earlier messages. If you must redact, do it before the message first enters the context.
- Deterministic serialisationSorted keys, fixed tool order, no random IDs, no timestamps in the prefix.
- Put breakpoints where layers endWith explicit caching, mark the end of tools, of the stable docs, and of the latest turn.
- Keep traffic warmCaches expire after minutes. Long-TTL options pay off for bursty traffic with big prefixes.
- Route to the same cacheSession affinity (or a cache key) so a user's calls land where their prefix is cached; self-hosted routers do prefix-aware routing.
- Measure itLog cached-read and cache-write tokens per call. A sudden drop in hit rate after a release is a bug.
price × (h·P·r + (1−h)·P·w + D), with P = prefix, D = dynamic tokens, h = hit rate, r = read multiplier, w = write multiplier.- anthropic SDK
cache_control: {"type": "ephemeral"}on blocks; usage reports cache_creation and cache_read tokens. - openai SDKAutomatic; read
usage.prompt_tokens_details.cached_tokens; setprompt_cache_key. - google-genaiImplicit caching, or
caches.createwith a TTL.
resp = client.messages.create(
model=MODEL,
max_tokens=2048,
system=[{"type": "text", "text": SYSTEM_PROMPT_V12, # stable
"cache_control": {"type": "ephemeral"}}],
tools=sorted(TOOLS, key=lambda t: t["name"]), # deterministic order
messages=history + [{"role": "user", "content": [
{"type": "text", "text": f"Today is {today}.\n{user_msg}", # volatile goes last
"cache_control": {"type": "ephemeral"}}]}],
)
u = resp.usage
metrics.observe("cache_hit_ratio",
u.cache_read_input_tokens / max(1, u.cache_read_input_tokens + u.cache_creation_input_tokens + u.input_tokens))- Azure OpenAI prompt cachingAutomatic on supported models; cached tokens reported in usage.
- API Management AI gatewaySemantic caching of whole responses (different from prompt caching).
- Bedrock prompt cachingCache checkpoints on supported models.
- Bedrock cross-region inferenceNote that routing can affect cache locality.
- Vertex AI context cachingImplicit and explicit caches for Gemini; Anthropic models on Vertex support prompt caching.
- vLLM automatic prefix cachingEnable with
--enable-prefix-caching(default on in recent versions). - SGLang RadixAttentionTree-structured prefix reuse.
- LMCache · llm-dKV offload and prefix-aware routing across replicas.
Cloud product names and features change often. Treat these as pointers and confirm current availability, regions and pricing in each provider's docs.
Caching beyond the basics
Where teams lose money without noticing.
Prompt caching is not response caching concepts
Prompt caching reuses the computation for a shared prefix; the model still generates a fresh answer. Response (or semantic) caching returns a stored answer for a similar question. Response caching is cheaper still but risky for personalised or changing answers. They stack.
Sub-agents and caching architecture
Each sub-agent with a different system prompt is a separate cache. Share a common prefix across sub-agent types where possible (same base instructions and tools, specialisation appended later).
Model switches reset the cache routing
Caches are per model. Routing alternate steps to a cheaper model can cost more than it saves if each switch re-processes a 50k-token prefix at full price. Route at task boundaries, not mid-run.
How contexts fail: rot, poisoning, distraction, confusion, clash
Drew Breunig's 2025 essay named four ways long contexts fail, and context rot adds a fifth. Poisoning: a wrong fact gets in and is reused. Distraction: so much history the model repeats itself instead of thinking. Confusion: irrelevant content (often tools) pulls the model off course. Clash: parts of the context contradict each other. Rot: quality decays as length grows. Each has a recognisable symptom and a standard fix.
A wrong fact becomes "truth"
Example: an agent hallucinates that a test passed, writes it in its notes, and builds on it for 40 steps. DeepMind's Gemini 2.5 report described a game-playing agent whose goals section got poisoned and pursued impossible goals.
Fix: verify claims with tools before recording them; separate observations from conclusions; let compaction drop unverified claims; restart from a clean checkpoint.
History outweighs reasoning
Example: past 100k tokens, an agent starts repeating earlier actions instead of planning new ones. The same Gemini report noted this tendency in long agent runs, and Databricks found correctness falling for some models well before their limits.
Fix: compaction, tool-result clearing, recitation of the plan, staying inside the effective window.
Irrelevant content gets used
Example: with 40 tools loaded for a weather question, the model calls a calendar tool. Berkeley's function-calling leaderboard shows models perform worse with more tools, and small models fail with dozens where they succeed with a few.
Fix: tool loadouts or search, fewer retrieved chunks, remove irrelevant sections, don't include "just in case" context.
The context disagrees with itself
Example: information arrives over several turns; the model commits to an early wrong guess and the corrections later clash with it. A 2025 Microsoft/Salesforce study found an average ~39% performance drop when the same task was split across multiple turns ("sharded").
Fix: consolidate requirements into one clear block; mark superseded info; for multi-turn, restate the full current task before acting; isolate sub-tasks.
Everything gets a bit worse as it gets longer
Even without bad content, recall, reasoning and instruction-following degrade with length (Ch 2). It's the background force behind the other four. Fix: budgets per layer, the comfortable zone, and every compression and isolation technique in this part.
Live demo · diagnose a context failure
Tick the symptoms you see. The diagnoser ranks likely failure modes and suggests where to look first.
The debugging routine
- Get the exact contextPull the fully rendered input for the failing call from traces (Ch 19). Not the template: the actual tokens.
- Check what was missingWas the fact the model needed present? If not, it's a selection problem.
- Check what was wrong or conflictingSearch the context for the bad claim and for contradictory statements.
- Check what was noiseMeasure each layer's tokens. Anything large and irrelevant is a suspect.
- Replay with editsRemove, move or fix one layer at a time and re-run the call. The smallest edit that fixes it tells you the cause.
- Turn it into a testAdd the case to your eval set so it never comes back.
Build a context pipeline end to end
Treat context assembly as a function with a budget: build_context(task, state) → messages. Inventory your sources, give each layer a token budget and a priority, render them in a fixed cache-friendly order, trim the lowest-priority content when over budget, and log a breakdown of every call. Then iterate with evals.
Step by step
- Define the task and the budgetWhat is one unit of work (a turn, a step)? What window, output reserve, latency and cost per call are acceptable? Write down the comfortable zone (e.g. 50% of the window).
- Inventory the sourcesFor each: where it comes from, how big it can get, how often it changes, who can see it, and whether it's trusted.
- Allocate budgets and prioritiesFixed layers get fixed budgets. Elastic layers (retrieval, history) get a share of what's left, with a priority for trimming.
- Render deterministicallySame inputs give the same bytes. Stable layers first. Tagged sections. Volatile content last.
- Fit to budgetIf over, trim in priority order: old tool results, then retrieval tail, then older history (summarise), never the system prompt or the current request.
- Manage over timeClearing and compaction for long runs; memory writes at session end.
- ObserveLog per-layer token counts, cache tokens, versions and IDs of everything included.
- Evaluate and iterateAblate layers, tune budgets, and track tokens per successful task.
A worked budget for a 200k-token agent
| Layer | Budget | Priority when trimming | Policy |
|---|---|---|---|
| System instructions | 3,000 fixed | Never trimmed | Versioned file; cached |
| Tool definitions | 8,000 fixed | Never trimmed mid-run | 12 tools + tool search; cached |
| Project / procedural memory | 2,000 fixed | Never trimmed | AGENTS.md-style file; cached |
| User memory | 1,000 | Low | Profile + top 5 memories |
| Retrieved knowledge | up to 20,000 | Medium: trim the tail | Rerank, dedupe, cite |
| History + tool results | up to 60,000 | High: clear, then summarise | Event log rendering; clear old results; compact at 100k total |
| State block + request | up to 4,000 | Never trimmed | Last in context |
| Output + thinking reserve | 16,000–32,000 | Reserved | max_tokens set per task |
| Comfortable ceiling | ≈ 100,000 | Half the window: leaves headroom and stays in the high-quality zone | |
The context builder
from dataclasses import dataclass, field
@dataclass
class Layer:
name: str
render: callable # () -> str, deterministic
budget: int # max tokens for this layer
priority: int # higher = trimmed first; 0 = never trim
cache: bool = False # end of a cacheable block?
trusted: bool = True
@dataclass
class BuiltContext:
system: list
messages: list
breakdown: dict = field(default_factory=dict)
class ContextBuilder:
def __init__(self, layers, ceiling, count=count_tokens):
self.layers, self.ceiling, self.count = layers, ceiling, count
def build(self, request: str) -> BuiltContext:
rendered = {}
for L in self.layers: # 1. render each layer
text = L.render()
if not L.trusted: # mark untrusted data
text = f"<untrusted_data source='{L.name}'>\n{text}\n</untrusted_data>"
rendered[L.name] = fit(text, L.budget, self.count) # per-layer cap
total = lambda: sum(self.count(t) for t in rendered.values()) + self.count(request)
for L in sorted(self.layers, key=lambda l: -l.priority): # 2. global ceiling
if total() <= self.ceiling or L.priority == 0:
break
rendered[L.name] = shrink(rendered[L.name], L, self.count) # clear / summarise / tail-trim
system, msgs = [], [] # 3. assemble in fixed order
for L in self.layers:
block = {"type": "text", "text": rendered[L.name]}
if L.cache:
block["cache_control"] = {"type": "ephemeral"}
(system if L.name in SYSTEM_LAYERS else msgs).append(block)
msgs.append({"type": "text", "text": request}) # request always last
breakdown = {n: self.count(t) for n, t in rendered.items()} | {"request": self.count(request)}
return BuiltContext(system, [{"role": "user", "content": msgs}], breakdown)Wiring it into an agent loop
def run(task, state, max_steps=60):
for step in range(max_steps):
state = manage(state, window=WINDOW, at=0.5) # clear + compact (Ch 12)
ctx = builder_for(state).build(render_state(state)) # plan + to-dos as the request
resp = call_model(ctx, max_tokens=OUTPUT_RESERVE)
trace.log(step=step, breakdown=ctx.breakdown, usage=resp.usage,
versions=state.versions, doc_ids=state.included_doc_ids)
if resp.stop_reason == "end_turn":
memory.extract_async(state.events) # background memory write
return resp.text
for call in resp.tool_calls:
result = shape(run_tool(call)) # Ch 6
state.events.append(ToolResult(call, result))
return escalate(state, reason="step budget exhausted")Agent SDKs (Claude Agent SDK, OpenAI Agents SDK, Google ADK, LangGraph, Microsoft Agent Framework) ship sessions, trimming, compaction and caching. Use them, but know what they put in the context: print one fully rendered request early and read it. You still own budgets, priorities and what's trusted.
Evaluating context
You can't improve context by intuition alone. Measure task success and tokens per successful task together, then use ablations (remove or change one layer, re-run) to learn what each piece is worth. Add targeted tests for long-context recall, compaction survival, ordering sensitivity and distractors, built from your own data.
What to measure
| Metric | Question it answers | How |
|---|---|---|
| Task success rate | Does it work? | Outcome checks: tests pass, answer matches, judge with rubric |
| Tokens per successful task | Is it efficient? | Total input + output tokens ÷ successes |
| Cost and latency per task | Can we afford it at scale? | From usage and traces, p50 and p95 |
| Context precision | How much of what we included was useful? | Judge or labels: fraction of included items relevant to the answer |
| Context recall | Did we include what was needed? | Labelled required facts present in context |
| Faithfulness / groundedness | Did the answer stick to the context? | Claim-level check against included sources |
| Cache hit rate | Is the layout stable? | Cached-read ÷ total input tokens |
| Compaction survival | Do key facts survive compaction? | Questions about pre-compaction facts, asked after |
| Position sensitivity | Does order change results? | Shuffle or move a key document; compare scores |
| Distractor robustness | Do near-miss documents fool it? | Inject similar but wrong passages |
Ablations: the most informative experiment
Run the same eval set several times, each with one change: drop the examples, halve the retrieval budget, remove memory, move the documents after the question, swap JSON for YAML. Plot success and tokens. Layers that cost a lot and change nothing are candidates for removal; layers whose removal hurts badly deserve more care. Run each configuration several times: model outputs vary, and differences of a few points on 50 cases are often noise.
VARIANTS = {
"baseline": {},
"no_examples": {"examples.budget": 0},
"retrieval_half": {"retrieval.budget": 10_000},
"no_memory": {"memory.budget": 0},
"docs_after_q": {"order": "question_first"},
"clear_results": {"clear_after_steps": 8},
}
def ablate(cases, runs=3):
rows = []
for name, cfg in VARIANTS.items():
for case in cases:
for r in range(runs):
out = run_agent(case.task, config=cfg, seed=r)
rows.append({"variant": name, "case": case.id,
"ok": case.check(out.answer),
"tokens": out.usage.total, "cost": out.cost})
df = pd.DataFrame(rows)
s = df.groupby("variant").agg(success=("ok", "mean"), tokens=("tokens", "mean"))
s["tokens_per_success"] = s.tokens / s.success.clip(lower=1e-9)
return s.sort_values("tokens_per_success")Targeted context tests
Needles from your own data
Plant 2–3 real facts that must be combined, at different depths, in realistic filler from your domain, with similar-looking distractors. Sweep length to find your model's effective window for your task.
Compaction regression
Script a long run that establishes facts early ("the customer ID is C-4471", "we ruled out the cache"), force compaction, then ask about them. Track survival rate per compaction prompt version.
Multi-turn sharding
Give the same task in one turn and split across five turns. A large gap means the model commits early; fix with restatement or a requirements block.
Injection in context
Include documents and tool results with embedded instructions. Pass means the model treats them as data (Ch 18).
1.96 · √(s(1−s)/N). At s = 0.8 and N = 100: about ±8 points. Compare variants on the same cases (paired) to reduce noise.- RagasContext precision, context recall, faithfulness.
- DeepEval · promptfooTest cases, LLM judges and CI assertions.
- inspect-aiAgent evals with sandboxes and scorers.
- LangSmith · Langfuse · Braintrust · PhoenixExperiments over traces and datasets.
- Foundry evaluationsGroundedness, relevance, retrieval and agent evaluators; CI integration.
- Bedrock evaluationsModel and RAG evaluation jobs with judges.
- AgentCore Evaluations / ObservabilityOnline and offline agent quality signals.
- Vertex AI Gen AI evaluation servicePointwise and pairwise metrics; agent trajectory evaluation.
- RULER · NoLiMa · LongBenchPublic long-context benchmarks for model selection.
- Ragas · DeepEval · promptfoo · OpenAI evalsOpen-source eval tooling.
Cloud product names and features change often. Treat these as pointers and confirm current availability, regions and pricing in each provider's docs.
Security: everything in context is a potential instruction
A model can't reliably tell your instructions from instructions hidden in a web page, email, document or tool result. So any untrusted text in the context can steer the model. Defend with structure (mark and isolate untrusted content), least context (don't load secrets or data the user can't see), and least privilege (enforce permissions in tools, never in prompts).
Trust zones inside one context
Threats that arrive through context
| Threat | How it happens | Defence |
|---|---|---|
| Indirect prompt injection | A retrieved page or email says "ignore previous instructions and…" | Mark untrusted content; limit tools after reading it; deterministic policy on actions; dual-model / CaMeL designs |
| Data exfiltration | Injected text makes the model put secrets in a URL, image link or outgoing message | Break the lethal trifecta (private data + untrusted content + outbound channel); block untrusted URLs and image rendering; egress allow-lists |
| Cross-user leakage | Retrieval or memory returns another user's data | Filter by permissions before ranking; per-user memory namespaces; tests with two accounts |
| Secret leakage | API keys, tokens or internal URLs placed in the context get repeated | Never put credentials in context; tools hold secrets server-side |
| Memory poisoning | An injected instruction is saved to memory and returns in every session | No memory writes from untrusted sources; validation and provenance on writes; review and expiry |
| Tool-description poisoning | A third-party MCP server's tool description hides instructions | Vet and pin servers; scan descriptions; show users what changed |
| System prompt extraction | Users coax the model into revealing instructions | Assume the prompt is public; keep secrets and business logic out of it |
| Shared-cache side channels | Timing differences reveal whether a prefix was recently cached by someone else | Use providers that isolate caches per organisation; don't share caches across tenants in self-hosted setups |
Structural defences, in order of strength
- Don't put it in the contextThe strongest defence. Data the model never sees can't leak; tools the agent doesn't have can't be abused.
- Enforce permissions outside the modelEvery tool call checked by deterministic policy with the user's identity. The prompt can be talked around; the policy can't.
- Isolate untrusted readingA quarantined model with no tools extracts structured fields from untrusted text; a privileged planner never sees the raw text (dual-LLM, CaMeL).
- Reduce capability after exposureOnce untrusted content enters a context, disable outbound and write tools for the rest of that run, or require approval.
- Mark and delimitWrap untrusted content in labelled tags, and state that it's data. Microsoft's "spotlighting" research (delimiting, datamarking, encoding) showed this lowers attack success. It helps; it isn't sufficient on its own.
- DetectInjection classifiers on inputs and outputs. One more layer, with known false negatives.
- OPA (Rego) · CedarDeterministic allow/deny for tool calls.
- PresidioDetect and redact PII before it enters context.
- Llama Prompt Guard · Lakera · NeMo GuardrailsInjection detection and rails.
- garak · PyRIT · promptfoo red teamAdversarial testing.
class Run:
tainted = False # has untrusted content entered this context?
def add_tool_result(run, tool, result):
if tool.returns_untrusted: # web fetch, email read, file upload…
run.tainted = True
result = f"<untrusted_data source='{tool.name}'>\n{redact(result)}\n</untrusted_data>"
run.events.append(ToolResult(tool.name, result))
def authorize(run, user, tool, args):
if not policy.allows(user, tool, args): # identity-based, deterministic
return Deny("not permitted for this user")
if run.tainted and tool.side_effect in {"send", "write", "pay"}:
return RequireApproval("untrusted content in context")
return Allow()- Azure AI Content Safety Prompt ShieldsDetects direct and document-based injection.
- Microsoft PurviewData classification and DLP for AI apps.
- Entra Agent IDIdentities and access for agents.
- Bedrock GuardrailsPrompt-attack filters, PII redaction, contextual grounding checks.
- AgentCore Identity · Cedar policiesDelegated access and policy on tool calls.
- Model ArmorPrompt-injection, jailbreak and sensitive-data screening.
- Sensitive Data Protection (DLP)Redaction before context.
- CaMeL reference designCapability-tracked dual-model architecture.
- Rebuff · LLM GuardOpen-source detectors.
- OWASP GenAI Top 10 (LLM and agentic)Threat checklists.
Cloud product names and features change often. Treat these as pointers and confirm current availability, regions and pricing in each provider's docs.
Observability: see the exact context
For every model call you should be able to answer: what exactly did the model see, how big was each part, which versions and documents were in it, and what did it cost? Log a per-layer token breakdown, cache tokens, versions and IDs on every span, and keep the rendered context (redacted) for sampled and failing calls.
What to record on every call
| Field | Example | Why |
|---|---|---|
| Per-layer token counts | system 2,910 · tools 7,850 · retrieval 12,400 · history 41,200 · request 180 | Find the layer that's growing or bloated |
| Usage from the provider | input 64,540 · cache_read 52,000 · cache_write 0 · output 820 | Cost and cache health |
| Versions | prompt v12 · tools v5 · compaction prompt v3 · model id | Tie regressions to changes |
| Included item IDs | doc ids [7, 19, 22] · memory ids [m-881] · tool list hash | Reproduce and explain an answer |
| Context events | compaction at step 41 (148k → 9k) · 12 results cleared | Correlate quality drops with management events |
| Rendered context (redacted) | Stored for sampled, flagged and failed calls | Read what the model actually saw |
| Trust state | tainted=true after step 6 (web_fetch) | Security audits |
from opentelemetry import trace
tracer = trace.get_tracer("context")
with tracer.start_as_current_span("chat " + MODEL) as span:
span.set_attribute("gen_ai.request.model", MODEL)
for layer, n in ctx.breakdown.items():
span.set_attribute(f"app.context.tokens.{layer}", n)
span.set_attribute("app.context.prompt_version", PROMPT_VERSION)
span.set_attribute("app.context.doc_ids", [d.id for d in docs])
span.set_attribute("app.context.tainted", run.tainted)
resp = call_model(ctx)
span.set_attribute("gen_ai.usage.input_tokens", resp.usage.input_tokens)
span.set_attribute("gen_ai.usage.output_tokens", resp.usage.output_tokens)
span.set_attribute("app.context.cache_read_tokens", resp.usage.cache_read_input_tokens)
if sampled() or flagged(resp):
blob = store_redacted(ctx) # keep the exact rendered input
span.set_attribute("app.context.blob", blob)The dashboard
Context size
p50 / p95 input tokens per call, by layer, over time. Growth after a release is the first sign of a bug.
Cache hit rate
Cached ÷ total input tokens. Alert on drops; agents usually should be above 70–80%.
Tokens per success
The efficiency metric that matters. Joins traces with outcomes.
Compactions per run
And quality before versus after. Spikes mean contexts are filling faster.
Truncations
Calls where the builder had to trim, and which layer lost content.
Overflow errors
Context-length errors and output cut-offs (stop reason = max tokens).
- OpenTelemetry + GenAI semantic conventionsStandard span names and gen_ai.* attributes; add your own app.context.* fields.
- OpenLLMetry · OpenInferenceAuto-instrumentation for SDKs and frameworks.
- LangSmith · Langfuse · Phoenix · Braintrust · W&B WeaveTrace UIs showing full prompts, tokens and costs.
- Foundry tracing + Application InsightsOpenTelemetry traces for agents and model calls.
- AgentCore Observability · CloudWatchOTel-compatible agent traces and dashboards.
- Bedrock invocation loggingFull request and response logs to S3 or CloudWatch.
- Cloud Trace · Vertex AI request-response loggingTraces and logged prompts for analysis in BigQuery.
- Langfuse · Arize Phoenix · OpenLITOpen-source LLM observability.
- Grafana + Tempo / JaegerTrace storage and dashboards.
Cloud product names and features change often. Treat these as pointers and confirm current availability, regions and pricing in each provider's docs.
System design: a context platform
At scale, context assembly becomes a shared service: a context orchestrator that, for each call, gathers instructions from a prompt registry, tools from a tool registry, knowledge from retrieval, facts from memory and history from a session store, applies policy and budgets, renders a cache-friendly request, and sends it through a model gateway. Every piece is versioned, observable and testable.
Reference architecture
Components and their contracts
| Component | Contract | Scaling concern |
|---|---|---|
| Prompt registry | Versioned instructions and examples by ID; rollout flags | Cache-friendly: one version per cohort, not per user |
| Tool registry | Approved tools with owners, schemas, size limits, trust labels | Hundreds of tools → tool search; definition size budget |
| Retrieval service | search(query, user, filters, budget) → cited items | p95 latency; permission filtering at query time |
| Memory service | get_profile, search_memories, write with provenance | Per-tenant isolation; deletion on request (GDPR) |
| Session / event store | Append-only events; cached summaries; checkpoints | Hot sessions in a fast store; archive to cheap storage |
| Orchestrator | build(task_type, user, session, request) → request + breakdown | Stateless, horizontally scaled; fan-out fetches in parallel |
| Model gateway | One API for many models; quotas; fallback; cache affinity | Rate limits; regional capacity; cache locality |
| Observability | Spans with breakdowns; sampled snapshots; redaction | Volume: sample snapshots, keep metrics for all |
The latency budget of context assembly
Context building sits on the critical path before the first token. Fetch independent layers in parallel; precompute what you can (profiles, summaries) in the background; set a deadline per source and degrade gracefully (answer without memory rather than wait). A typical budget for an interactive assistant: policy 5 ms, memory 30 ms, retrieval 80–200 ms, rerank 50–150 ms, render 5 ms, then model time-to-first-token, which is itself shorter for cached prefixes.
max(t_memory, t_retrieval + t_rerank, t_session) + t_render, not their sum.- FastAPI + asyncioA stateless orchestrator with parallel fetches and deadlines.
- LiteLLM · PortkeyModel gateway: routing, fallback, budgets, usage.
- Redis · PostgresSession state, summaries and profiles.
- Foundry Agent Service + API Management AI gatewayHosted agents with token limits, routing and logging.
- Cosmos DB · Azure AI Search · Azure Cache for RedisMemory, retrieval and session state.
- Bedrock AgentCore (Runtime, Memory, Gateway)Session-isolated runtime, memory and tool gateway.
- DynamoDB · OpenSearch · ElastiCacheState, retrieval and caches.
- Vertex AI Agent Engine (Sessions, Memory Bank)Managed session and memory.
- Vertex AI Search · Memorystore · FirestoreRetrieval, cache and state.
- LangGraph Platform / TemporalDurable orchestration with state.
- vLLM + llm-d / prefix-aware routingSelf-hosted serving that keeps caches warm.
- Postgres + pgvector · Redis · KafkaStores and event streams.
Cloud product names and features change often. Treat these as pointers and confirm current availability, regions and pricing in each provider's docs.
Cost and latency engineering
For most LLM products, input tokens are the bill, because contexts are large and re-sent every call. The biggest levers, in typical order: caching the prefix, trimming tool results and retrieval, managing history growth, routing simple calls to smaller models, and isolating heavy reading into cheaper sub-agents. Latency follows the same levers: fewer uncached input tokens means faster first tokens.
Live demo · monthly cost of your context
The levers
| Lever | Typical saving | Effort | Risk |
|---|---|---|---|
| Fix cache breakers; order for caching | 50–90% of input cost on cached part | Low | Almost none |
| Shape tool results | 30–80% of agent context | Low | Dropping a needed field |
| Clear old tool results | 40–80% on long runs | Low | Re-fetch cost if needed again |
| Retrieval budget + reranking | 30–70% of RAG context | Medium | Lower recall |
| Tool search instead of all tools | Most of the definitions block | Medium | Search misses |
| Compaction | Turns quadratic growth into linear | Medium | Lost details |
| Model routing by task | 3–20× on routed calls | Medium | Quality on hard cases; cache resets |
| Code execution for data-heavy steps | Up to 90%+ on those steps | Higher | Sandbox security |
| Batch APIs for offline work | ≈ 50% where offered | Low | Hours of delay |
I = input tokens, C = cacheable part, h = hit rate, r / w = read / write multipliers, O = output tokens
Time to first token ≈ queue + overhead + k · uncached input tokens (k depends on model and hardware)
Scaling from 1 user to 1,000,000
At one user, context is a string you edit by hand. At a thousand, it's a quality problem: you need evals to know if a change helped. At a hundred thousand, it's a cost and cache problem. At a million, it's a platform: versioned context services, per-tenant isolation, regional capacity and governance over what goes into every model call.
Pick a stage
The failure catalog: technical and functional problems
Every entry has a symptom, root cause and fix, tagged by area and severity. Click a cell in the heat map, filter by severity, or search for a word from your bug report.
Every trade-off, side by side
Each row is a decision with two ends. The marker shows where most production teams sit by default. Move it for your own risk, scale and team.
Alternatives, complements, and what's next
Context engineering changes behaviour at inference time, with no training. Sometimes it's better to change the model (fine-tuning), the task (code instead of an LLM), or to lean on a bigger window. The frontier is moving toward models trained to manage their own context, standardised context sources, and smarter KV-cache infrastructure.
Alternatives, compared
| Alternative | Better than more context engineering when | Worse when |
|---|---|---|
| Just use a bigger window | Small, stable inputs; prototypes; one-off analysis of a long document | Many steps, high volume, distractors, cost sensitivity |
| Fine-tuning (SFT, LoRA) | A stable style, format or narrow skill needed on every call; to shrink long instructions and examples | Knowledge that changes; per-user facts; small teams without eval infrastructure |
| Reinforcement fine-tuning | A checkable task where you want the model to learn strategies (including how to use tools) | Few examples; unclear rewards |
| Cache-augmented generation (CAG) | A small corpus that fits comfortably and changes rarely; latency matters | Large or changing corpora; per-user permissions |
| Deterministic code | The answer can be computed; rules are known | Messy language input |
| Smaller specialised model | High-volume, narrow tasks with short contexts | Broad reasoning across many sources |
| Structured data + SQL | Exact facts, aggregates, joins | Unstructured knowledge |
What's next
Trained to manage context
Models increasingly learn, through RL in real harnesses, to take notes, search instead of reading everything, and compact their own history. More of today's harness logic moves into the model.
Self-improving contexts
ACE-style playbooks, prompt optimisers (DSPy, GEPA) and memory systems that learn from outcomes treat context as something optimised, not hand-written.
KV cache as a resource
Offloading KV caches to CPU and SSD, sharing them across replicas, prefix-aware routing and longer cache lifetimes make large stable prefixes cheaper.
Standard context sources
MCP for tools and resources, AGENTS.md for project instructions, Skills for procedures. Context becomes portable across tools and vendors.
Beyond attention
Hybrid architectures (state-space layers, linear attention, memory tokens) aim to make long contexts cheaper. They shift the trade-offs but don't remove the need to choose what matters.
Auditable context
Regulation (such as the EU AI Act's logging and oversight duties) pushes teams to record what information drove a decision. Context snapshots become compliance records.
Context engineering connects the other manuals: retrieval in the RAG Guide, tools and resources in the MCP Guide, and loops, memory and multi-agent systems in the Agents Guide.
Production checklist, glossary and sources
Tick items as you go. Progress is saved in this browser only.
Glossary
| Term | Definition |
|---|---|
| ACE | Agentic Context Engineering (2025): contexts as evolving playbooks updated by small, itemised edits. |
| AGENTS.md | A cross-tool convention for project instructions that coding agents load at session start. |
| Attention budget | The idea that each added token dilutes the model's attention to the rest. |
| CAG | Cache-augmented generation: load a whole small corpus into a cached context instead of retrieving. |
| Compaction | Summarising a context into a brief and continuing in a fresh, smaller window. |
| Context clash | Parts of the context contradict each other. |
| Context collapse | Detail eroding through repeated full rewrites of a summary or playbook. |
| Context confusion | Irrelevant content (often tools) leading the model astray. |
| Context distraction | Long history causing the model to repeat past actions instead of reasoning. |
| Context editing | Automatically removing or clearing parts of the context (e.g. old tool results) between calls. |
| Context poisoning | A wrong fact entering the context and being reused as truth. |
| Context rot | Performance degrading as input length grows, even below the limit. |
| Contextual retrieval | Prepending a generated description to each chunk before indexing. |
| Effective context length | The length up to which a model still performs well on a given task. |
| Instruction hierarchy | The trained priority of system over developer over user over data. |
| Just-in-time context | Holding references and loading content only when the model decides it's needed. |
| KV cache | Per-token key and value vectors computed during prefill and reused during decoding. |
| Lethal trifecta | Private data + untrusted content + an outbound channel in one agent. |
| Lost in the middle | Lower recall for information placed mid-context (Liu et al., 2023). |
| Observation masking | Hiding old tool observations while keeping the agent's reasoning and actions. |
| Prefill | The phase where the model processes all input tokens before generating. |
| Progressive disclosure | Revealing context in layers (summary, then details) as the task needs it. |
| Prompt caching | Provider reuse of computation for an unchanged prompt prefix, billed at a discount. |
| Recitation | Re-writing the plan or to-do list at the end of the context each step. |
| Skill | A folder of instructions and resources an agent loads when its description matches the task. |
| Spotlighting | Marking untrusted input (delimiters, datamarks, encoding) so models treat it as data. |
| Tool loadout | Selecting a small set of relevant tools per request. |
| Tool-result clearing | Replacing old tool outputs with placeholders to save tokens. |
Sources and further reading
Core essays
- Anthropic: Effective context engineering for AI agents (2025)
- LangChain: Context engineering for agents (2025)
- Manus: Context engineering for AI agents, lessons from building Manus (2025)
- Drew Breunig: How long contexts fail (2025) · How to fix your context
- Cognition: Don't build multi-agents (2025)
- HumanLayer: 12-Factor Agents
Research
- Lost in the Middle (Liu et al., 2023)
- RULER: real context size of long-context models (2024) · NoLiMa (2025)
- Chroma: Context Rot (2025)
- Agentic Context Engineering, ACE (2025)
- A Survey of Context Engineering for LLMs (2025)
- LLMs Get Lost in Multi-Turn Conversation (2025)
- MemGPT (2023) · Generative Agents (2023)
- LLMLingua-2 (2024)
Provider documentation
Less, but better tokens
The Context Engineering Guide. Written with research current to October 2026. Models, prices, cache rules and SDK features change often: check official docs for anything newer, and treat numbers here as starting points to measure against. Companion guides: RAG Guide · MCP Guide · Agents Guide.