Context Engineering GuideTHE RIGHT TOKENS · AT THE RIGHT TIME
Context engineering for LLMs & agents · October 2026

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.

26chapters
6scale stages, 1 → 1M users
80+problems with fixes
10live demos
Five sources (instructions, tools, memory, retrieved knowledge and history) flow through a context builder that selects, compresses and orders them into a fixed-size context window, which the model reads to produce the next step. every step · a fresh, curated window Instructions Tools Memory Retrieved docs History Contextbuilderselect · trimorder · cache window free space LLMnext step smallest set of high-signal tokens

Pick where you are starting

Every chapter is tagged with a level. Choosing a path highlights the chapters to read first. Nothing is hidden.

Chapter 01Foundations

What context engineering actually is

In one line

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 One promptrole, task, rules,examples, formatwritten once,tuned by hand LLM Question: "how do I phrase this?" context engineering instructions tool definitions memory retrieved docs history + state Context builderbudget per layerselect · compressorder for caching LLM Tool /answer result feeds the next step Question: "what should the model see now?"

Prompt engineering versus context engineering

AspectPrompt engineeringContext engineering
Unit of workA prompt stringA pipeline that assembles context per call
Time scaleOne call or one turnMany calls, sessions, days; agents with 50–500 steps
Main skillClear writing, examples, structureInformation selection, budgeting, retrieval, memory, caching, systems design
SourcesMostly static textInstructions, tool schemas, RAG, memory stores, history, environment state, other agents
Failure looks likeWrong tone, format driftMissing facts, stale memory, distraction, contradictions, injection, runaway cost
Measured byOutput quality on examplesTask success, tokens per success, cache hit rate, latency, safety
OwnerWhoever writes the promptEngineering 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.

Processor

The model

Fixed weights. Brilliant at using what it can see; cannot see anything else. Trained knowledge is old, generic and unverifiable.

RAM

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.

Disk

External stores

Files, databases, vector indexes, memory stores, logs. Unlimited, cheap, durable. Brought into the window only when needed.

Scheduler

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.

Cache

Prompt / KV cache

Providers reuse computation for an unchanged prefix. Stable content first means cheaper, faster calls.

Firewall

Trust boundaries

Everything in context can steer the model. Untrusted text (web pages, emails, tool output) must be marked and contained.

The core claim

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

  1. 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.
  2. 2022 · Prompt engineeringChain-of-thought, role prompts and templates. Windows are 2k–8k tokens, so every word is fought over.
  3. 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.
  4. 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.
  5. 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.
  6. 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

TermPlain meaningChapter
TokenThe unit models read and bill by. About ¾ of an English word.2
Context windowThe maximum tokens (input + output) a model handles in one call.2
Context rotQuality dropping as the context gets longer, even below the limit.2, 15
Effective contextThe length at which a model still performs well on your task.2
System promptStanding instructions at the start of the context.5
Just-in-time contextKeeping references (paths, IDs) and loading content only when needed.7
MemoryInformation saved outside the window and brought back later.8
CompactionSummarising history so work can continue in a smaller context.12
Context isolationGiving a sub-task its own clean context (sub-agent, sandbox).13
Prompt cachingProvider reuse of an unchanged prefix, billed at a discount.14
Context poisoningA wrong fact enters the context and is repeated as truth.15
Prompt injectionInstructions hidden in content that the model treats as commands.18
Chapter 02FoundationsBuilder

How the context window really works

Key insight

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.

ContentRough tokensNotes
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,500Symbols, indentation and identifiers tokenise poorly
JSON record with 20 fields≈ 150–300Keys and quotes repeat on every record
Non-English text1.5–3× EnglishVaries a lot by language and tokenizer
One image≈ 500–2,000+Depends on resolution and provider
A 300-page book≈ 150,000–200,000Fits 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

1 · prefill (reads input, in parallel) cached prefix new tokens: computed this call KV cache: a key and value vector per token, per layer Cost and time-to-first-token grow with uncached input length 2 · decode (writes output, one token at a time) t1 t2 t3 … each new token attends to every token in the cache Output tokens cost 3–8× input tokens

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.

KV cache size ≈ 2 × layers × kv_heads × head_dim × bytes_per_value × tokens
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.

–estimated recall at this position
–worst point (mid-context)
–best point (start or end)

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.

Practical rule

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).

Deep dive

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.

Chapter 03FoundationsBuilder

Anatomy of a context

The shape

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

