Skip to content

Context Engineering: The Discipline Behind Reliable Agents

Context engineering is deciding what an AI agent sees on every turn. Learn the techniques for budgeting, compacting, and structuring context for reliable agents.

TechnoKeen Engineering 9 min read Published
On this page

Context engineering is the practice of deciding exactly what information an AI agent sees on each model call: instructions, tool definitions, retrieved data, conversation history, and intermediate results. Prompt engineering asks how to phrase a request. Context engineering asks what belongs in the window at all, in what order, and what should be dropped as a task runs long. For agents that take dozens of steps, it is usually the difference between a demo and a system you can rely on.

Key takeaways

  • The model only knows what is in its context window on that call. Most agent failures that look like “the model got confused” are really context failures: missing facts, stale facts, or too much noise.
  • Treat context as a budget. Every token of tool output, history, or instructions competes with every other token for the model’s attention.
  • The core techniques are selection (load only what’s needed), compaction (summarize or trim as you go), externalization (store state outside the window), and isolation (give sub-tasks their own clean context).
  • Long contexts are not free even when they fit. Recall of details buried in the middle of very long inputs tends to degrade, and cost and latency scale with every token.
  • Build context deliberately in code with a clear assembly step, and log the assembled context so you can debug what the model actually saw.

Why context is the real interface

A model call is a pure function: context in, tokens out. Whatever the agent “remembers,” “knows,” or “decided earlier” only matters if it’s present in the input to the current call.

In a single-turn chatbot, the context is small and mostly written by a human. In an agent, the context grows on every step. Tool results pile up. Earlier reasoning stays in the transcript. Error messages from failed attempts linger. After thirty steps, the window might be dominated by a 4,000-line log file the agent read on step three and no longer needs.

Consider a coding agent fixing a failing test. On step one, its context holds the task, the repo structure, and the test output. By step twenty, it also holds six file reads, two failed patch attempts, three test runs, and its own commentary. The original task description is now a small fraction of the window. If the agent starts optimizing for the wrong goal, the cause is often visible right there.

Anthropic’s Building effective agents makes the related point that tool definitions deserve as much engineering attention as prompts. Context engineering extends that attention to everything that enters the window.

The anatomy of an agent’s context

It helps to name the parts, because each one needs a different policy.

+--------------------------------------------------+
| System instructions     stable, cacheable         |
| Tool definitions        stable per agent/task     |
| Long-term memory/facts  selected per task         |
| Retrieved documents     selected per step         |
| Conversation history    grows; needs compaction   |
| Recent tool results     large; needs trimming     |
| Current state / plan    small; always fresh       |
+--------------------------------------------------+
Component Typical failure Policy
System instructions Bloated with edge cases; contradictory rules Keep short, structured, and versioned
Tool definitions Too many tools; overlapping descriptions Load per task; namespace clearly
Memory Stale or irrelevant facts injected every time Retrieve by relevance; include timestamps
Retrieved docs Whole documents where one section would do Pass excerpts with source IDs
History Grows without bound Summarize older turns; keep recent turns verbatim
Tool results Huge raw payloads Truncate, filter, or summarize at the tool boundary
Current state Missing, so the model re-derives it each turn Maintain explicitly and re-inject

Technique 1: Selection

The cheapest token is the one you never add. Selection means loading only the context a step actually needs.

Tools. An agent with eighty tools available on every turn will spend attention, and tokens, on all eighty. If the task is “reconcile this invoice,” it probably needs five. Route tasks to tool subsets, or let the agent request additional tool groups when it needs them.

Memory. Don’t inject every stored fact about a user into every call. Retrieve facts relevant to the current task. Our guide to designing memory for AI agents covers the retrieval side in detail.

Documents. Prefer passing the relevant section with a source reference over the full document. If the model needs more, give it a tool to read further. This “just in time” approach, where the agent holds lightweight references like file paths or document IDs and loads content on demand, scales better than front-loading everything.

Technique 2: Compaction

Compaction shrinks what’s already in the window. There are three levels, from cheap to expensive.

Trim at the tool boundary

The best place to control tool output is inside the tool. Return the fields the model needs, cap result counts, and truncate long text with a clear marker. A tool that returns raw API JSON is pushing a context problem onto every caller. See tool design for AI agents for patterns.

Clear stale tool results

Once the agent has acted on a tool result, the full payload often has no further value. Replacing it with a short stub (“[file contents of src/auth.ts, 412 lines, read at step 3; re-read if needed]”) keeps the transcript coherent while reclaiming space. The agent can always call the tool again.

