Context engineering for AI agents: a hands-on playbook

How we debug and design what goes into an agent's context window. Seven layers, a trace audit you can run today, templates for each layer, and the four ways context goes wrong.

By the AY Automate team · Updated Nov 21, 2026 · 5 min read

Time
One day per agent
Level
Advanced
Works with
Any model provider
First win
A trace audit in an hour

Inside this playbook

  • 5prompts, templates and code to copy
  • 1diagrams and real screenshots
  • 6steps, start to finish

Diagram

The playbook at a glance

  1. Map the layers

    7 kinds of context

  2. Audit a trace

    tag and count tokens

  3. Fix the prompt

    right altitude

  4. Trim tools + retrieval

    just in time

  5. Manage long tasks

    compact, notes, sub-agents

  6. Lock output + evals

    schema and test set

The playbook: measure what is in the window before you change any of it.

In short

  • Context engineering is deciding what the model sees at each step: instructions, the user's request, retrieved data, recent state, long-term memory, tool definitions and results, and the output format. Anthropic puts the goal well: find "the smallest possible set of high-signal tokens" that makes the outcome you want likely.
  • Bigger windows do not fix it. Anthropic describes context rot: as tokens pile up, the model's ability to recall and use them drops. So the job is selection, not stuffing. For the concepts and history, read our context engineering guide. This page is the hands-on part: what to check, in what order, with templates.
  • You end up with: An agent that gets the smallest set of useful tokens at each step, and a test set that proves it.

Who it is for: Engineers building agents or LLM features that work in demos and drift in production.

Overview

At a glance

  • 1. Instructions

    System prompt: role, rules, boundaries. Loaded every call.

  • 2. Tools

    Definitions of what the agent can call, plus every result it got back.

  • 3. Long-term memory

    Saved facts, preferences, past outcomes. Pulled in when relevant.

  • 4. Retrieved context

    Docs, records or search results fetched for this task.

  • 5. State

    Recent turns and working notes. The part that grows every step.

  • 6. User request

    What was asked, and how it changed over the turns.

  • 7. Output format

    Schema or format the next system expects.

Before you start