1 · System instructions: role, goal, rules, style 2 · Tool definitions: names, descriptions, schemas 3 · Examples: a few canonical demonstrations 4 · Long-term memory: profile, preferences, project notes 5 · Retrieved knowledge: documents, records, search results 6 · Conversation history: earlier turns (maybe summarised) 7 · Tool results: what the last actions returned 8 · Current state: plan, to-do list, goal reminder, date 9 · User request: the question or task right now Reserved: output and thinking tokens stable · same for every usercache it, version it like code per user or sessionselect it: only what's relevant per step · changes every callcompress it, keep it recent size every layer · leave headroom

Every layer, and what it forces you to decide

LayerTypical sizeChangesKey decisionsCommon mistake
System instructions500–5,000Per releaseAltitude, structure, priorities, escalationA wall of rules with no priorities (Ch 5)
Tool definitions100–800 per toolPer release or per taskHow many tools, loaded when, described how50 tools always loaded, 30k tokens per call (Ch 6)
Examples200–3,000Per releaseWhich cases; how diverseTen near-identical examples the model copies
Long-term memory100–3,000Per sessionWhat to load always vs on demandStale or wrong facts loaded forever (Ch 8)
Retrieved knowledge1,000–50,000Per turnTop-k, reranking, chunk size, citationsTwenty loosely related chunks (Ch 7)
Conversation history0–100,000+Every turnWindow, summarise, or structured stateAppending forever until it breaks (Ch 9)
Tool results100–50,000 eachEvery stepShape, truncate, clear old onesRaw 40k-token API dumps (Ch 12)
Current state50–1,000Every stepPlan, to-dos, goal reminder near the endPutting a timestamp at the top, which breaks caching (Ch 14)
User request10–5,000Every turnPlace last; rewrite if vagueBurying the question above a long document
Reserved output1,000–64,000Per taskMax tokens, thinking budgetNo 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.