Summarize older history

When the conversation grows past a threshold, replace older turns with a structured summary: decisions made, facts established, open questions, and what’s been tried and failed. Keep the most recent turns verbatim, because the model needs exact recent detail to continue smoothly.

Summarization is lossy, so design the summary format around what the agent must not forget. A generic “summarize the conversation above” prompt will drop the one constraint that mattered.

Technique 3: Externalization

Some state doesn’t belong in the transcript at all. Store it outside the window and inject a compact view of it.

  • Plans and task lists. Keep the current plan as a structured object the agent updates through a tool. Re-inject it near the end of the context each turn so it stays salient.
  • Scratch files. Long-running agents can write notes to a file or key-value store, then read them back later. This is how an agent can work coherently across many context resets.
  • Artifacts. Generated code, drafts, and reports live in storage. The context holds a reference and maybe a short preview.

Externalized state is also easier to inspect, test, and resume after a crash than state that only exists in a growing message list.

Technique 4: Isolation

When a sub-task needs a lot of exploration, run it in a separate context. A sub-agent searches through forty files, then returns a two-paragraph summary to the parent. The parent’s window never sees the forty files.

This is one of the strongest arguments for multi-agent systems: not that multiple “personas” are smarter, but that each gets a clean, focused context. The trade-off is that the parent only knows what the sub-agent chose to report, so the return format needs to be specified as carefully as any API.

A context assembler in practice

Context engineering works best as an explicit step in code, not an accident of appending to a list. Here is a simplified TypeScript assembler that builds each call’s messages from typed components under a token budget.

type Role = "user" | "assistant";

interface Message {
  role: Role;
  content: string;
}

interface Turn extends Message {
  step: number;
  kind: "chat" | "tool_result";
  toolName?: string;
}

interface AgentState {
  task: string;
  plan: string[];              // externalized plan, updated via a tool
  facts: string[];             // selected memory relevant to this task
  history: Turn[];             // full transcript, kept outside the window
  summaryOfOlderTurns?: string;
  currentStep: number;
}

interface Budget {
  total: number;               // tokens available for messages
  recentTurnsVerbatim: number; // how many recent turns to keep in full
  toolResultStaleAfter: number;// steps before a tool result is stubbed
}

// Rough estimate; swap in your provider's tokenizer or token-count API.
const estimateTokens = (text: string): number => Math.ceil(text.length / 4);

function stubToolResult(turn: Turn): Turn {
  const lines = turn.content.split("\n").length;
  return {
    ...turn,
    content:
      `[Earlier ${turn.toolName ?? "tool"} result from step ${turn.step}, ` +
      `${lines} lines, cleared to save context. Call the tool again if needed.]`,
  };
}

export function assembleContext(state: AgentState, budget: Budget): Message[] {
  const header: Message = {
    role: "user",
    content: [
      `## Task\n${state.task}`,
      state.facts.length ? `## Relevant facts\n${state.facts.map((f) => `- ${f}`).join("\n")}` : "",
      state.summaryOfOlderTurns ? `## Progress so far\n${state.summaryOfOlderTurns}` : "",
    ].filter(Boolean).join("\n\n"),
  };

  // Plan goes last so it is fresh and salient on every call.
  const planFooter: Message = {
    role: "user",
    content:
      `## Current plan (step ${state.currentStep})\n` +
      state.plan.map((p, i) => `${i + 1}. ${p}`).join("\n"),
  };

  const fixedCost = estimateTokens(header.content) + estimateTokens(planFooter.content);
  let remaining = budget.total - fixedCost;
  if (remaining <= 0) {
    throw new Error("Header and plan exceed the context budget; trim facts or summary.");
  }

  // Walk history newest-first, keeping what fits.
  const kept: Turn[] = [];
  const newestFirst = [...state.history].reverse();

  for (const [i, original] of newestFirst.entries()) {
    const isRecent = i < budget.recentTurnsVerbatim;
    const isStale =
      original.kind === "tool_result" &&
      state.currentStep - original.step > budget.toolResultStaleAfter;

    const turn = !isRecent && isStale ? stubToolResult(original) : original;
    const cost = estimateTokens(turn.content);

    if (cost > remaining) break; // older turns are covered by the summary
    kept.push(turn);
    remaining -= cost;
  }

  const historyMessages: Message[] = kept
    .reverse()
    .map(({ role, content }) => ({ role, content }));

  return [header, ...historyMessages, planFooter];
}

