What is context engineering, and how do you manage context in long-running agents?

Learning path, stage 5 of 5: Shipping to production · question 6 of 10

Context engineering is deciding exactly which tokens the model sees at each step (instructions, tools, history, retrieved data, tool results) so it has what it needs and as little else as possible. In long-running agents the context fills up with old tool output, so you compact it, clear stale results, store notes outside the context, and use sub-agents with their own clean contexts.

Why it matters

  • Context is a limited budget of attention. More tokens can mean worse focus ("context rot") as well as higher cost.
  • Agents gather context quickly: a few file reads or searches can add tens of thousands of tokens.

Techniques

  • Compaction: summarise the conversation when it nears a limit and continue from the summary. Some APIs do this on the server.
  • Clearing tool results: drop old, bulky tool outputs and keep only what's needed.
  • Structured notes / memory files: the agent writes progress, decisions and todos to a file it can re-read later.
  • Just-in-time retrieval: keep lightweight references (paths, IDs, URLs) and load the content only when needed.
  • Sub-agents: delegate heavy reading and get back a short summary.
  • Lean tool design: short results, pagination, filters, a detail level.
  • A stable prefix so the prompt cache keeps working while the tail changes.

Sources

Code example

tsx
1// Server-side compaction (beta): the API summarises old context automatically.
2import Anthropic from "@anthropic-ai/sdk";
3
4const client = new Anthropic();
5const messages: Anthropic.Beta.BetaMessageParam[] = [];
6
7export async function agentTurn(userMessage: string) {
8 messages.push({ role: "user", content: userMessage });
9
10 const res = await client.beta.messages.create({
11 betas: ["compact-2026-01-12"],
12 model: "claude-opus-5-5",
13 max_tokens: 16000,
14 messages,
15 context_management: { edits: [{ type: "compact_20260112" }] },
16 });
17
18 // append the FULL content: compaction blocks must be sent back next turn
19 messages.push({ role: "assistant", content: res.content });
20
21 return res.content
22 .filter((b): b is Anthropic.Beta.BetaTextBlock => b.type === "text")
23 .map((b) => b.text)
24 .join("");
25}

To run it: follow the one-time setup guide, add npm i @anthropic-ai/sdk zod @opentelemetry/api vitest, save the code as a .ts file and run npx tsx file.ts. Anything marked declare is a part you supply.

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the AI Agents & LLMs set.

Open in study app