Lecture 25 · Fundamentals of Context Engineering

Scalable AI: Bridging Theory, Understanding, and Practice · Lecture 25。个人学习讲义与配套实验,按主题整理并持续修订。

课程源码 ZIP ↓

个人整理的学习笔记,非官方讲义;课程来源与整理说明见课程介绍。配套示例未逐一运行验证。

本篇目录

Maps to: UC Berkeley EE 290/194 Scalable AI, Spring 2026 Lecture 21, Fundamentals of Context Engineering (74 slides: a catalogue of nine context patterns, then two product families). The Fall 2026 lecture (L22, scheduled for Nov 18) had no public slides when these notes were written.

Sources beyond the slides, each cited where used:

  • Liu et al., Lost in the Middle: How Language Models Use Long Contexts (TACL 2024; arXiv 2307.03172): position and retrieval-depth effects, Tables 1 and 5–6;
  • Anthropic’s prompt-caching documentation and OpenAI’s prompt-caching guide (both checked 2026-11-01): prices, TTLs, minimum lengths, routing;
  • Yichao “Peak” Ji, Context Engineering for AI Agents: Lessons from Building Manus (July 2025);
  • Anthropic Engineering, Introducing advanced tool use on the Claude Developer Platform (2025): tool-definition token counts, tool search, programmatic tool calling;
  • DeepSeek-AI, DeepSeek-V3.2 §4.4 (arXiv 2512.02556), as summarized on the slides: context management for a search agent;
  • Hong, Troynikov and Huber, Context Rot (Chroma, July 2025): long-input degradation across 18 models;
  • Sukhbaatar et al., End-To-End Memory Networks (NeurIPS 2015): the architecture of this lecture’s reader.

Recommended reading: the slides’ references: the context-engineering survey (arXiv 2507.13334), the agentic-RAG survey (arXiv 2501.09136), Agentic Context Engineering (arXiv 2510.04618), and the MCP specification. Then Liu et al. and the Manus post.

Code: code/lecture25/ contains:

  • ctx_world.py: Context World, a private knowledge base with versions, a document corpus and reading tasks with known answers;
  • reader.py: a small attention reader trained to answer from its context (~20 s, cached);
  • retrieval.py: chunking, BM25, packing, deduplication, freshness and compression;
  • context_budget.py: tokens, dollars and TTFT of a call, with and without caching;
  • six demos: the budget, reading evidence, retrieve-and-pack, memory, tools as context, prompt caching.

Reading time: ~2.5 hours for the prose; ~1.5 minutes to run all demos (plus ~20 s once to train the reader).


0. How to read this lecture

0.1 Learning goals

After this lecture you should be able to:

  1. Define context engineering as a systems problem: assembling, for each model call, the bundle of instructions, task, evidence, memory, tool descriptions and observations that lets the next completion be right, under a budget of tokens, latency and money.
  2. Price a context: tokens per slice, cost per call and per task, time to first token, and how prompt caching changes each.
  3. Explain what a model does with what you give it: evidence beats memory, distractors and length dilute attention, the usable context is shorter than the window, and ordering conventions decide conflicts.
  4. Design an evidence path (chunking, retrieval, reranking, packing, compression, freshness) and predict where it fails.
  5. Design memory with a write gate, keys and overwrite rules, and tool registries that are searched rather than loaded.
  6. Recognize the nine context patterns of the slides in shipped products, from fast answer engines to deep-research systems and coding harnesses.

0.2 Prerequisites and scope

  • Prerequisites:
    • Lecture 16: chat templates, tool calls, the system prompt;
    • Lecture 22: prefill vs decode, TTFT, the prefix cache;
    • Lecture 23: RadixAttention and KV-aware routing (the server side of prompt caching).
  • Scope: everything that decides what is in the context window at decision time, and what it costs.
  • Not in scope:
    • agent loops, harnesses and multi-agent systems (Lecture 26);
    • guardrails and the security of what enters the context, such as injected instructions in retrieved text (Lecture 27);
    • embedding models and vector databases in depth (Lecture 25’s retrieval is lexical; see the CMU 11-642 notes for the rest).

0.3 Section → code map

SectionIdeaCode in code/lecture25/
§1what context engineering is; the nine patterns–
§2the window as a budgetcontext_budget.py, 01_context_budget.py
§3what a model does with its contextctx_world.py, reader.py, 02_reading_evidence.py
§4the evidence path (RAG)retrieval.py, 03_retrieve_and_pack.py
§5memory04_memory.py
§6tools as context05_tools_as_context.py
§7long-context management and prompt caching06_prompt_caching.py
§8products: answer engines, deep research, harnesses–

0.4 The toy world and the reader (read this before the numbers)

The numbers in §3–§5 come from a real model reading real contexts, in a world small enough to know every answer.

  • Context World (ctx_world.py) has two kinds of facts, both stated as sentences like “the capital of velmora is ostrin .”:
    • public facts: Lecture 9’s 100 invented countries × 4 relations. A model can learn them in its weights.
    • private facts: 300 new entities × 4 relations that exist only in a private corpus of 1,200 wiki pages and 120 update-log pages. 65% of them appear on some page; 27% change by the latest version.
  • One word is one token in Context World. Real BPE tokenizers use about 1.3 tokens per English word, so multiply toy counts by ~1.3 for intuition (Demo 01 Part D).
  • The reader (reader.py) is a 0.66M-parameter attention model trained for ~20 s to answer a question from the sentences in its context, to say “unknown” when a private fact is missing, and to fall back on its memorized public facts otherwise. It is a memory network (Sukhbaatar et al. 2015): the attention of a transformer applied over sentences instead of tokens.