A real implementation needs more than this. Most provider APIs require strict user/assistant alternation and pair each tool result with the tool call that produced it, so you would trim on turn boundaries and keep call/result pairs together. You also need a background step that refreshes summaryOfOlderTurns when history falls out of the window. But the shape is the point: context is assembled from typed parts under an explicit budget, and each part has its own policy.

Ordering and structure

Where content sits in the window affects how well the model uses it.

  • Put stable content first. System instructions and tool definitions rarely change, so placing them at the start lets provider-side prompt caching reuse them across calls. That reduces latency and cost.
  • Put the freshest, most decision-relevant content last. The current plan, the latest tool result, and the specific question for this step belong near the end.
  • Use clear structure. Headings or XML-style tags around documents, facts, and instructions help the model tell them apart. Tagging retrieved content as data also makes it easier to instruct the model not to follow instructions found inside it, which helps, though it is not a complete defense against prompt injection.
  • Include provenance. Source IDs and timestamps on facts and documents let the model resolve conflicts and cite its sources.

Debugging context problems

When an agent misbehaves, the first question is always: what exactly did the model see on the failing call? If you can’t answer that, you’re guessing.

A practical checklist:

  1. Log the fully assembled context for every model call, or at least a reproducible reference to it. Our guide to observability for AI agents covers how to capture this with tracing.
  2. Check for absence. Was the fact the agent needed actually in the window? Agents can’t use what they weren’t given.
  3. Check for staleness. Was an outdated version of a fact present alongside, or instead of, the current one?
  4. Check for noise. What fraction of the window was relevant to the step? Large irrelevant tool outputs are a common culprit.
  5. Check for contradictions. Do the system prompt, memory, and retrieved docs disagree? The model will pick one, and not always the one you’d choose.
  6. Replay with edits. Re-run the failing call with a modified context to confirm the diagnosis before changing code.

Turn each confirmed failure into an eval case so the fix stays fixed.

Common anti-patterns

  • The append-only transcript. Every message and tool result ever produced, forever. It works for short tasks and collapses on long ones.
  • The kitchen-sink system prompt. Hundreds of lines of rules accumulated from past incidents, many of them conflicting or irrelevant to the current task.
  • Raw API payloads. Tool results passed through unfiltered because writing a formatter felt like extra work.
  • “Just use a bigger window.” Larger windows raise the ceiling, but they don’t remove the cost of noise, and attention to detail across very long inputs is uneven.
  • Invisible assembly. Context built in five different places in the codebase, so nobody can say what the model receives.

FAQ

How is context engineering different from prompt engineering?

Prompt engineering focuses on wording instructions well for a single call. Context engineering covers everything that enters the window across a multi-step run, including tools, memory, retrieved data, history, and state, and how that changes over time. Good prompts are one part of good context.

Do larger context windows make context engineering unnecessary?

No. Bigger windows let you fit more, but every token still adds cost and latency, and models tend to use details buried deep in very long inputs less reliably. Selection and compaction remain valuable even when everything technically fits.

When should we summarize history versus clear tool results?

Clearing stale tool results is cheap and nearly lossless when the agent can re-fetch the data, so do it first. Summarization is more expensive and lossy, so reserve it for when the conversation itself, meaning decisions and reasoning, has grown too large. Design the summary format around what the agent must retain.

How do we measure whether context changes helped?

Run the same eval suite before and after the change and compare task success, steps per task, and tokens per task. Context changes often improve cost without changing accuracy, or vice versa, so track both. Our guide to agentic RAG discusses separating retrieval quality from answer quality, which applies here too.

Working with TechnoKeen

We help teams diagnose unreliable agents by tracing what the model actually sees and rebuilding context assembly around explicit budgets and policies. If your agent works in demos but drifts on long tasks, let’s talk. You can also find related terms in our glossary.

  • #context engineering
  • #context window
  • #agent reliability
  • #prompt engineering

TechnoKeen Engineering

TechnoKeen is an enterprise agentic AI company. Our engineers design, deploy, and govern AI agents for organizations in regulated and complex industries, and share what we learn in the field.

About TechnoKeen →

Keep reading

Engineering 9 min read

How to Choose an AI Agent Framework in 2026

How to choose an AI agent framework: compare graph, role-based, provider SDK, and minimal approaches by control, observability, lock-in, and team fit.

Ready to put agents to work?

Book a 45-minute executive briefing. We will review your priority workflows, current AI efforts, and risk posture, then outline a clear path to agents in production.