Notes
All notes

Context Engineering (AI Engg #4)

A support agent answers a question about a customer’s plan with confident, detailed nonsense. The model is fine. The prompt is fine. The problem is that the prompt contained the entire knowledge base, the whole conversation, and a dozen tool outputs — and buried inside it, at position 40,000 of a 60,000-token context, sat the one policy paragraph that mattered. The model skimmed past it.

Prompt engineering writes the instruction. Context engineering curates everything else the model sees, and fits it into a budget. Anthropic’s September 2025 engineering guide, and the 2026 practice that followed, made this the central skill of the field: the goal is the smallest set of high-signal tokens that produces the right answer. This chapter is the multiplier from Chapter 1, made concrete.

The problem: attention is finite

The context window in Chapter 2 is a maximum, not a promise. Long inputs degrade in three distinct ways:

  1. Context rot. As the context grows, the model’s ability to use any particular piece of it drops. The “lost in the middle” effect is real: information at the start and end is used more reliably than information in the middle.
  2. Context distraction. Irrelevant but authoritative-looking text (an old policy doc, a verbose tool log) competes for attention and can steer a wrong answer.
  3. Context poisoning. Untrusted content — a retrieved web page, a user-uploaded file — contains instructions that hijack the model. This is prompt injection (Chapter 13), and it lives in your context pipeline.

Add economics: every token in context costs money on every call and adds latency. A 60K-token context with 5K of signal is paying 55K tokens’ worth of tax, twelve times a second.

So context engineering has a precise objective:

\[ \text{context}^* = \arg\max_{|C| \le B} \ \text{recall}(C) - \lambda \cdot \text{distraction}(C) - \mu \cdot \text{cost}(C) \]

where \(B\) is the token budget, \(\text{recall}\) measures whether the needed facts are present, and \(\text{distraction}\)/\(\\text{cost}\) penalize noise and volume. The \(\lambda\) and \(\mu\) are your call — a medical assistant weights distraction heavily; a brainstorming tool barely cares.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  b/.style={draw, thick, rounded corners=4pt, minimum width=2.3cm, minimum height=0.8cm, font=\rmfamily\small, align=center},
  a/.style={->, thick}]
  \node[b, fill=blue!10] (s) at (-3.4,0) {sources\\docs, memory, tools};
  \node[b, fill=orange!20] (c) at (0,0) {context layer\\select, filter, compact};
  \node[b, fill=green!12] (w) at (3.4,0) {window\\$|C| \le B$};
  \draw[a] (s) -- (c); \draw[a] (c) -- (w);
  \node[font=\rmfamily\small, text=black!60, anchor=north] at (0,-0.85) {the layer is where AI engineering actually happens};
\end{tikzpicture}

The context layer: four stages

Think of a pipeline that runs on every request: retrieve → filter → compact → fit.

Retrieve. Pull candidate facts from wherever they live: a vector database (Chapter 9), a SQL lookup, a memory store, the current thread, tool results, user profile. Cast wide here — recall matters. You will over-fetch (top-20, not top-3) and trim later.

Filter. Drop duplicates, expired facts, low-score chunks, anything failing a tenant/permission check. Rerank with a cross-encoder so the best evidence rises. This is where you enforce that a customer only ever sees their own data.

Compact. Summarize or trim what is bulky but useful: long tool outputs, old conversation turns, entire documents. Compaction is discussed in Section 5; it is the difference between a context that fits and one that does not.

Fit. Assemble the survivors into the final prompt under budget \(B\), ordering for attention (hard rules first, question last) as in Chapter 3, and leaving room for the output.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  b/.style={draw, thick, rounded corners=4pt, minimum width=1.85cm, minimum height=0.7cm, font=\rmfamily\small},
  a/.style={->, thick}]
  \node[b, fill=blue!10] (r) at (-3.0,0) {retrieve};
  \node[b, fill=cyan!15] (f) at (-1.0,0) {filter};
  \node[b, fill=orange!15] (c) at (1.0,0) {compact};
  \node[b, fill=green!12] (m) at (3.0,0) {fit};
  \draw[a] (r) -- (f); \draw[a] (f) -- (c); \draw[a] (c) -- (m);
  \node[font=\rmfamily\small, text=black!60, anchor=north] at (0,-0.6) {wide recall $\to$ precision $\to$ size $\to$ order};
\end{tikzpicture}

Memory: short-term vs long-term

An LLM is stateless (Chapter 2). “Memory” is a design pattern, not a feature. Split it:

A useful taxonomy from 2026 practice:

The engineering rule: do not use RAG as memory. Retrieval is optimized for finding text similar to a query; memory needs decisions and state to survive reliably. Store a structured memory record (typed JSON with timestamps and scope) and retrieve it explicitly.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  b/.style={draw, thick, rounded corners=4pt, minimum width=2.7cm, minimum height=0.8cm, font=\rmfamily\small, align=center},
  a/.style={->, thick}]
  \node[b, fill=orange!15] (st) at (0,0) {working memory\\this session};
  \node[b, fill=green!12] (lt) at (0,-1.7) {long-term store\\episodic + semantic + procedural};
  \draw[a] (lt) -- node[right, font=\rmfamily\small] {retrieve} (st);
  \draw[a, dashed] (st) -- node[left, font=\rmfamily\small] {write back} (lt);
\end{tikzpicture}

Context sources and catalogs

Where does context come from in a real system?

As systems grow, teams add a context catalog: a registry of what fields exist, who owns them, their freshness and sensitivity. Tools like DataHub and Atlan play this role for data; modus and similar tools for retrieval orchestration. You do not need enterprise tooling on day one, but you need the discipline: know what context exists, where it comes from, and how fresh it is.

Compaction: the technique that makes long tasks possible

When a conversation or agent run approaches the budget, you cannot simply truncate — you lose decisions and open loops. Compaction summarizes the history into a compact, structured form and continues from it.

A good compaction prompt preserves:

COMPACT = """Summarize the conversation so work can continue.
Keep: decisions (+ reasons), open tasks, exact IDs/paths/numbers, user constraints.
Drop: greetings, restated context, resolved dead ends.
Output sections: DECISIONS / OPEN / ARTIFACTS / CONSTRAINTS."""
def compact(history):
    return client.chat.completions.create(
        model="gpt-4o-mini", temperature=0,
        messages=[{"role": "system", "content": COMPACT},
                  {"role": "user", "content": history}],
    ).choices[0].message.content

Two caveats from the 2026 literature. First, Anthropic’s guidance is to tune compaction for recall: it is better to keep one extra useful detail than to drop something needed. Second, there is a counter-trend: with prompt caching so cheap, a 2026 study (Louis Bouchard) found that for some chats, keeping the full history cached can be cheaper, faster, and more faithful than compacting. The rule is task-dependent — measure both. Compaction wins for long agent runs with exploding tool output; keep-everything wins for bounded, cached chats.

Isolation and multi-agent context

When several agents collaborate (Chapter 11), sharing one giant context is the naive mistake: every agent’s noise poisons every other. The mature patterns are:

This keeps the parent’s window clean and makes failures attributable. It is also a security boundary: an untrusted sub-agent cannot inject into the main one if only typed results cross the boundary.

Context failure modes

Name them so you can catch them:

Failure What it looks like Fix
Context rot long context, answer ignores the middle compact, reorder, reduce size
Distraction answer cites irrelevant doc rerank, raise score threshold
Poisoning model follows injected instructions treat content as data, isolate, moderate
Staleness old fact wins over new freshness filters, timestamps
Drift earlier wrong turn repeated compact and correct, or reset
Overflow request errors / truncates budget accounting, compaction
\begin{tikzpicture}[font=\rmfamily, >=stealth,
  b/.style={draw, thick, rounded corners=3pt, minimum width=1.7cm, minimum height=0.62cm, font=\rmfamily\small},
  a/.style={->, thick, black!55}]
  \node[b, fill=red!10] (p) at (-2.4,0) {poisoning};
  \node[b, fill=orange!12] (d) at (0,0) {distraction};
  \node[b, fill=yellow!20] (r) at (2.4,0) {rot};
  \node[b, fill=blue!10] (o) at (0,-1.3) {overflow};
  \draw[a] (p) -- (o); \draw[a] (d) -- (o); \draw[a] (r) -- (o);
  \node[font=\rmfamily\small, text=black!60, anchor=north] at (0,-1.9) {all roads lead to a bad answer unless measured};
\end{tikzpicture}

Evaluating context (not just answers)

You cannot tune context blindly. Keep a small evaluation set of query → expected evidence pairs and measure the pipeline before generation:

# recall@k sanity check for your retrieval stage
def recall_at_k(queries, retriever, k=5):
    hits = 0
    for q, expected_doc in queries:          # 50-200 labeled pairs
        got = retriever(q, k=k)
        if expected_doc in [d.id for d in got]:
            hits += 1
    return hits / len(queries)
# aim > 0.9 on your golden set before blaming the model

When an answer is wrong, the first question is never “how do we prompt better?” It is “was the right evidence in context?” Most of the time, it was not.

Pitfalls

QQuestionSelf-check

Why can a smaller context beat a bigger one? What is compaction and when is it unnecessary?

ASolution

Because attention is finite and noise distracts: fewer, higher-signal tokens raise the chance the model actually uses the right evidence, and they cost less. Compaction summarizes history to fit the budget; with cheap prompt caching and bounded chats, keeping everything can win, so compaction is unnecessary when the context is small and cached and the task does not explode tool output.

Next: Types of Models (AI Engg #5) — now that you can steer context, which frozen model do you point it at?