Why not a token-level transformer? We tried first: Lecture 21’s parent fine-tuned on reading tasks, and 4-layer transformers trained from scratch. They learned to copy “a value of the right type” from the context, but never to match the entity: with one distractor about another entity they were right ~50% of the time, exactly chance. Even pure associative recall did not emerge in 6,000 steps, and the parent itself resolves let x = 4 ; let y = 7 ; y is no better than chance. In-context lookup (an induction circuit) needs far more training than a laptop budget. The sentence-level reader learns lookup in seconds and keeps the behaviours we want to measure: softmax attention shared by all evidence, a learned recency bias, a learned “nothing matches” option, and parametric memory. It is far less distractible than an LLM inside its trained length and collapses faster outside it; §3 compares its curves with published LLM measurements.


1. What context engineering is

1.1 The object being engineered

The slides’ working definition: context engineering is the systems problem of assembling what the model sees at decision time:

  • system and developer instructions;
  • the active user task;
  • retrieved evidence;
  • persisted memory;
  • tool and resource descriptions;
  • fresh observations from calls already made.

They write it as one function, rebuilt at every step t:

c_t = f(instructions, task, retrieval, memory, tools, observations_t)

Three consequences follow, and they are the reason the topic is a systems topic rather than “prompt writing”:

  1. The object is built by code, every turn. In a chat, an agent or a pipeline, c_t is a structured bundle that changes from step to step. Small packing mistakes compound across steps.
  2. Quality depends on selection, ordering, deduplication and refresh policy, not only on wording. Which ten chunks, in what order, with which stale memory removed: these decide the answer.
  3. Most valuable knowledge is outside the weights. Private corpora, live systems and code bases must be retrieved, summarized or reached through tools, then injected on purpose.

The design question, in the slides’ words: given fixed model capability and a finite budget (tokens, latency, cost), what should be in context now so that the next completion is correct, grounded and efficient?

1.2 Bigger windows did not remove the problem

Windows grew from 4K tokens (2023) to 200K–1M. Three costs remained:

  • Money. Input tokens are billed on every call. An agent re-sends its whole history on every call, so its input bill grows with the square of the number of calls (§2).
  • Latency. Every uncached token must be prefilled before the first output token (Lecture 22). For a 70B model on 4 H100s, 131K tokens take ~18 s (Demo 01).
  • Focus. Models do not use long contexts evenly. Liu et al. found that GPT-3.5-Turbo answered 75.8% of multi-document questions when the answer was in the first of 20 documents, but 53.8% when it was in the 10th: below its closed-book accuracy of 56.1%, i.e. worse than giving it no documents at all. Chroma’s Context Rot report (18 models, 2025) found performance falling with input length even on simple retrieval and copying tasks, well inside the advertised windows.

1.3 The harness

The slides call the end-to-end system around the model the harness: its default tools, allowed actions, what gets pulled into context automatically, session and memory rules, and how user intent becomes a structured task brief. Coding terminals (Claude Code, Codex-class CLIs) treat the repository, the diff, the tests and the shell as the substrate: the model plan–act–observes with file and command tools, and project instruction files checked in by the team are prepended to every session. Orchestration harnesses keep a primary agent in sync with the outside world and delegate long coding episodes to child sessions through a compact handoff. Lecture 26 is about harnesses; this lecture is about the context each of them builds.

1.4 The catalogue: nine patterns, five families

The slides organize the field as nine patterns, each a different answer to “where does this slice of state come from, and how does it enter c_t?”:

FamilyPatternPrimary stateBest fitMain failure
evidence1. RAGexternal evidencegrounded Q&A over corporawrong evidence
evidence2. Agentic RAGa retrieval trajectorymulti-hop searchsearch loops
action3. Tools / MCPlive systemstasks needing actions or live statetool confusion
action4. Workflows (typed pipelines)typed intermediatesrepetitive, auditable flowsbrittle rigidity
persistence5. Memorypersisted statecontinuity across sessionsstale noise
control6. Agentic loopscontroller statelong-horizon taskstranscript bloat
control7. Subagentspartitioned local statespecialized workersgiant handoffs
substrate8. File-nativefiles and artifactscode and large reposnavigation chaos
substrate9. Long-context managementthe window budgethuge sessions with reusenoisy windows

Real systems compose several. The rest of the lecture measures the mechanics underneath them: the budget (§2), what the model does with evidence (§3), evidence paths (§4, patterns 1–2), memory (§5, pattern 5), tools (§6, pattern 3) and long-context management with caching (§7, pattern 9). Patterns 6–8 are Lecture 26’s.


2. The context window as a budget

2.1 Anatomy of one call (Demo 01 Part A)

A representative coding agent at turn 20 (slice sizes are a typical configuration, not one product’s):