Before you start

  • One agent or LLM feature with a task that fails sometimes
  • Logs or traces that show the full prompt sent to the model
  • A way to count tokens (your provider's token counter or SDK)
  • 10 to 20 real examples of the task, with what good looks like
  • Access to change the prompt, tools and retrieval code

Step 1 · 1 to 2 hours

Audit one real trace before you change anything

Pick a run that went wrong. Dump the exact context the model saw at the failing step, then tag every chunk with its layer from the stack above and count its tokens. Most teams are surprised by what is in there: old tool results, three copies of the same doc, rules that contradict each other.

Config

Trace audit sheet (columns)

step,layer,source,tokens,needed_for_this_step(y/n),conflicts_with,notes
What to look for in the audit.
  • Tool results from many steps ago

    It usually means
    Nothing clears old results
    Go to
    Step 5
  • Whole documents where one paragraph matters

    It usually means
    Retrieval loads too much up front
    Go to
    Step 4
  • Two rules that disagree

    It usually means
    Prompt grew by patches
    Go to
    Step 2
  • Ten similar tools

    It usually means
    Overlapping tool set
    Go to
    Step 3
  • A wrong fact repeated in later turns

    It usually means
    Context poisoning
    Go to
    What breaks, below

Step 2 · 1 hour

Rewrite the system prompt at the right altitude

Anthropic names two failure modes: prompts that hardcode brittle if-else logic, and prompts so vague they assume shared context the model does not have. The fix sits between them: clear sections, strong defaults, a few examples. Plain, direct language.

Prompt

System prompt skeleton

# Role
You are [agent] for [company]. You help [who] do [job].

# Goal for every task
[What a finished, correct result looks like, in one or two lines.]

# How to work
- Start by [first action, e.g. reading the ticket and the customer record].
- Use [tool] when [condition]. Prefer [tool A] over [tool B] for [case].
- If information is missing, [ask / search / stop and report].

# Boundaries
- Never [action with real cost, e.g. issue refunds].
- Escalate to a human when [condition].

# Output
Return [format]. See the schema in the tool definition.

# Examples
<example> [short input] -> [ideal output] </example>
<example> [edge case] -> [ideal output] </example>

Step 3 · 1 hour

Trim the tool set

Every tool definition costs tokens on every call, and overlapping tools make the agent guess. Keep tools few, clearly different, and return only what the next step needs. If a human engineer could not say which tool to use for a case, the model will not either.

Code

Tool definition template

{
  "name": "search_orders",
  "description": "Find a customer's orders by email. Use this before any refund or delivery question. Returns at most 5 orders, newest first.",
  "input_schema": {
    "type": "object",
    "properties": {
      "email": { "type": "string", "description": "Customer email, exact match" },
      "status": { "type": "string", "enum": ["open", "shipped", "returned", "any"] }
    },
    "required": ["email"]
  }
}

Say when to use it, what it returns, and the limit. Return IDs and short fields, not full records.

Step 4 · Half a day

Retrieve just in time, not all up front

Anthropic describes agents that keep lightweight identifiers (file paths, stored queries, links) and load the data at runtime with tools, instead of pre-loading everything. The agent discovers context step by step. Claude Code works this way: it reads files when it needs them, rather than embedding the whole repo.

  • Small, always-needed facts (company policy summary)

    Fetch it just in time
    Large or task-specific docs
  • Data the first step cannot start without

    Fetch it just in time
    Anything the agent may or may not need
  • Stable reference that rarely changes

    Fetch it just in time
    Live records: orders, tickets, inventory

Step 5 · Half a day

Manage long tasks: compact, take notes, split

State is the layer that grows every turn. Anthropic's three techniques, and when each fits:

  • Compaction

    What it does
    Summarize the conversation near the limit and restart the window with the summary
    Use it when
    Long back-and-forth tasks
  • Tool result clearing

    What it does
    Drop raw results of old tool calls
    Use it when
    Always, it is the lightest compaction
  • Structured notes

    What it does
    Agent writes notes to a file outside the window and reads them back
    Use it when
    Iterative work with clear milestones
  • Sub-agents

    What it does
    Focused agents with clean windows return short summaries to a lead agent
    Use it when
    Research or analysis that explores a lot

Prompt

Compaction prompt

Summarize this session so a fresh agent can continue it.
Keep: the goal, decisions made and why, open questions, current state
of each sub-task, file paths and IDs referenced, and any user
preferences stated. Drop: raw tool outputs, dead ends already ruled
out (one line each), and pleasantries. Max 400 words.

Step 6 · Half a day

Lock the output and build a test set

If the next system parses the answer, give the model a schema and validate it: retry on failure, do not hope. Then turn your 10 to 20 real examples into an eval set and run it after every context change. Without it, every fix is a guess.

Diagram

The loop after every change to prompt, tools, retrieval or memory.

  1. Change one layer

    never two at once

  2. Run eval set

    same 20 cases

  3. Compare

    pass rate, tokens, cost

  4. Keep or revert

    write down why

Code

Eval case format

{
  "id": "refund-007",
  "input": "Customer says order arrived broken, wants money back",
  "context_fixture": "fixtures/refund-007.json",
  "must": ["calls search_orders", "asks for a photo", "does not issue refund"],
  "must_not": ["promises a timeline"],
  "output_schema": "schemas/support-reply.json"
}

Watch out

What breaks, and the fix

  • Context poisoning: a hallucination gets into the window and is repeated

    Fix: Validate tool outputs before they enter state, and compact with "facts confirmed by tools" only.

  • Context distraction: so much history the model loses the task

    Fix: Clear old tool results and compact. Re-state the goal at the top of the summary.

  • Context confusion: irrelevant chunks steer the answer

    Fix: Retrieve just in time and cap chunks per step. Cut what the audit marked as not needed.

  • Context clash: two parts of the window disagree

    Fix: One source of truth per fact. Rewrite patched prompts as one clean version.

  • Too many overlapping tools

    Fix: Merge or remove until each tool has one clear job.

  • Fixes that help one case and break three

    Fix: Change one layer at a time and run the eval set every time.

Results

How to measure it

  • Task pass rate

    How to track it
    Eval set of 10 to 20 real cases, after each change
    What good looks like
    Goes up, never silently down
  • Tokens per successful task

    How to track it
    Provider usage logs, divided by passes
    What good looks like
    Falls as you trim
  • Tool call errors

    How to track it
    Traces: wrong tool, bad arguments, retries
    What good looks like
    Close to zero on the eval set
  • Context size at failure

    How to track it
    Token count at the failing step in traces
    What good looks like
    Failures no longer cluster at long contexts
  • Cost per task

    How to track it
    Tokens x model price per task
    What good looks like
    Stable or lower while pass rate holds

Questions

FAQ

What is context engineering in simple terms?

Choosing what an AI model sees at each step, so it has what it needs and nothing that distracts it. Prompt writing is one part of it. Tools, retrieval, memory and output format are the rest.

Is context engineering better than prompt engineering?

It is the bigger job, not a rival. Prompt engineering is the instructions layer. Context engineering covers every layer that reaches the model, which matters once agents run many steps with tools.

Do bigger context windows make this unnecessary?

No. Anthropic reports context rot across models: recall drops as tokens pile up. A bigger window gives you room, not focus.

What is compaction?

Summarizing a long conversation near the window limit and starting a fresh window with the summary. Clearing old tool results is the lightest version of it.

How do I know if my context changes helped?

Run the same eval set before and after, and compare pass rate, tokens and cost per task. Change one layer at a time so you know what moved the number.

Where should I start if my agent is unreliable?

With the trace audit in step 1. Dump the context at a failing step and tag it by layer. The biggest problem is usually visible in the first hour.

Sources

AI Engineers

Want an engineer to build this with you?

Agent works in the demo and drifts in production? An AI engineer joins your team in 10 days and builds it with you, in your stack.

From $3,000/month. Starting price, your quote may be higher. First month money-back.