Context engineering

In one sentence

Deciding, at every step of an agent or pipeline, exactly which tokens enter the window (instructions, tools, documents, tool results, memory, history), aiming for the smallest set of high-signal tokens.

Analogy: A surgeon's tray: the nurse doesn't dump the whole supply room on it, but lays out the instruments for this step and swaps them as the operation moves on.

Every step rebuilds the window from curated sources; bulky material is trimmed, summarized, or kept outside and loaded on demand.

How it works

  • In an agent, the context is rebuilt dozens of times per task and grows with every tool call.
  • Attention is a finite budget: as the window fills, recall and reasoning degrade while cost and latency rise.
  • Load just in time: keep file paths or ids and let tools fetch content when needed.
  • Trim tool output, clear stale results, and compact history into a summary near the limit.
  • Sub-agents explore in a clean context and return a ~1–2k-token summary, not their full exploration.

Check yourself

Answer to mark it learned; your answers aren't scored.

Your support agent's system prompt holds the full 300-page product manual plus all 40 tools, loaded upfront "just in case". It often confuses overlapping tools and ignores key instructions. Best fix?

Go deeper

Full explanation

Prompt engineering is writing one good instruction. Context engineering is curating everything the model sees on every turn of a multi-step system: system prompt, tool definitions, retrieved documents, tool results, memory and history. In an agent, that context is rebuilt dozens of times per task and grows with every tool call.

The constraint: attention is a finite budget. As the window fills, recall and reasoning degrade (Lost in the middle & context rot) while cost and latency rise. Anthropic frames the goal as finding the smallest set of high-signal tokens that maximizes the chance of the desired outcome.

Techniques that work:

  • Just-in-time retrieval: keep lightweight references (file paths, URLs, query ids) and let the agent load content with tools (grep, head, search) when needed, instead of pre-loading everything.
  • Trim tool output: return IDs and summaries, paginate, truncate; clear stale tool results.
  • Compaction: near the limit, summarize history (decisions, open bugs, next steps) and continue from the summary.
  • Structured notes: the agent writes progress to a file (NOTES.md, a to-do list) outside the window and re-reads it.
  • Sub-agents: delegate a search to an agent with a clean context; it returns a 1–2k-token summary, not its 50k tokens of exploration.
  • Lean system prompt and toolset: guidance at the "right altitude", few non-overlapping tools.
Code Trim tool output and compact history on a budget
pythonTrim tool output and compact history on a budget
import anthropic

client = anthropic.Anthropic()
MODEL = "claude-sonnet-5-5"  # any long-context model
BUDGET = 100_000             # compact well before the hard window limit
KEEP_RECENT = 8              # latest messages stay verbatim

def trim_tool_result(text: str, limit: int = 4_000) -> str:
    # Tool output is the usual bloat: keep head + tail, tell the agent how to get more
    if len(text) <= limit:
        return text
    note = "\n[... truncated; call read_file with an offset for more ...]\n"
    return text[: limit // 2] + note + text[-limit // 2 :]

def compact(history: list[dict]) -> list[dict]:
    # Real code: split on a turn boundary, never between tool_use and tool_result
    old, recent = history[:-KEEP_RECENT], history[-KEEP_RECENT:]
    summary = client.messages.create(
        model=MODEL, max_tokens=2_000,
        messages=[{"role": "user", "content":
            "Summarize this agent transcript for your future self: goal, decisions, "
            "open bugs, files touched, next step. Drop raw tool output.\n\n"
            + render(old)}],  # render(): messages -> plain text
    ).content[0].text
    return [{"role": "user", "content": f"<progress>{summary}</progress>"}] + recent

def prepare_context(system: str, history: list[dict]) -> list[dict]:
    used = client.messages.count_tokens(
        model=MODEL, system=system, messages=history
    ).input_tokens
    return compact(history) if used > BUDGET else history
Real example

A coding agent fixing a broken test suite ran out of window after ~40 tool calls: 70% of its 180k tokens were raw pytest and cat output it had already acted on. Changes: tool results capped at ~4k characters with a pointer to read more; results older than 10 turns cleared; a NOTES.md holding the plan and findings; codebase search delegated to a sub-agent that returns a ~1.5k-token summary. The same tasks now peak at ~60k tokens of context, each step is cheaper, and the "forgot what it was doing" loops mostly disappeared.

Trade-offs +3 · −3

+ You gain

  • Often the biggest quality lever for agents, bigger than swapping models.
  • Cuts cost and latency on every one of the dozens of calls an agent makes.
  • Makes long-horizon tasks possible beyond a single context window.

− You pay

  • Every summary or trim is lossy: drop the wrong detail and the agent repeats work or contradicts itself.
  • More moving parts (summarizers, memory stores, sub-agents), each needing its own evals.
  • Sub-agents multiply tokens: Anthropic's multi-agent research system used ~15× the tokens of a chat.

Use it when

Any agent or multi-step pipeline that makes more than a handful of tool calls, accumulates history, or pulls several sources into one window.

Avoid it when

Single-shot calls with small, fixed inputs: a well-written prompt is enough, and summarization or memory layers only add failure modes.

Numbers to know 3
  • Anthropic: a sub-agent may explore with tens of thousands of tokens but returns a condensed summary of ~1,000–2,000 tokens.
  • Anthropic's multi-agent researcher: ~15× chat tokens; token usage alone explained ~80% of performance variance on BrowseComp.
  • Anthropic reported that clearing stale tool results cut token use by 84% in a 100-turn web-search eval.
Common pitfalls 4
  • Dumping a full 50 KB API response into the window when the next step needs 5 fields.
  • Compaction prompts that drop decisions and open bugs, so the agent retries what already failed.
  • Loading the whole knowledge base and every tool upfront "just in case": more distractors, more confusion between overlapping tools.
  • Never measuring context composition: log tokens per source (system, tools, history, tool results) at every step.
Interview questions 3

Answer out loud first, then reveal.

How is context engineering different from prompt engineering?Show answer

Prompt engineering optimizes one static instruction. Context engineering is a systems problem: in an agent, the window is rebuilt on every step from many sources (system prompt, tools, retrieved docs, tool results, memory, history) and it grows on its own. So I design it like a cache with a budget: what is always present, what loads just in time, what gets summarized, what gets evicted. The typical failure isn't a badly worded instruction; it's the right instruction drowned in 150k tokens of stale tool output.

Your agent gets worse after ~40 steps. How do you fix it?Show answer

First I measure tokens per step by source; usually tool results dominate. Then, cheapest first: trim tool output at the source (IDs and summaries, pagination), clear old tool results, add structured notes so progress survives outside the window, and compact history with a summary that keeps decisions and open issues. If the task has independent sub-searches, I move them to sub-agents with clean contexts. I validate each change on long-horizon evals, because compaction can silently drop the one detail that matters.

When would you avoid sub-agents?Show answer

When subtasks are tightly coupled, like edits across one codebase: each sub-agent sees only its slice and makes decisions that conflict with the others. They shine on breadth-first, parallelizable work such as research, where each branch can be summarized independently. They also cost a lot (Anthropic reported ~15× chat tokens for its multi-agent system), so the value of the task has to justify the bill.