slicetokensshare of a 200K window(input,uncached,(input, uncached,3/M)
system prompt3,0001.5%0.009
tool definitions (20 built-in)12,0006.0%0.036
project memory files2,0001.0%0.006
history (20 earlier turns)56,00028.0%0.168
this turn’s tool result2,5001.2%0.008
total75,50037.8%0.227

The model’s 300-token reply costs $0.0045. Without a prefix cache, the first token arrives after 8.2 s (Lecture 22’s step model, Llama-3-70B on 4 × H100). The part that grows, the history, is 74% of the context and nobody wrote it by hand.

2.2 Growth (Demo 01 Parts B–C)

Each turn adds a tool result (2.5K) and a reply (0.3K). The call at turn t carries 19.5K + 2.8K·t tokens, so:

  • the per-call cost and TTFT grow linearly in t: 0.059and1.5satturn0,0.059 and 1.5 s at turn 0, 0.478 and 24.8 s at turn 50;
  • the task’s total input grows quadratically: 40 turns send 2.96M input tokens for 12,000 output tokens, a ratio of 247:1. Manus reports ~100:1 for its agent. Output is 5× pricier per token, but input is 98% of the bill.

Where is the wall? DeepSeek-V3.2’s search agent (slides) acts when usage passes ~80% of its 128K window. For our agent with a 200K window, 80% arrives at turn 51. Load five MCP servers (Anthropic measured ~55K tokens of tool definitions for GitHub, Slack, Sentry, Grafana and Splunk) and it arrives at turn 31.

Back-of-envelope. Total input over T turns = T·H + d·T(T−1)/2, with head H and growth d per turn. For H = 17K, d = 2.8K, T = 40: 680K + 2,184K = 2.86M tokens (2.96M with each turn’s tool result counted, as in the demo). The quadratic term dominates after T ≈ 2H/d = 12 turns.

2.3 What to take from the budget view

  • Every slice must earn its tokens. A 12K-token tool list on every call is a fixed tax; a 56K history is a growing one.
  • Order slices by stability (static first, volatile last), so a prefix cache can reuse them (§7).
  • Count in tokens, price in dollars and seconds. TTFT grows with the uncached context: long contexts are slow before they are expensive.

3. What a model does with its context

§2 priced the context. This section asks what the tokens buy. Every number is the reader of §0.4 on reading tasks with known answers (Demo 02; 600 questions per cell, so ±2 points near 90% and ±4 near 50%).

3.1 Evidence is the only route to private knowledge (Part A)

situationaccuracysays “unknown”
public fact, no evidence (closed book)1.0000.000
private fact, no evidence (closed book)0.9980.998
private fact, the fact alone in context1.0000.000
private fact + 8 distractors1.0000.000

For a private fact with no evidence, the right answer is “unknown”. The reader was trained to abstain; a model that answers a value there is hallucinating. Real LLMs abstain far less reliably, which is why an explicit abstention policy (answer only from evidence, say so when it is missing) is part of every grounded-answer system the slides discuss.

3.2 Distractors and the effective context (Part B)

Accuracy by distractor kind and count (the reader was trained with 0–24 distractors, i.e. up to ~216 tokens):

distractorsk=08244896192384
prose1.0001.0000.9930.9920.9820.9070.723
same entity, other relation1.0001.0000.9320.8020.5130.1480.057
same relation, other entity1.0001.0000.9950.9900.9870.9150.773
mixed1.0001.0000.9880.9800.9370.7350.383
mixed: attention on the right sentence0.9490.8360.6850.6290.5100.3600.235
mixed: tokens14802164128121,6103,196

Three lessons:

  1. Inside its trained lengths the reader is nearly immune to distractors; outside, it decays. Mixed accuracy is 0.988 at 24 distractors, 0.937 at 96 and 0.383 at 384. Nothing about the window changed: attention can see all 3,196 tokens. What changed is that the model never learned to find one fact among 384. Real long-context models show the same gap between the advertised window and the effective one (Chroma’s Context Rot; RULER-style benchmarks).
  2. Attention is a shared budget. The weight on the right sentence falls from 0.95 to 0.51 at 96 distractors and 0.24 at 384, even while the answer is still right. Every extra sentence costs focus.
  3. Near-duplicates are the most dangerous distractors. Facts about the same entity are much worse than facts about other entities: 0.513 vs 0.987 at 96. (With 3 other relations, those facts repeat ~k/3 times each; repeated near-duplicates pile up attention.) In retrieval, near-duplicate chunks of the same page are exactly what comes back together, which is why deduplication belongs in every packer.

3.3 Position (Part C)

With 96 same-relation distractors, by distance between the fact and the question:

sentences between fact and question04122024284060
accuracy0.9980.9930.9780.9270.8700.9900.9970.993

The dip sits at distances near 24, the edge of training: every training example had at most 25 sentences, so the recency embeddings for distances near 24 were trained on few examples. Beyond them (28+), the reader treats positions alike. Real models show their own shapes, set by their own data: GPT-3.5-Turbo’s U (75.8% first, 53.8% middle, 63.2% last, Liu et al. Table 6) is the famous one. The transferable lesson: position effects are learned, they are measurable, and they differ by model. Put the most important evidence where your model reads best (usually the start or right before the question), and measure it.

3.4 Conflicts: the later statement wins (Part D)

Two statements of the same fact disagree, among 8 distractors:

layoutanswers current valueanswers old value
old value stated before the current one0.7630.228
old value stated after the current one0.1280.858

The reader learned the convention of its training data, where the later statement in an update log is current. It applies the convention to whatever order the packer produces. A packer that puts stale memory after fresh evidence makes the model wrong, and so does a reranker that happens to place an old copy nearest the question (§4.5, §5). Ordering is part of the interface between the context builder and the model.

3.5 Evidence vs memory (Part E)

situation (public facts, 8 distractors)accuracy
evidence agrees with memory1.000
evidence states a new value (counterfactual)0.995
fact missing from evidence → falls back on memory0.983

Evidence overrides memory when present, and memory fills in when evidence is silent. This is the behaviour RAG relies on to deliver fresh facts. It is also why stale or poisoned evidence is dangerous: the model will believe it over what it knows. (Lecture 27 treats injected instructions in retrieved text as a security problem.)


4. The evidence path: RAG

4.1 The pipeline

The slides’ RAG components, in order:

ingest → chunk → embed / index → retrieve → rerank → pack → (model)

componentrole
corpus + ingestiondecides what is even searchable
chunking + metadatathe retrieval granularity and filters (dates, sources, versions)
embeddings + lexical signalsthe similarity space and exact-match support
retriever + indexcandidate evidence under a latency budget
rerankerwhich candidates deserve the context budget
packerdeduplicate, order and cite the final payload

Demo 03 builds each piece (retrieval.py; BM25 as the retriever) on Context World’s private corpus and scores the whole path with the reader. 600 questions; 65% are answerable from some page, the rest should get “unknown”.

4.2 Chunk granularity (Part A)

chunkingchunkskrecallaccuracytokens
pages1,2001 / 3 / 100.765 / 0.969 / 1.0000.838 / 0.973 / 0.99359 / 167 / 472
sentences8,4161 / 3 / 101.000 / 1.000 / 1.0001.000 / 0.987 / 0.9877 / 16 / 47
24-word windows4,1141 / 3 / 100.648 / 0.862 / 0.9060.765 / 0.890 / 0.89720 / 57 / 165
24-word windows, 8 overlap5,2971 / 3 / 100.673 / 0.954 / 1.0000.780 / 0.910 / 0.90321 / 58 / 180

(recall = the answer sentence, complete, is in the packed evidence, over answerable questions; accuracy includes abstentions.)

  • Granularity is a token bill. Pages need 472 tokens per question to reach the accuracy sentences reach with 7–47.
  • Fixed windows cut facts in half. 46% of window pieces are fragments such as “velmora is ostrin .” that no longer say which relation they are about. Overlap rescues recall (1.000 at k = 10) but not accuracy (0.903): the fragments stay in context and mislead.
  • Honest caveat: Atlas facts are self-contained single sentences, which flatters sentence chunks. Real facts span sentences, and sentence chunks lose the surrounding context; section-aware chunking (split at headings and paragraphs, attach the title) is the usual compromise.

4.3 More chunks: recall saturates, accuracy turns down (Part B)

pages retrieved131030100300
recall0.7650.9691.0001.0001.0001.000
accuracy0.8380.9730.9930.9850.8220.545
tokens591674721,2764,47712,427

Recall is complete at k = 10; accuracy peaks there and falls once the evidence exceeds what the reader can use. Liu et al. found the same shape on NaturalQuestions with real retrievers: “model performance saturates long before retriever recall saturates”, so retrieving 50 documents instead of 20 bought ~1.5 points for GPT-3.5-Turbo. Pick k by measuring end-to-end accuracy, not recall.

4.4 Reranking and compression under a budget (Part C)

Top-30 pages from BM25, packed into a fixed token budget three ways:

budgetpackingrecallacc: answerableacc: unanswerableacc: alltokensextra model calls
80BM25 order0.6630.6630.9710.770690
80reader rerank0.7960.7960.6880.7587030
80extractive compression1.0001.0001.0001.000180
160BM25 order0.9130.9130.9810.9371500
160reader rerank0.9950.9950.7310.90315130
160extractive compression1.0001.0001.0001.000180

The reader rerank reads each candidate page alone and orders pages by how confidently the reader answers from it: an “LLM as reranker”. It does what rerankers promise on answerable questions (0.913 → 0.995). But on unanswerable questions accuracy drops from 0.981 to 0.731. For a fact that exists nowhere, the pages the model is most confident about are exactly the near misses that fool it. Selecting evidence by the model’s own confidence selects its failure cases. Rerankers need a relevance signal independent of the answer, and an abstention threshold (“no candidate is relevant enough”), not just an ordering. They also cost compute: 30 extra model calls per question here.

Extractive compression (keep only the sentences that name the question’s entity) is perfect at 18 tokens with no model calls. That is real, but flattering: the question names the entity verbatim and facts are single sentences. Real compressors (summaries; LLMLingua-style token dropping) lose information, and the loss must be measured end to end.

4.5 Freshness is a packing rule (Part D)

After two update rounds, 27% of private facts have changed. Retrieval over wiki pages plus update-log pages returns both the old and the new statement:

packing rule (sentence chunks, k = 10)accuracy (current value)stale value in contexttokens
relevance order (BM25), best last0.38064%52
newest last (sort by version)0.93864%52
keep only the newest value (version metadata)0.9564%44

The model has no idea which statement is newer; the packer does. With relevance order the old value lands nearer the question too often, and the reader’s “later wins” habit (§3.4) picks it. Sorting by version fixes most of it; dropping superseded values using version metadata fixes it best and saves tokens. Freshness lives in metadata and packing rules, not in the model.

4.6 Agentic RAG

Plain RAG retrieves once. Agentic RAG (pattern 2) makes retrieval a trajectory: decompose the task, search, inspect, rewrite the query, switch stores, search again. Its extra components: a planner, a query rewriter and store router, an evidence judge (“enough to answer yet?”), and a stopping rule with a budget. Its typical failures (slides): search loops, one bad early query anchoring the whole trajectory, and evidence found in an intermediate step but dropped before the final answer. Every step is a model call over a growing context, so §2’s arithmetic applies; Lecture 26 builds the loop.

4.7 Failure modes of evidence paths

From the slides, with where each shows up here:

failurewhere measured
wrong corpus or wrong chunk size§4.2 (fragments)
recall is good but reranking/packing is poor§4.4 (BM25 order at 80 tokens)
redundant chunks waste the budget§3.2 (near-duplicates), pack(dedup=True)
no citation or abstention policy§3.1, §4.4 (unanswerable questions)
evidence present but never used§4.3 (k = 300)
stale evidence wins§4.5

5. Memory

5.1 What memory is (and is not)

The slides’ distinction: long context is what you load now; memory is what you choose to keep, index, refresh and retrieve later. Kinds of memory:

  • working: the current context;
  • episodic: what happened in earlier sessions;
  • semantic: durable facts and preferences;
  • artifact: files, reports and code produced earlier.

Components: a write gate (what is worth storing), a schema (profile, preference, episode, artifact), an index and retriever, freshness (TTL, invalidation), consolidation of duplicates and conflicts, and a read policy (when to load what into c_t). Good items: durable preferences, project conventions, reusable workflow hints, links to past artifacts. Bad items: transient chat, stale guesses, giant transcript dumps.

5.2 Five policies over 30 sessions (Demo 04)

An assistant talks to one user for 30 sessions about 40 private entities. Each session the user states 8 facts among 10 chit-chat sentences, then asks 12 questions (10 about facts stated in some session, 2 never stated). Each fact changes with probability 8% between sessions.

policysessions 1–56–1011–2021–30tokens per question, session 30items stored
none (this session only)0.5690.3000.2750.25824118
full transcript0.9830.9330.8420.7335,467540
store everything, top-8 by relevance0.9830.9670.8830.83356540
store everything, top-8 newest last0.9831.0001.0000.94256540
gated, keyed, overwrite, top-80.9831.0001.0001.00056124
  • No memory forgets. It only knows this session.
  • The transcript fails twice. It grows without bound (5,467 tokens per question by session 30, its cost quadratic in sessions) and its accuracy decays as it leaves the reader’s trained lengths and accumulates superseded values.
  • Store-everything + retrieval keeps the context small but brings back stale versions next to current ones. Packed by relevance, BM25 ties put the older copy last and the reader trusts it. Newest-last packing helps (0.942); its remaining misses are the reader’s own: in all 7 wrong answers the current value was in context, behind 2.4 older copies on average.
  • A write gate with keys and overwrite (facts only, one item per entity and relation, newest wins) stores 124 items instead of 540 and is perfect in sessions 21–30. Memory quality is decided at write time, not read time.

5.3 Memory in practice

The slides’ memory tooling: vector and keyword stores, profile stores, project memory files (instruction files checked into a repository and loaded by coding harnesses at session start), freshness checkers and consolidators, and trace viewers for read/write events. Their failure list maps onto Demo 04: memory too noisy to help (store everything), stale items never invalidated (no overwrite), everything written and nothing filtered (no gate), useful artifacts never indexed. A good default: write structured, keyed items; invalidate on update; keep the store small enough that a human can read it.


6. Tools as context

6.1 A tool is a context pattern

The slides’ key point: a tool pattern is really a context pattern. Tool descriptions shape which action the model considers (its “action prior”), and tool outputs become the next layer of evidence. The registry side (names, descriptions, schemas, permissions, versioning) is context paid on every call; the execution side (timeouts, retries, observation reduction, provenance labels, clear errors) decides how much of each output enters the next call. MCP (the Model Context Protocol) standardizes how servers expose tools, resources and prompts to a client.

6.2 The registry tax (Demo 05 Part A)

registrytoolstokens per tooltokens, all loadedshare of 200K
this demo (terse schemas, chars ÷ 4)28813137,78419%
Anthropic’s example: 5 MCP servers (quoted)58~950~55,00028%

Anthropic reports that adding Jira alone (~17K tokens) pushes such a setup past 100K, and that it has seen tool definitions take 134K tokens before optimization. At 3permillioninputtokens,37,784tokensare3 per million input tokens, 37,784 tokens are 0.11 per call before the model reads the task ($0.011 with caching, §7), and they occupy attention on every call.

6.3 Tool search (Parts B–C)

Instead of loading every definition, give the model a search tool and load the top-k matches. In Demo 05 the 600 requests use words like “open a bug”, “ping”, “PR”, and name the service only half the time:

recall@kk=135102050
terse descriptions0.3000.5080.7320.8530.8920.920
descriptions listing a few more words users say0.6320.8500.9420.9680.9730.990
loaded tokens (search tool 500 + k definitions)6399191,1991,8993,2987,497
  • k = 5 finds the right tool 94% of the time for ~1,200 tokens instead of ~40,000. Anthropic’s Tool Search Tool: ~77K tokens before the first request → ~8.7K, and MCP-eval accuracy from 49% to 74% for Claude Opus 4 (79.5% → 88.1% for Opus 4.5). The accuracy gain is the point: fewer, clearer options per call.
  • Descriptions are retrieval keys. Listing two more verbs and one more noun users say lifts recall@5 from 0.732 to 0.942. A tool search cannot find is a tool the model cannot call.
  • Ambiguity is not a retrieval problem. When the request does not name the service and the object exists in several (“an issue”: GitHub or Sentry), recall@1 is 0.302 vs 0.747 with the service named. Loading more tools hands the model the same coin flip; asking, or routing by context (which project is open), fixes it.

6.4 Reducing observations

Tool outputs are the other half of the tax. The slides’ failure list: raw outputs pasted with no reduction, too many overlapping tools, vague descriptions. Anthropic’s programmatic tool calling lets the model write code that calls tools and returns only the result: in their budget example ~200 KB of raw expense data became ~1 KB in context, and on complex research tasks average token use fell from 43,588 to 27,297 (−37%). The principle: reduce observations before they enter the context, in code, not by asking the model to ignore them.


7. Long-context management and prompt caching

7.1 Static prefix, volatile suffix

The slides’ picture of a well-packed window: static prefix → task and recent state → evidence slice → volatile observations, with compaction checkpoints. Two mechanisms make the order matter:

  • Prompt caching (provider side) bills a repeated prefix at a discount. Anthropic: a cache read costs 0.1× the input price; writing costs 1.25× (5-minute TTL) or 2× (1-hour TTL). The TTL is refreshed on every hit and measured from the start of the request. The prefix order is tools → system → messages, with up to 4 explicit breakpoints and a 20-block lookback; prompts shorter than a model-dependent minimum (512 to 4,096 tokens; 1,024 for Sonnet 4.6) are not cached. OpenAI caches automatically from 1,024 tokens, routes requests by a hash of the initial tokens, and suggests keeping ~15 requests per minute per prefix/key so traffic stays on the machines holding the cache.
  • Prefix caching in the engine (Lectures 22–23) skips the prefill of a cached prefix, which cuts TTFT.

Both reuse only an identical prefix: the first token that differs ends the reusable part. Manus calls the KV-cache hit rate “the single most important metric for a production-stage AI agent”: cached Sonnet input costs 0.30permilliontokensvs0.30 per million tokens vs 3.

7.2 Break-even and TTL (Demo 06 Parts A–B)

A 20,000-token prefix used n times: the 5-minute write pays back on the 2nd call (1.25 + 0.1 < 2), the 1-hour write on the 3rd (2 + 0.1 + 0.1 < 3), and 100 calls cost 8.97× less than uncached.

Whether the cache is warm depends on traffic. With Poisson requests at rate λ and the TTL refreshed on each request, the hit rate is the probability the next request comes within the TTL, h = 1 − e^(−λ·TTL) (the simulation matches the formula to 3 digits):

reuse ratehit rate, 5 mincost vs no cachehit rate, 1 hcost vs no cache
once per 20 min0.2201.00×0.9510.19×
once per 10 min0.3930.80×0.9970.11×
once per 5 min0.6320.52×1.0000.10×
once per minute0.9930.11×1.0000.10×

A prefix shared by many users (a product’s system prompt) is always warm. A single user’s agent that pauses for 10 minutes between steps is not, and the 1-hour TTL is worth its higher write price.

7.3 What breaks the cache (Part C)

A 40-turn agent task, 17K-token head, history +2,800 tokens per turn:

layouttask costvs no cache
timestamp in the last slice of the head$1.485.94× cheaper
timestamp in the first line of the system prompt$10.920.80× (more expensive)
tool JSON serialized in a different order each call$10.520.83×
tool list changed every 5 turns$3.102.83×
tool list changed every turn$10.520.83×
no caching$8.771.00×

A timestamp precise to the second at the top of the system prompt is the mistake Manus names first: every call rewrites everything at the 1.25× write price, more expensive than not caching at all. Non-deterministic serialization (dictionary order in tool JSON) does the same silently. Dynamically adding and removing tools mid-task breaks the prefix at the tool list; Manus’s advice is to keep the tool list stable and mask unavailable tools at decoding time instead of removing them. Make the context append-only where you can.

7.4 Caching over a whole task (Part D)

settingtask costTTFT turn 1turn 20turn 40
no caching$8.771.31 s7.45 s17.28 s
prefix caching, calls < 5 min apart$1.471.31 s0.40 s0.58 s
prefix caching, calls 400 s apart (TTL expired)$10.921.31 s7.45 s17.28 s

Caching cuts the task’s cost 6× and makes late turns 30× faster to first token, because the engine prefills only the newest 2,800 tokens. Let the TTL expire between calls and every turn pays full price plus the write premium.

7.5 Compaction

When the window fills, something must go. The slides’ long-context components: transcript-to-state compaction, rolling summaries or checkpoints, differential updates since the last turn, an eviction policy for old observations, and cache boundaries. DeepSeek-V3.2’s BrowseComp agent (slides, from §4.4 of its report) compares four policies when usage passes ~80% of a 128K window:

  • summary: compress the overflowed trajectory and restart (strong, but many extra steps);
  • discard-75%: drop the earliest 75% of tool-call history, keep the tail;
  • discard-all: clear all prior tool history and continue (strong Pass@1 for its cost);
  • parallel-fewest-step: run N independent traces and keep the shortest (parallel test-time compute).

Pass@1 rose from about 51.4 without these policies to about 67.6 with the best serial one: the same model, a different harness.

Compaction’s price (Demo 06): summarizing a 70K-token history into 5K at turn 25 costs 0.11(the5K−tokensummaryisoutput),breaksthecacheonce,andthenturns26–40cost0.11 (the 5K-token summary is output), breaks the cache once, and then turns 26–40 cost 0.41 instead of $0.69, with every later call 65K tokens lighter. It pays for itself within the task. The risk is quality, not money: a summary can drop an unresolved constraint. Lecture 26 measures that.


8. Products: the patterns, composed

The slides’ second half reads shipped products as compositions of the catalogue. Their central claim: good products stabilize reusable context objects: a task brief → evidence cards → sometimes a research notebook → a cited answer or report.

8.1 Family A: fast answer engines

ChatGPT Search, Perplexity’s standard and Pro modes, and the open-source Perplexica/Vane:

  1. Triage into a task brief. Before retrieval, a router decides whether live search is needed, which vertical applies (weather, maps, finance, sports), how deep to search (quick vs pro), how to normalize time, entities and location, and the citation and abstention policy. OpenAI’s public documentation states that ChatGPT Search may rewrite a question into one or more targeted queries and send more specific ones after inspecting the first results.
  2. Rewrite and fan out. Standalone queries, entity and date expansion, several targeted queries across web, files and widgets: already agentic RAG.
  3. Evidence cards, not raw results. Deduplicate near-identical sources, prefer primary ones, trim HTML and tool noise, keep the smallest support set that grounds the answer, and preserve source IDs so citations survive generation.
  4. Synthesis with citations, then reuse the chat tail for follow-ups, re-retrieving when a follow-up changes scope.

c_search = {instructions, task brief, recent chat, evidence cards, widget slots}. Perplexity shows that “answer engine” and “deep research” are not different model species: Standard, Pro and Research are different budgets on the same skeleton (search depth, evidence size, chat vs report).

8.2 Family B: deep-research engines

ChatGPT Deep Research, Perplexity Research, STORM and LangChain’s Open Deep Research:

  1. Scoping produces a research brief: objective, audience, deliverable, comparison axes, preferred sources, allowed tools, time horizon, acceptance checks. OpenAI’s API guide describes the product flow as clarification → prompt rewriting → deep research: a staged context pipeline, not one big prompt.
  2. A supervisor with subagents. One browsing thread accumulates too much raw context, so subtopics go to workers with isolated contexts that return compact findings, not transcripts.
  3. A notebook beats transcript bloat. Findings are stored as items (claim, sources, notes, section tag, confidence or conflict, open questions), so citations survive many more calls.
  4. Report writing and checking from the brief and the notebook, not by rereading every page; then checks for missing citations and unsupported claims, and export.

STORM publishes its pipeline: discover perspectives, simulate writer–expert conversations grounded in sources, build a hierarchical outline, write from outline + references, polish. Its outline is a compaction boundary. Open Deep Research’s lessons (slides): use multiple agents only when the task parallelizes cleanly, write after research rather than with many poorly coordinated section agents, isolate subtopic contexts, and compress the user chat into a brief before the heavy run.

8.3 What to build first, and what to evaluate

The slides’ build order: (1) the brief and the router; (2) evidence cards (compact, deduplicated, citation-ready); (3) a notebook once tasks become multi-step; (4) only then supervisors and subagents, when the task truly parallelizes or tool contexts must be isolated; (5) evaluation and safety: trace logging, claim–source checks, staged access to private tools, caching and compaction.

Evaluate claim–source support, plan coverage, citation accuracy and latency/cost/tool-call budgets, not whether the final paragraph sounds good. Typical failures: fast engines route wrongly (should have searched), pick the wrong vertical, pack weak or stale evidence, attach citations to irrelevant support, or let follow-up state bleed into a fresh factual query; deep-research engines underspecify the brief, stop too early or search aimlessly, lose provenance in the notebook, or mix private connectors and the public web unsafely.


9. Summary

  1. Context engineering builds c_t for every call: instructions, task, evidence, memory, tools and observations, selected, ordered, deduplicated and refreshed by code, under a budget of tokens, money and latency.
  2. The budget: an agent’s context grows linearly per call and its input bill quadratically per task; input is ~98% of the cost; uncached TTFT grows with the context. Tool registries are a fixed tax per call.
  3. What the model does: evidence beats memory; attention is shared, so every sentence costs focus; the usable context is set by training, not by the window; near-duplicates are the worst distractors; position effects and conflict conventions are learned and must be measured.
  4. Evidence paths: chunk granularity is a token bill and fixed windows cut facts; more retrieval stops helping long before recall saturates; reranking by the model’s own confidence hurts abstention; compression is cheap and powerful when it can be done in code; freshness is a packing rule using metadata.
  5. Memory is decided at write time: gate, key, overwrite. Replaying transcripts and storing everything both fail as sessions accumulate.
  6. Tools are context: search the registry, write descriptions with the words users use, reduce outputs before they enter the context, and resolve ambiguity by asking.
  7. Caching rewards stable, append-only prefixes: 10× cheaper reads, 30× faster TTFT late in a task; a timestamp in the first line makes caching more expensive than no caching. Compaction trades a one-off cost and a quality risk for lighter calls; harness policies alone moved DeepSeek’s agent from ~51 to ~68 Pass@1.

10. Common pitfalls

  • Treating the window as free. A 200K window is not a 200K budget: cost, latency and focus all degrade before it fills.
  • Retrieving more to be safe. Accuracy peaks and then falls (§4.3); measure end to end.
  • Splitting documents into fixed windows without overlap or sentence awareness: fragments mislead (§4.2).
  • Reranking by model confidence without an abstention threshold (§4.4).
  • Ignoring versions. Stale statements retrieved next to fresh ones win whenever they land in the model’s preferred position (§4.5).
  • Logging everything into memory. Noise and stale copies crowd out the current fact; gate and overwrite at write time (§5).
  • Loading every tool of every connected server on every call; vague or overlapping descriptions (§6).
  • Putting volatile text early: timestamps, request IDs, re-serialized JSON, a changing tool list at the top of the prompt (§7.3).
  • Letting the cache expire between agent steps without choosing the TTL deliberately (§7.2).
  • Summarizing away constraints during compaction (§7.5; Lecture 26).

11. Exercises

  1. Quadratic input. An agent has a 30K-token head and adds 4K tokens per turn. How many input tokens does a 60-turn task send? At 3/Minputwithnocaching,andwithprefixcaching(writes3/M input with no caching, and with prefix caching (writes 3.75/M, reads $0.30/M, every call within the TTL)?

    AnswerΣ_{t=0}^{59} (30K + 4K·t) = 60 × 30K + 4K × 1,770 = 1.8M + 7.08M = 8.88M tokens → $26.6 uncached. Cached: each call writes its new 4K (the first call writes 30K) and reads the rest: writes ≈ 30K + 59 × 4K = 266K → $1.00; reads = 8.88M − 0.27M = 8.61M → $2.58; total ≈ $3.6, ~7× cheaper.
  2. TTL choice. A user’s agent calls the model on average every 4 minutes (Poisson). Compare the expected input cost per call (relative to plain input) with a 5-minute and a 1-hour TTL, using h = 1 − e^(−λ·TTL).

    Answerλ = 0.25/min. 5 min: h = 1 − e^(−1.25) = 0.713 → 0.713 × 0.1 + 0.287 × 1.25 = 0.43×. 1 h: h = 1 − e^(−15) ≈ 1 → 0.10×. The 1-hour TTL is ~4× cheaper per call here despite its 2× write price.
  3. Break-even of a reranker. A reranker costs 20 cheap model calls of 500 tokens each per question and lets you pack 3 chunks instead of 10 chunks of 400 tokens into the expensive model, with the same accuracy. If the cheap model costs 1/10 of the expensive one per token, does reranking save money?

    AnswerReranking: 20 × 500 = 10,000 cheap tokens = 1,000 expensive-token equivalents. Packing saves 7 × 400 = 2,800 expensive tokens. Net saving 1,800 token-equivalents per question: yes, about 40% of the evidence cost, plus lower TTFT. But check unanswerable questions (§4.4) before shipping it.
  4. Where to put the date. A system prompt must contain today’s date. Where should it go so that the 17K-token head stays cacheable, and what granularity should it have?

    AnswerAt the end of the stable head (or in the first user message), and at day granularity, not seconds: then the head is identical for every call that day and caches. A per-second timestamp at the top makes every call a full write (Demo 06 Part C: $10.92 vs $1.48 for the task).
  5. Memory schema. Design the keys and the write rule for a coding assistant’s project memory that should remember (a) the test command, (b) the user’s preferred code style, (c) a bug that was fixed last week. Which of them should expire?

    Answer(a) key "commands/test", overwritten when it changes, no expiry but re-validated when it fails; (b) key "preferences/style", overwritten; (c) an episode item keyed by the bug/issue ID with a link to the commit, low priority, expiring or archived after the fix is merged and tests pass. Transient chat about the bug should not be written at all.
  6. Tool search sizing. Your registry has 400 tools averaging 700 tokens. Tool search returns the top 8 and costs 500 tokens of its own. What fraction of the registry’s tokens does each call carry? What recall@8 would you need for this to be worth it, if a missing tool means a retry costing one extra call of 20K tokens?

    AnswerAll loaded: 280,000 tokens (exceeds a 200K window!). With search: 500 + 8 × 700 = 6,100 tokens, 2.2%. The saving per call is ~274K tokens; a miss costs ~20K extra. Search pays as long as recall@8 > ~7% in token terms; the real constraint is accuracy (a confused model), so measure task success, not just tokens.
  7. Why did the reader fail on same-entity distractors? In Demo 02, 96 same-entity distractors gave 0.513 but 96 same-relation distractors 0.987. Explain with the reader’s attention, and say what a packer could do about it.

    AnswerThe question vector contains the entity and the relation. Same-entity facts share the entity word, so each scores almost as high as the gold sentence; with ~32 copies of each of the other three facts, their combined attention outweighs the single gold sentence and the attended value mixes the wrong relation's value. Same-relation facts share only the relation word, which carries less weight than the rare entity name. A packer can deduplicate repeated sentences (the 32 copies become 1 each) and put the best match nearest the question.

No assignment targets context engineering directly. Assignment 4 (Inference and Serving) benefits from this lecture’s accounting:

  • measure TTFT with and without prefix reuse, and explain the difference with prefill FLOPs (Lecture 22);
  • design request traces with realistic shared prefixes (system prompts, few-shot examples, multi-turn chats) instead of independent prompts, since prefix caching changes the engine’s behaviour completely;
  • report cost per request in tokens, not only latency.

For the research project, the habit to carry is: every context decision is an experiment with an end-to-end metric (answer accuracy, claim–source support) and a cost (tokens, TTFT, dollars).


13. Research directions

  • Measuring effective context: benchmarks that report, per model, the length and position profile at which retrieval, multi-hop reasoning and conflict resolution degrade, so context builders can be tuned per model.
  • Learned packing: models or policies that choose which evidence to include and in what order, trained on end-to-end accuracy and cost rather than retrieval recall (Agentic Context Engineering, arXiv 2510.04618, treats the context itself as an evolving playbook).
  • Calibrated rerankers and abstention: relevance signals independent of the answer, and thresholds that keep unanswerable questions unanswered (§4.4’s failure).
  • Memory with guarantees: write gates, invalidation and consolidation evaluated on long-horizon benchmarks (the slides cite several 2025–26 memory benchmarks).
  • Cache-aware context design: harnesses and serving systems co-designed for KV reuse across turns, agents and users (Lecture 23’s routing plus this lecture’s ordering rules).
  • Compaction that preserves constraints: summaries checked against the task’s open requirements; when to discard, summarize or restart (DeepSeek-V3.2’s ablation shows the stakes).

14. Further reading

  • The slides’ survey references: arXiv 2507.13334 (context-engineering taxonomy), 2501.09136 (agentic RAG), 2506.10408 (reasoning and agentic RAG), 2510.04618 (agentic context engineering); the MCP specification.
  • Liu et al., Lost in the Middle (TACL 2024).
  • Ji, Context Engineering for AI Agents: Lessons from Building Manus (2025).
  • Anthropic’s prompt-caching documentation and engineering post on advanced tool use; OpenAI’s prompt-caching guide.
  • Shao et al., STORM (arXiv 2402.14207); LangChain’s Open Deep Research repository and blog.
  • Sukhbaatar et al., End-To-End Memory Networks (2015), for the reader used here.

15. Next lecture

Lecture 26, Agentic Applications and Harness Design, puts the model inside a loop: plan, act, observe, update state. The harness decides the tools, the sandbox, the context management between steps (compaction, notes, subagents), retries and verification, and when to stop. We will build a small harness over a simulated environment, measure its failure modes and costs, and compare single-agent and multi-agent designs, reusing this lecture’s budget arithmetic and its reader.


术语表 (Glossary, English → 中文)

English中文
context engineering上下文工程
context window / token budget上下文窗口 / 词元预算
harness模型外围系统(驾驭框架)
system prompt / instructions系统提示 / 指令
retrieval-augmented generation (RAG)检索增强生成
agentic RAG / query rewriting智能体式检索增强 / 查询改写
chunk / chunking / fragment块 / 切块 / 残片
BM25 / lexical retrieval / embedding retrievalBM25 / 词法检索 / 向量检索
recall@k / reranker / packer前 k 召回率 / 重排序器 / 装填器
deduplication / freshness / version metadata去重 / 新鲜度 / 版本元数据
extractive compression / summary抽取式压缩 / 摘要
evidence card / citation / provenance证据卡片 / 引用 / 出处
abstention / hallucination弃答 / 幻觉
parametric knowledge / counterfactual evidence参数化知识 / 反事实证据
distractor / near-duplicate干扰项 / 近似重复
effective context / context rot有效上下文 / 上下文腐化
lost in the middle / position bias / recency中间遗失 / 位置偏差 / 新近性
memory (working / episodic / semantic / artifact)记忆(工作 / 情景 / 语义 / 产物)
write gate / overwrite / TTL / consolidation写入门控 / 覆盖 / 存活时间 / 合并
tool definition / tool registry / tool search工具定义 / 工具注册表 / 工具检索
Model Context Protocol (MCP)模型上下文协议
observation reduction / programmatic tool calling观察结果精简 / 程序化工具调用
prompt caching / cache write / cache read提示缓存 / 缓存写入 / 缓存读取
stable prefix / volatile suffix / append-only稳定前缀 / 易变后缀 / 只追加
compaction / checkpoint压缩整理 / 检查点
task brief / research notebook任务简报 / 研究笔记本
supervisor / subagent主管智能体 / 子智能体
memory network记忆网络
← 返回课程目录