–input tokens
–of the window used (incl. output reserve)
–input cost per call at $3 / M
–share of input that is cacheable

    The six questions for every model call

    1. 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.
    2. What can it do?Which tools, with what permissions. Only those relevant to this step.
    3. What has already happened?Decisions made, actions taken, errors seen. Summarised if old, verbatim if recent.
    4. What should it avoid?Constraints, policies, things already ruled out. Stated once, clearly, with the reason.
    5. What should it produce?Format, length, schema, audience. Shown with an example if it matters.
    6. What can be left out?Everything else. The most underused question: every irrelevant token is cost, latency and distraction.
    Deep dive

    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.

    Chapter 04FoundationsDecision

    When context engineering matters most

    Rule of thumb

    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

    LevelWhat it looks likeGood enough forNext problem you'll hit
    0 · Static promptOne hand-written prompt string, maybe with a variable or twoClassification, extraction, simple rewritingThe model lacks facts about your business
    1 · Template + retrievalPrompt template, top-k RAG chunks, last few turnsDocument Q&A, support FAQ botsLong chats, wrong chunks, no memory of the user
    2 · Managed sessionHistory policy (summary + recent), user memory, tool definitions, prompt cachingAssistants, copilots, simple agentsAgents that run 30+ steps fill and rot the window
    3 · Dynamic per-step assemblyA context builder with per-layer budgets, just-in-time retrieval, result shaping, clearing, compaction, sub-agentsProduction agents, coding agents, research agentsKnowing which change helped; cost at scale
    4 · Measured and self-improvingContext versions with evals, ablations, cost per success, playbooks the agent updates from experiencePlatforms serving many teams and millions of usersGovernance, 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

    1. It works in the playground but not in productionThe playground had a clean, short context. Production adds history, retrieval noise and tool output.
    2. Quality drops later in a conversation or runClassic context rot or history bloat (Ch 15).
    3. The model ignores an instruction it follows elsewhereThe instruction is buried, contradicted, or outweighed by examples.
    4. It confidently uses an outdated or wrong factStale memory, poisoned history, or a retrieved document from the wrong version.
    5. It calls the wrong tool, or invents oneToo many similar tools, vague descriptions, or tools removed mid-conversation.
    6. Costs climb faster than usageContexts are growing per call, or caching is silently broken (Ch 14).
    Read the context first

    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.

    Chapter 05FoundationsBuilder

    Instructions: system prompts at the right altitude

    Key insight

    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.

    text
    <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

    DoInstead ofWhy
    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 weightRules conflict; the model needs to know which wins
    Use normal emphasis; reserve strong words for real hard limitsCRITICAL, MUST, ALWAYS in every lineNewer 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 timeWithout one, the model invents to comply
    Show 3–5 diverse, canonical examplesA long list of edge cases, or 10 near-identical examplesExamples are "pictures worth a thousand words"; similar ones get copied verbatim
    Keep facts out of instructions; load them as dataPasting prices and product lists into the system promptFacts change; instructions shouldn't need a release to update a price
    Start minimal, add rules for observed failuresWriting every rule you can imagine up frontEach 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.

    –
      Deep dive

      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.
      Chapter 06Builder

      Tools are context too

      Key insight

      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

      Raw API response500 records × 60 fields≈ 40,000 tokens Result shaper (your code) • keep the 6 fields that matter• top 10 rows + total count• readable IDs, not UUID soup• "use page=2 or filter=… for more"• errors that say how to fix the call Into contextcompact summary≈ 600 tokens Storedfull result,handle: res_42

      Definitions: how many tools, and when

      TechniqueHow it worksUse whenWatch out for
      Small static tool set5–20 task-shaped tools always loadedMost agentsPressure to keep adding "just one more"
      Tool searchA search tool finds and loads definitions on demand from a large catalogDozens 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 modelMany tools, predictable per-request needsChanging tools per call breaks the cache
      Mask, don't removeKeep all definitions stable; restrict choices with tool_choice, allow-lists or constrained decodingState machines where available actions changeNeeds provider support for forcing or restricting tools
      NamespacingPrefix related tools (browser_, crm_) so the model and masks can treat them as groupsMultiple MCP serversSimilar names across servers confuse the model
      Agents as toolsWrap a specialist agent with its own tools behind one toolBroad domainsMore tokens overall; less visibility
      Why changing tools mid-run hurts

      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.

      Implement it withTool definitions and result shapingTool search, masking, result caps and code execution
      Definition overhead per task ≈ Σ 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.
      python
      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

      Cloud product names and features change often. Treat these as pointers and confirm current availability, regions and pricing in each provider's docs.

      Deep dive

      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.

      Chapter 07Builder

      Retrieval and just-in-time context

      Key insight

      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

      up-front (pre-retrieval) Query Search k=8 Context8 chunks ≈ 6k tokens→ one answer ✓ fast, one model call, predictable✗ misses what the query didn't say✗ irrelevant chunks dilute attention just-in-time (agentic) Contextindex of handlespaths, titles, IDs grep · search · read(path,lines 120-180) · query dbloads only what it chooses ✓ finds things the first query missed✓ context stays small and relevant✗ more steps and latency; needs good tools

      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

      ModeBest forLatencyMain risk
      Up-front RAG (top-k chunks)Q&A over documents; single-turn; latency-sensitiveLowIrrelevant or missing chunks
      Up-front + rerank + compressLarge corpora where precision mattersMediumReranker cost; over-aggressive compression
      Agentic search (tools)Codebases, investigations, multi-hop researchHigherWandering; many steps
      Hybrid: small up-front set + toolsMost assistants and agentsMediumTwo systems to tune
      Whole-corpus in context (CAG)Small, stable corpora under ~100k tokens with cachingLow (cached)Context rot; costs if cache misses
      Structured lookup (SQL, APIs, graph)Facts with exact answers: balances, statuses, relationshipsLowQuery 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.

      Implement it withRetrieval for contextHybrid search, reranking and agentic search tools
      Retrieved budget: 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.
      python
      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))

      Cloud product names and features change often. Treat these as pointers and confirm current availability, regions and pricing in each provider's docs.

      Go deeper

      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.

      Chapter 08BuilderArchitect

      Memory: context that outlives the window

      Key insight

      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

      KindHoldsExampleTypical storeLoaded
      WorkingThe current contextThis conversation, this step's tool resultsThe context windowAlways
      Session / short-termState of one task or conversationPlan, to-do list, scratchpad notesSession store, filesEvery step of the session
      SemanticFacts and preferences"Prefers metric units", "Account is on the Enterprise plan"Key-value, vector, graphProfile always; details retrieved
      EpisodicPast events and outcomes"Last migration failed on step 4 because of a lock"Vector store, logsRetrieved by similarity
      ProceduralHow to do thingsProject instructions, skills, learned playbooksFiles (CLAUDE.md, SKILL.md), prompt storeAlways (short) or on demand

      The memory lifecycle

      1 · Extractfacts, events 2 · Consolidatemerge, dedupe, resolve 3 · Storescope, source, time 4 · Retrieveby relevance, recency 5 · Injectlabelled, budgeted 6 · Forgetexpire, correct, delete memory improves only if it can also be corrected

      Writing memory: hot path or background

      Hot path

      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.

      Background

      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

      1. 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.
      2. Retrieved per turnYour code searches memory with the current request and injects the top few items, labelled with their date and source.
      3. 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.
      A common memory ranking score (from Generative Agents, 2023):
      score = α · similarity(query, memory) + β · e−age/τ + γ · importance
      Implement it withMemory for contextProfiles, episodic stores and memory tools
      • 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.
      python
      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>")

      Cloud product names and features change often. Treat these as pointers and confirm current availability, regions and pricing in each provider's docs.

      Deep dive

      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.

      Chapter 09Builder

      Conversation history and agent state

      Key insight

      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

      PolicyWhat the model seesGood forLoses
      Full historyEvery message and tool resultShort sessionsNothing, until it overflows or rots
      Sliding windowThe last N turns or tokensCasual chatEarly goals and decisions
      Summary + recentA running summary, plus the last few turns verbatimLong chats, assistantsDetails the summary dropped
      Tool-result clearingAll turns, but old bulky tool outputs replaced by a placeholderAgentsOld raw data (re-fetchable)
      Structured stateA state object (goal, plan, facts, open questions) instead of raw turnsWorkflows and long agentsNuance not captured in the schema
      Event log → custom renderYour own compact rendering of typed eventsProduction agentsWhatever you choose not to render

      Own your context window: event log in, rendered view out

      event log (durable, complete) #1 user_message "migrate billing to v2"#2 tool_call grep("BillingClient")#3 tool_result 48 matches …#4 decision "do services first"#5 error tests failed: 3#6 human_approval approved… #212 Rendererbudget: 30k tokensrules per event typedeterministic output Summary of events 1–180goal, decisions + why, files touched, ruled-out ideas Recent events 181–212 verbatimold tool results cleared, errors kept State block (last)plan · to-dos ✓/☐ · open questions · next step

      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.

      python
      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 first

      Three tricks from production agents

      Recitation

      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.

      Keep errors

      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.

      Vary

      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.

      Chapter 10Builder

      Formatting, ordering and placement

      Key insight

      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

      1. Stable before volatileSystem instructions, tool definitions and fixed reference text first, in a deterministic order. This is what caches (Ch 14).
      2. 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.
      3. 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.
      4. Strongest evidence at the edgesWithin a retrieved block, avoid putting the key document in the middle of twenty.
      5. 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

      FormatStrengthWeaknessUse for
      XML-style tagsUnambiguous boundaries; nests well; easy to reference ("the text in <contract>")Some extra tokensSeparating sections and untrusted content
      MarkdownReadable; compact; models know it wellHeading levels can blur in deep nestingInstructions, documents, notes
      JSONExact structure; machine-parsableToken-heavy (quotes, braces, repeated keys)Small structured objects, output schemas
      YAMLLighter than JSON for nested dataWhitespace-sensitiveConfigs, nested records
      CSV / Markdown tablesVery compact for many similar rowsWide tables are hard to read; lossy for nestingLists of records
      Plain proseNatural for reasoning and narrativeFacts can hide in sentencesSummaries, 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

      text
      <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.
      Deep dive

      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.

      Chapter 11FoundationsBuilder

      The four strategies: write, select, compress, isolate

      The map

      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.

      Write

      Save it outside the window

      Scratchpads, to-do files, notes, memory stores, saved tool results, checkpointed state.

      Solves: forgetting across compactions and sessions.

      Select

      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.

      Compress

      Use fewer tokens for the same meaning

      Compaction, summaries, tool-result clearing, trimming, result shaping, prompt compression.

      Solves: window overflow, cost and context rot.

      Isolate

      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

      SymptomLikely strategyFirst technique to try
      Agent forgets the goal after a long runWrite + compressTo-do file with recitation; compaction that keeps the goal
      Answers miss facts that exist in your dataSelectBetter retrieval (rerank, contextual chunks) or a search tool
      Cost per task grows faster than stepsCompress + cacheTool-result clearing; fix cache breakers
      Wrong tool chosen among manySelectTool search or a smaller task-shaped tool set
      Research sub-tasks pollute each otherIsolateParallel sub-agents that return condensed findings
      Huge data passes through the modelIsolateCode execution in a sandbox; return handles
      Assistant doesn't remember the userWrite + selectBackground memory extraction + small profile in prefix
      Chapter 12Builder

      Compression: compaction, clearing and summaries

      Key insight

      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

      TechniqueHowTypical savingInformation riskCost
      Result shapingReturn only needed fields and rows from tools50–95% per resultLowCode only
      Tool-result clearingReplace old tool outputs with a placeholder; keep the call record40–80% of agent contextLow (re-fetchable)Code only
      Observation maskingHide old observations but keep the agent's reasoning and actionsSimilar to clearingLowCode only
      TrimmingDrop oldest turns beyond a token limitBoundedHigh (early goals)Code only
      Running summarySummarise turns older than N into one block, updated incrementally70–90% of old historyMediumOne small model call
      CompactionAt a threshold, summarise everything into a brief and restart the context from it80–95% at each compactionMediumOne model call
      Token-level prompt compressionDrop low-information tokens with a small model (LLMLingua family)2–20×Medium; text becomes terseSmall model pass
      Simple often wins

      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.

      managed contextunmanaged (append everything)window limit
      –peak context (managed)
      –compactions
      –input tokens across the run (managed)
      –unmanaged total (or step it overflows)

      What a compaction must keep

      text
      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

      1. 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.
      2. Trigger earlyCompact at 50–80% of the window, so the summariser has room and the agent never works in the worst-quality zone.
      3. Keep the recent tailCarry the last few steps verbatim after the summary. The model needs fresh, concrete context to continue smoothly.
      4. Re-attach what's re-fetchable as handlesInstead of summarising a file's content, keep its path. The agent can re-read it.
      5. Prefer incremental updatesRepeatedly rewriting a summary from scratch erodes detail ("context collapse"). Append and edit items instead.
      6. Test survivalBuild eval cases that ask, after compaction, about facts established before it (Ch 17).
      Implement it withCompaction and context editingBuilt-in and do-it-yourself compression
      Unmanaged input across n steps: 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.
      python
      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

      Cloud product names and features change often. Treat these as pointers and confirm current availability, regions and pricing in each provider's docs.

      Chapter 13ArchitectBuilder

      Isolation: sub-agents, sandboxes and quarantine

      Key insight

      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

      Lead agentgoal, plan, condensed findingscontext ≈ 20k tokens Sub-agent A · pricing40 pages read, 12 searchescontext ≈ 90k Sub-agent B · reviews300 reviews clusteredcontext ≈ 70k Sub-agent C · regulation5 statutes, 2 rulingscontext ≈ 60k brief: objective, scope, format, tools returns ≈ 1.5k tokens each

      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 whenShare 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 smallThe output of each step is a change others must build on
      Parallelism saves wall-clock timeCoherence of style or design matters
      A sub-task handles untrusted content you want quarantinedThe task fits comfortably in one window
      Different tools or permissions are needed per sub-taskBudget is tight; you can't afford 3–15× tokens

      Other forms of isolation

      Environment

      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.

      State

      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.

      Security

      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

      text
      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.
      Implement it withSub-agents and context isolationSpawning, briefing and condensing
      Total tokens ≈ 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.
      python
      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)

      Cloud product names and features change often. Treat these as pointers and confirm current availability, regions and pricing in each provider's docs.

      Chapter 14BuilderArchitect

      Prompt caching and the KV cache

      Key insight

      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

      step 1 system + tools (written to cache) user turn step 2 cache hit · ≈0.1× price, fast tool result (new) step 3 cache hit · everything before tool result (new) broken 10:42:07 a timestamp at the top changes the prefix → everything recomputed at full price

      How the major providers do it

      ProviderHow you enable itCached-read priceLifetimeNotes
      Anthropic (API, Bedrock, Vertex)Explicit cache_control breakpoints (up to 4), or automatic in some SDKs≈ 0.1× input5 minutes (refreshed on use); 1 hour optionCache writes cost more (≈1.25× for 5 min, 2× for 1 h); minimum cacheable length applies
      OpenAIAutomatic for prompts over ~1,024 tokensDiscount varies by model, roughly 50–90% offMinutes, longer off-peak; extended options on some modelsOptional prompt_cache_key improves routing to the same cache
      Google GeminiImplicit caching on recent models, plus explicit cached content with a TTLLarge discount on cached tokensImplicit: short; explicit: you set the TTLExplicit caches bill storage per hour
      Self-hosted (vLLM, SGLang)Automatic prefix caching / RadixAttentionSaves your GPU timeUntil evicted from GPU memoryLMCache 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.

      –estimated cache hit rate
      –input cost / month, no caching
      –input cost / month, with caching
      –saved

      Rules for a cache-friendly context

      1. Stable first, volatile lastSystem prompt, tools, fixed reference docs, then session memory, then history, then the new turn.
      2. Append-only historyDon't edit or re-order earlier messages. If you must redact, do it before the message first enters the context.
      3. Deterministic serialisationSorted keys, fixed tool order, no random IDs, no timestamps in the prefix.
      4. Put breakpoints where layers endWith explicit caching, mark the end of tools, of the stable docs, and of the latest turn.
      5. Keep traffic warmCaches expire after minutes. Long-TTL options pay off for bursty traffic with big prefixes.
      6. 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.
      7. Measure itLog cached-read and cache-write tokens per call. A sudden drop in hit rate after a release is a bug.
      Implement it withPrompt cachingBreakpoints, cache keys and self-hosted prefix caching
      Cost per call ≈ 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 SDKcache_control: {"type": "ephemeral"} on blocks; usage reports cache_creation and cache_read tokens.
      • openai SDKAutomatic; read usage.prompt_tokens_details.cached_tokens; set prompt_cache_key.
      • google-genaiImplicit caching, or caches.create with a TTL.
      python
      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))

      Cloud product names and features change often. Treat these as pointers and confirm current availability, regions and pricing in each provider's docs.

      Deep dive

      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.

      Chapter 15FoundationsBuilder

      How contexts fail: rot, poisoning, distraction, confusion, clash

      The taxonomy

      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.

      Poisoning

      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.

      Distraction

      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.

      Confusion

      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.

      Clash

      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.

      Rot

      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

      1. Get the exact contextPull the fully rendered input for the failing call from traces (Ch 19). Not the template: the actual tokens.
      2. Check what was missingWas the fact the model needed present? If not, it's a selection problem.
      3. Check what was wrong or conflictingSearch the context for the bad claim and for contradictory statements.
      4. Check what was noiseMeasure each layer's tokens. Anything large and irrelevant is a suspect.
      5. 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.
      6. Turn it into a testAdd the case to your eval set so it never comes back.
      Chapter 16Builder

      Build a context pipeline end to end

      The plan

      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

      1. 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).
      2. 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.
      3. Allocate budgets and prioritiesFixed layers get fixed budgets. Elastic layers (retrieval, history) get a share of what's left, with a priority for trimming.
      4. Render deterministicallySame inputs give the same bytes. Stable layers first. Tagged sections. Volatile content last.
      5. 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.
      6. Manage over timeClearing and compaction for long runs; memory writes at session end.
      7. ObserveLog per-layer token counts, cache tokens, versions and IDs of everything included.
      8. Evaluate and iterateAblate layers, tune budgets, and track tokens per successful task.

      A worked budget for a 200k-token agent

      LayerBudgetPriority when trimmingPolicy
      System instructions3,000 fixedNever trimmedVersioned file; cached
      Tool definitions8,000 fixedNever trimmed mid-run12 tools + tool search; cached
      Project / procedural memory2,000 fixedNever trimmedAGENTS.md-style file; cached
      User memory1,000LowProfile + top 5 memories
      Retrieved knowledgeup to 20,000Medium: trim the tailRerank, dedupe, cite
      History + tool resultsup to 60,000High: clear, then summariseEvent log rendering; clear old results; compact at 100k total
      State block + requestup to 4,000Never trimmedLast in context
      Output + thinking reserve16,000–32,000Reservedmax_tokens set per task
      Comfortable ceiling≈ 100,000Half the window: leaves headroom and stays in the high-quality zone

      The context builder

      python
      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

      python
      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")
      Frameworks do some of this for you

      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.

      Chapter 17BuilderArchitect

      Evaluating context

      Key insight

      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

      MetricQuestion it answersHow
      Task success rateDoes it work?Outcome checks: tests pass, answer matches, judge with rubric
      Tokens per successful taskIs it efficient?Total input + output tokens ÷ successes
      Cost and latency per taskCan we afford it at scale?From usage and traces, p50 and p95
      Context precisionHow much of what we included was useful?Judge or labels: fraction of included items relevant to the answer
      Context recallDid we include what was needed?Labelled required facts present in context
      Faithfulness / groundednessDid the answer stick to the context?Claim-level check against included sources
      Cache hit rateIs the layout stable?Cached-read ÷ total input tokens
      Compaction survivalDo key facts survive compaction?Questions about pre-compaction facts, asked after
      Position sensitivityDoes order change results?Shuffle or move a key document; compare scores
      Distractor robustnessDo 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.

      python
      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).

      Implement it withContext evaluationDatasets, judges, ablations and CI
      Margin of error on a success rate s from N runs ≈ 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.

      Cloud product names and features change often. Treat these as pointers and confirm current availability, regions and pricing in each provider's docs.

      Chapter 18Architect

      Security: everything in context is a potential instruction

      Key insight

      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

      Trustedsystem prompt you wrotetool definitions you controlreviewed procedural memorycan instruct Semi-trustedauthenticated user messagesthat user's own memoriesinternal docs within their accesscan request, within policy Untrustedweb pages, emails, ticketsuploaded files, third-party APIsother users' contentdata only · never instructions Policy layer outside the model: permissions, approvals, egress rules enforced on every tool call

      Threats that arrive through context

      ThreatHow it happensDefence
      Indirect prompt injectionA 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 exfiltrationInjected text makes the model put secrets in a URL, image link or outgoing messageBreak the lethal trifecta (private data + untrusted content + outbound channel); block untrusted URLs and image rendering; egress allow-lists
      Cross-user leakageRetrieval or memory returns another user's dataFilter by permissions before ranking; per-user memory namespaces; tests with two accounts
      Secret leakageAPI keys, tokens or internal URLs placed in the context get repeatedNever put credentials in context; tools hold secrets server-side
      Memory poisoningAn injected instruction is saved to memory and returns in every sessionNo memory writes from untrusted sources; validation and provenance on writes; review and expiry
      Tool-description poisoningA third-party MCP server's tool description hides instructionsVet and pin servers; scan descriptions; show users what changed
      System prompt extractionUsers coax the model into revealing instructionsAssume the prompt is public; keep secrets and business logic out of it
      Shared-cache side channelsTiming differences reveal whether a prefix was recently cached by someone elseUse providers that isolate caches per organisation; don't share caches across tenants in self-hosted setups

      Structural defences, in order of strength

      1. 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.
      2. 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.
      3. 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).
      4. Reduce capability after exposureOnce untrusted content enters a context, disable outbound and write tools for the rest of that run, or require approval.
      5. 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.
      6. DetectInjection classifiers on inputs and outputs. One more layer, with known false negatives.
      Implement it withContext securityPolicy, isolation, filtering and detection
      • 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.
      python
      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()

      Cloud product names and features change often. Treat these as pointers and confirm current availability, regions and pricing in each provider's docs.

      Chapter 19BuilderArchitect

      Observability: see the exact context

      Key insight

      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

      FieldExampleWhy
      Per-layer token countssystem 2,910 · tools 7,850 · retrieval 12,400 · history 41,200 · request 180Find the layer that's growing or bloated
      Usage from the providerinput 64,540 · cache_read 52,000 · cache_write 0 · output 820Cost and cache health
      Versionsprompt v12 · tools v5 · compaction prompt v3 · model idTie regressions to changes
      Included item IDsdoc ids [7, 19, 22] · memory ids [m-881] · tool list hashReproduce and explain an answer
      Context eventscompaction at step 41 (148k → 9k) · 12 results clearedCorrelate quality drops with management events
      Rendered context (redacted)Stored for sampled, flagged and failed callsRead what the model actually saw
      Trust statetainted=true after step 6 (web_fetch)Security audits
      python
      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).

      Implement it withContext observabilityTraces, token accounting and context replay
      • 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.

      Cloud product names and features change often. Treat these as pointers and confirm current availability, regions and pricing in each provider's docs.

      Chapter 20Architect

      System design: a context platform

      The shape

      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

      Apps & agentschat, copilots,agent workers context orchestrator Policy & identitywho, what data, which tools Budgeterper-layer limits by task Assemblerfetch in parallel, trim Rendererdeterministic, tagged versions + breakdown on every request Promptregistry Toolregistry / MCP Retrievalsearch + rerank Memory serviceprofiles, episodes Session / event storehistory, state, summaries Model gatewayrouting, fallback,cache affinity,quotas, keys Modelprovidersor self-hosted Observability & evalstraces, token breakdowns, snapshots, scores Background workersmemory extraction, summaries, re-indexing,context evals on new versions

      Components and their contracts

      ComponentContractScaling concern
      Prompt registryVersioned instructions and examples by ID; rollout flagsCache-friendly: one version per cohort, not per user
      Tool registryApproved tools with owners, schemas, size limits, trust labelsHundreds of tools → tool search; definition size budget
      Retrieval servicesearch(query, user, filters, budget) → cited itemsp95 latency; permission filtering at query time
      Memory serviceget_profile, search_memories, write with provenancePer-tenant isolation; deletion on request (GDPR)
      Session / event storeAppend-only events; cached summaries; checkpointsHot sessions in a fast store; archive to cheap storage
      Orchestratorbuild(task_type, user, session, request) → request + breakdownStateless, horizontally scaled; fan-out fetches in parallel
      Model gatewayOne API for many models; quotas; fallback; cache affinityRate limits; regional capacity; cache locality
      ObservabilitySpans with breakdowns; sampled snapshots; redactionVolume: 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.

      Implement it withContext platform building blocksGateways, stores and orchestration
      Assembly latency with parallel fetches ≈ 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.

      Cloud product names and features change often. Treat these as pointers and confirm current availability, regions and pricing in each provider's docs.

      Chapter 21Architect

      Cost and latency engineering

      Where the money goes

      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

      –per month
      –per 1,000 calls
      –input share of the bill
      –same traffic, no levers and no caching

      The levers

      LeverTypical savingEffortRisk
      Fix cache breakers; order for caching50–90% of input cost on cached partLowAlmost none
      Shape tool results30–80% of agent contextLowDropping a needed field
      Clear old tool results40–80% on long runsLowRe-fetch cost if needed again
      Retrieval budget + reranking30–70% of RAG contextMediumLower recall
      Tool search instead of all toolsMost of the definitions blockMediumSearch misses
      CompactionTurns quadratic growth into linearMediumLost details
      Model routing by task3–20× on routed callsMediumQuality on hard cases; cache resets
      Code execution for data-heavy stepsUp to 90%+ on those stepsHigherSandbox security
      Batch APIs for offline work≈ 50% where offeredLowHours of delay
      Cost per call ≈ pin · [ C·h·r + C·(1−h)·w + (I − C) ] + pout · O
      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)
      Chapter 22Architect

      Scaling from 1 user to 1,000,000

      Pattern

      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

      Chapter 23ArchitectBuilder

      The failure catalog: technical and functional problems

      How to use this

      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.

      Chapter 24ArchitectBuilder

      Every trade-off, side by side

      Read the dial

      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.

      Chapter 25EveryoneStrategy

      Alternatives, complements, and what's next

      Bottom line

      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

      AlternativeBetter than more context engineering whenWorse when
      Just use a bigger windowSmall, stable inputs; prototypes; one-off analysis of a long documentMany 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 examplesKnowledge that changes; per-user facts; small teams without eval infrastructure
      Reinforcement fine-tuningA 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 mattersLarge or changing corpora; per-user permissions
      Deterministic codeThe answer can be computed; rules are knownMessy language input
      Smaller specialised modelHigh-volume, narrow tasks with short contextsBroad reasoning across many sources
      Structured data + SQLExact facts, aggregates, joinsUnstructured knowledge

      What's next

      Models

      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.

      Research

      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.

      Infrastructure

      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.

      Standards

      Standard context sources

      MCP for tools and resources, AGENTS.md for project instructions, Skills for procedures. Context becomes portable across tools and vendors.

      Architecture

      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.

      Governance

      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.

      Companion guides

      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.

      Chapter 26Everyone

      Production checklist, glossary and sources

      Tick items as you go. Progress is saved in this browser only.

      Glossary

      TermDefinition
      ACEAgentic Context Engineering (2025): contexts as evolving playbooks updated by small, itemised edits.
      AGENTS.mdA cross-tool convention for project instructions that coding agents load at session start.
      Attention budgetThe idea that each added token dilutes the model's attention to the rest.
      CAGCache-augmented generation: load a whole small corpus into a cached context instead of retrieving.
      CompactionSummarising a context into a brief and continuing in a fresh, smaller window.
      Context clashParts of the context contradict each other.
      Context collapseDetail eroding through repeated full rewrites of a summary or playbook.
      Context confusionIrrelevant content (often tools) leading the model astray.
      Context distractionLong history causing the model to repeat past actions instead of reasoning.
      Context editingAutomatically removing or clearing parts of the context (e.g. old tool results) between calls.
      Context poisoningA wrong fact entering the context and being reused as truth.
      Context rotPerformance degrading as input length grows, even below the limit.
      Contextual retrievalPrepending a generated description to each chunk before indexing.
      Effective context lengthThe length up to which a model still performs well on a given task.
      Instruction hierarchyThe trained priority of system over developer over user over data.
      Just-in-time contextHolding references and loading content only when the model decides it's needed.
      KV cachePer-token key and value vectors computed during prefill and reused during decoding.
      Lethal trifectaPrivate data + untrusted content + an outbound channel in one agent.
      Lost in the middleLower recall for information placed mid-context (Liu et al., 2023).
      Observation maskingHiding old tool observations while keeping the agent's reasoning and actions.
      PrefillThe phase where the model processes all input tokens before generating.
      Progressive disclosureRevealing context in layers (summary, then details) as the task needs it.
      Prompt cachingProvider reuse of computation for an unchanged prompt prefix, billed at a discount.
      RecitationRe-writing the plan or to-do list at the end of the context each step.
      SkillA folder of instructions and resources an agent loads when its description matches the task.
      SpotlightingMarking untrusted input (delimiters, datamarks, encoding) so models treat it as data.
      Tool loadoutSelecting a small set of relevant tools per request.
      Tool-result clearingReplacing old tool outputs with placeholders to save tokens.

      Sources and further reading

      The idea behind it all

      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.