Skip to content
Index Ai Academy
Phase 10 · Context & control

Managing the context window

Budgets, clearing old tool results, compaction and a cacheable prefix.

About 45 minutes · Model names, prices and versions checked November 2026 · A free account opens the whole lesson.
Already have an account? Sign in to open this lesson

What it covers9

First principles

What can a harness remove from history without breaking a tool exchange?

A model request has a limited context window. Keep unresolved call-and-result pairs intact, then summarize completed material while retaining the facts and references later turns need.

  1. Starting point

    Transcript fills with old messages and tool output

  2. What changes

    Compactor picks a completed boundary and preserves needed facts

  3. Result

    Newest request fits and still has coherent tool pairs

Compare all three steps
  1. Starting point

    Transcript fills with old messages and tool output

  2. What changes

    Compactor picks a completed boundary and preserves needed facts

  3. Result

    Newest request fits and still has coherent tool pairs

Complete and reverse the trace

Given Transcript fills with old messages and tool output and Newest request fits and still has coherent tool pairs, write down the missing step that connects them.

Compare with the worked step

Compactor picks a completed boundary and preserves needed facts

Now take Compactor picks a completed boundary and preserves needed facts and the result above. Write an input and an implementation that could produce this trace.

Check one starting point

Transcript fills with old messages and tool output. Check that your implementation produces the result shown above.

Try it on a new case

The oldest item is a tool call whose result remains in the next message. Can you remove just the call?

Show worked reasoning

Keep the pair together, or summarize the completed exchange as a unit when it is safe to do so. Retaining an orphaned result leaves the transcript structurally incomplete.

Run, change, and build

Check this when debugging. Thinking a bigger context window removes the need to manage context.

Trace the cause · Harness decision and state
  1. Trace the action from the proposed tool call through validation to the recorded result. Predict what survives a stop.
  2. Change one permission, cost limit, or interruption point. Compare the trace and persistent state to see which rule determined the outcome.
  3. Try the same reasoning on this case. The oldest item is a tool call whose result remains in the next message. Can you remove just the call?

Why it matters

Every model call sends the whole conversation. A coding agent that reads twenty files and runs the tests ten times can fill even a large context window within an hour. Then calls get slow and costly, quality drops as old material crowds out what matters, and finally the request is too big to send. Long-running agents depend on managing context well. This is one of the main things that separates a toy harness from a professional one.

What you'll be able to do

  • Treat the context window as a budget, and measure how much each part uses
  • Clear old tool results while keeping every tool_use paired with its result
  • Compact a long conversation into a summary at a safe cut point
  • Order requests so the stable prefix can be cached, and keep it stable
Quick check
A coding agent has read 20 files and run the tests 10 times, and its context window is nearly full. What helps most?
  1. Start the whole task again in a new session
  2. Switch off the tests to save some space
  3. Clear out old tool results it no longer needs
  4. Send every file again so nothing is forgotten
Show the answer

Clear out old tool results it no longer needs

Old file contents and test logs take up most of a long session. Trimming them, and compacting the history, keeps the context for what still matters. This lesson budgets the context like a desk of fixed size.

The idea: one window, four parts

Recall: Hosts: connecting servers to a model kept a host inside its context limits, and Tokens and the context window showed what a window holds. An agent fills its window on its own, one tool result at a time.

A budget with four parts

Picture a desk of a fixed size. Your tools, your instructions, the papers for the job and the space to write your reply all have to fit on it. A request works the same way. Each one holds: tool definitions, the system prompt, the messages, and room for the reply (max_tokens). They all share one window. The response's usage tells you the real input size, so log it every turn:

used = (u["input_tokens"] + u["cache_read_input_tokens"]
        + u["cache_creation_input_tokens"])
Quick check
One turn's usage is below. What does this print?
u = {"input_tokens": 1200, "cache_read_input_tokens": 48000,
     "cache_creation_input_tokens": 3000, "output_tokens": 900}
used = (u["input_tokens"] + u["cache_read_input_tokens"]
        + u["cache_creation_input_tokens"])
print(used)
  1. 1200
  2. 52200
  3. 49200
  4. 53100
Show the answer

52200

With caching, input_tokens counts only the uncached part. The real input is all three: 1,200 + 48,000 + 3,000 = 52,200 tokens.

Bigger isn't free even when it fits. On a buried desk, the note you need is still there, and you won't find it. Models attend less sharply to details buried in a huge context, sometimes called context rot. So the goal isn't only to fit, but to keep the context full of what matters now.

Five ways to keep it lean

  1. Send less in. Output caps, concise tool results, offset and limit (the tool registry and file tools).
  2. Clear old tool results. A file read 40 turns ago is probably stale. Replace its content with a short placeholder. Keep the tool_use and tool_result blocks, so the pairing stays valid.
  3. Compact. Replace the older part of the conversation with a summary: the task, decisions made, files changed, what's left. Keep the recent turns word for word.
  4. Move it out. Write notes and plans to files the agent can read back (memory and planning).
  5. Delegate. A subagent explores in its own context and returns only a short answer (subagents).

The Claude API can do 2 and 3 on the server. Context editing (beta) has a clear_tool_uses_20250919 strategy that clears old tool results past a threshold. Compaction (beta compact-2026-01-12) summarizes automatically when the context gets long; your loop appends the whole response.content each turn, compaction block included, and the API handles the rest.

Try it now

Step through 15 calls. The sawtooth is the whole job of context management.

In your own words
A request fits in the window. Why keep trimming it anyway?

Write a sentence or two, then compare it with a good answer in the lesson.

In code: clear, compact and cut safely

Worked example

Clear old results, keep the pairing

Replacing an old tool result frees its tokens while the conversation stays valid, because each tool_use still has its tool_result. The function builds new blocks and leaves the old list as it was.

def call(i):
    block = {"type": "tool_use", "id": i, "name": "read"}
    return {"role": "assistant", "content": [block]}

def result(i, text):
    block = {"type": "tool_result", "tool_use_id": i, "content": text}
    return {"role": "user", "content": [block]}

messages = [call("a"), result("a", "x" * 9000), call("b"), result("b", "y" * 4000)]

def clear_old(messages, keep_last=1):
    spots = [(i, j) for i, m in enumerate(messages)
             for j, b in enumerate(m["content"]) if b["type"] == "tool_result"]
    old = set(spots[:-keep_last])
    note = "[cleared: read again if you need it]"
    return [{**m, "content": [{**b, "content": note} if (i, j) in old else b
                              for j, b in enumerate(m["content"])]}
            for i, m in enumerate(messages)]

def size(messages):
    return sum(len(b.get("content", "")) for m in messages for b in m["content"])

cleared = clear_old(messages)
print("before:", size(messages), "after:", size(cleared))
print(cleared[1]["content"][0])
It runs right here in your browser, with nothing to install.

The placeholder tells the model that the file is still there and how to get it back. The newest result stays whole, since that's probably what it's working on now. The original list is untouched, so the harness can still log or compare it.

Edits and thinking blocks

On a model that thinks, such as claude-opus-5-5, replies carry thinking blocks, and each one has a signature tied to everything before it: the tools, the system prompt and every earlier message. Change an earlier turn, by clearing a result or summarizing old turns, and every thinking block after the change no longer matches. Send those blocks back and the API can reject the request with a 400 ("bound to a different conversation"). On claude-opus-5-5 it may let the request through instead, and the model then reasons from notes about text that has changed. Neither is what you want, so build as if the 400 always comes.

So in production, let the server do 2 and 3: its clearing and compaction don't count as edits, because the API checks the conversation as you sent it. When you clear or compact in your own code, as in this lesson, also drop the thinking blocks (thinking and redacted_thinking) from every assistant message after the first one you changed. Keep their text and tool calls. Dropping a run of thinking blocks from the end is allowed; editing in the middle is what breaks them.

Quick check
A harness clears the tool result in message 2 of this conversation, on a model that thinks. Which assistant messages must lose their thinking blocks before the next call?
roles = ["user", "assistant", "user", "assistant", "user", "assistant"]
changed = 2
drop = [i for i, r in enumerate(roles) if r == "assistant" and i > changed]
print(drop)
  1. [3, 5]
  2. [1]
  3. []
  4. [1, 3, 5]
Show the answer

[3, 5]

The thinking in message 1 was written before the change, so it still matches. Messages 3 and 5 came after it, so their thinking blocks no longer match the conversation and must go. Their text and tool calls stay.

Quick check
Why replace old tool results with a placeholder, rather than deleting the tool_result blocks?
  1. The model would crash if a message suddenly became much shorter
  2. Every tool_use must still have a matching tool_result, or the request is invalid
  3. Placeholders are cheaper to store than deleting blocks and rebuilding the list
  4. Deleting items from a list isn't allowed in Python while it's being sent
Show the answer

Every tool_use must still have a matching tool_result, or the request is invalid

The API checks the pairing. Keep the structure; shrink the content.

Worked example

Ten growing turns, plotted

The same sawtooth, computed: the harness clears the old results when the total passes 150,000, and keeps the last two.

import matplotlib.pyplot as plt

FIXED, RESULT, NOTE = 15_000, 12_000, 50
LIMIT, CLEAR_ABOVE, KEEP = 200_000, 150_000, 2

results, sent = [], []
for call in range(15):
    if FIXED + sum(results) > CLEAR_ABOVE:
        results = [NOTE] * (len(results) - KEEP) + results[-KEEP:]
    sent.append(FIXED + sum(results))
    results.append(RESULT)
print(sent)

plt.plot(sent, marker="o", label="tokens sent")
plt.axhline(CLEAR_ABOVE, color="gray", linestyle="--", label="clear above")
plt.axhline(LIMIT, color="red", linestyle=":", label="window")
plt.xlabel("model call")
plt.ylabel("input tokens")
plt.title("Context size per call, with clearing")
plt.legend()
plt.show()
In the lesson you can change this and run it.

Where to cut when compacting

You can't cut anywhere. If you tear pages out of an interview transcript, you mustn't leave an answer without its question. If the recent part starts with a user message of tool_result blocks, their tool_use blocks are in the part you summarized away, and the request is invalid. A safe cut is right before an assistant message: put the summary in a new first user message, then the recent turns from that assistant message on. Roles still alternate, and every result in the recent part has its tool call there too.

The summary prompt matters. Treat it as a handover note at the end of a shift. Ask for the original task, key decisions and their reasons, files touched, errors met and fixed, and the next steps. A summary that loses the task leaves an agent that's lost.

Worked example

Finding a safe place to cut

A cut must fall right before an assistant message, or some tool_result loses its tool_use. Here's a function that finds the latest safe cut that keeps enough recent turns.

roles = ["user", "assistant", "user", "assistant", "user", "assistant", "user"]
kinds = ["text", "tool_use", "tool_result", "tool_use", "tool_result", "text", "text"]

def safe_cut(roles, keep_recent):
    for i in range(len(roles) - keep_recent, 0, -1):
        if roles[i] == "assistant":
            return i
    return None

cut = safe_cut(roles, keep_recent=3)
print("cut before message", cut, f"({roles[cut]}, {kinds[cut]})")
print("summarized:", kinds[:cut])
print("kept word for word:", kinds[cut:])

cut = safe_cut(roles, keep_recent=2)
print("asking to keep 2 keeps:", kinds[cut:])
In the lesson you can change this and run it.

The search walks backward to an assistant turn, so it may keep a little more than you asked for. That's fine: keeping one extra turn costs little, and an invalid request costs the whole call.

Quick check
Compaction looks for a safe cut, right before an assistant message. What does this print?
messages = ["task", "a1", "r1", "a2", "r2", "a3", "r3"]
roles = ["user", "assistant", "user", "assistant", "user", "assistant", "user"]
cut = len(messages) - 3
while cut > 0 and roles[cut] != "assistant":
    cut -= 1
print(cut, messages[cut:])
  1. 5 ['a3', 'r3']
  2. 3 ['a2', 'r2', 'a3', 'r3']
  3. 4 ['r2', 'a3', 'r3']
  4. 0 ['task', 'a1', 'r1', 'a2', 'r2', 'a3', 'r3']
Show the answer

3 ['a2', 'r2', 'a3', 'r3']

Index 4 holds tool results, so the cut moves back to the assistant message at 3. Every kept result still has its tool call.

Drill

Where the context went

Write budget_report(parts, limit): parts maps names (system, tools, history...) to token counts. Return lines NAME: N tokens (P%), largest first, with P the share of the total rounded to a whole number, then a last line Total: T of LIMIT followed by (over by X) if T is above the limit.

def budget_report(parts, limit):
    return [f"{k}: {v}" for k, v in parts.items()]


PARTS = {"system": 3_000, "tools": 12_000, "history": 170_000, "reserve": 16_000}
for line in budget_report(PARTS, 200_000):
    print(line)
In the lesson, your code is checked as you write it.

Compaction loses things

A movie recap never has every scene, and a summary always drops detail. So write important decisions and plans to files, which survive compaction word for word, and read them back whenever you need them again later on in a session.

In your own words
Where does compaction cut, and what does it lose?

Write a sentence or two, then compare it with a good answer in the lesson.

In a production harness: the server does it for you

The cacheable prefix

If you've already checked the first 50 pages of a contract, you can skip them next time, as long as not one word has changed. Prompt caching does the same thing. It makes a repeated prefix, the unchanged start of a request, cheaper and faster. The order is tools, then system, then messages, so:

  • Put stable things first: tool definitions, then the system prompt, then the conversation.
  • Don't put the time, a random ID or a changing count in the system prompt; it would change the prefix every call.
  • Keep tool order fixed; sort them once.
  • To change instructions mid-session, append rather than edit. Recent models, claude-opus-5-5 among them, accept system role messages later in the conversation for this. Not every model does, so check before you rely on it.

Clearing and compaction do change the prefix, so the next call pays to rebuild the cache, and when your own code does them, the thinking blocks after the change go too. That's why you clear in large batches when crossing a threshold, not a little every turn.

In plain words: keep the start of every request exactly the same, and put whatever changes at the end.

Quick check
From the lesson on cost and latency: a cache hit needs the start of a request to be exactly what was sent before, which is why stable content goes first. What does this print: the blocks call 2 shares with call 1 from the start, and the blocks call 3 shares with call 2?
def shared_prefix(a, b):
    count = 0
    for x, y in zip(a, b):
        if x != y:
            break
        count += 1
    return count

call_1 = ["tools", "system", "msg 1", "msg 2"]
call_2 = ["tools", "system", "msg 1", "msg 2", "msg 3"]
call_3 = ["tools", "system v2", "msg 1", "msg 2", "msg 3"]
print(shared_prefix(call_1, call_2), shared_prefix(call_2, call_3))
  1. 5 4
  2. 4 4
  3. 4 3
  4. 4 1
Show the answer

4 1

Call 2 only added a message at the end, so all four earlier blocks can be read from the cache. Call 3 changed the system prompt, and everything after the change has to be paid for again, though the messages are word for word the same. That is why this lesson's harness only ever adds to the end.

Quick check
Which habit keeps the cacheable prefix stable?
  1. Put today's date at the top of the system prompt
  2. Sort tool definitions once and never reorder them
  3. Shuffle the tools each call
  4. Rewrite the system prompt every turn
Show the answer

Sort tool definitions once and never reorder them

Caching reuses an unchanged start of the request. Anything that changes it early makes later calls pay full price.

Drill

What breaks the cache?

Anything near the top of a prompt that changes on every request makes the cached prefix useless. Write prefix_breakers(system): return every date like 2026-11-07 and every clock time like 09:14 (or 09:14:05) found in the text, in order, using re.findall with one pattern for each.

import re

SYSTEM = ("Today is 2026-11-07 and the time is 09:14:05. "
          "You help customers of Trailhead Outfitters.")


def prefix_breakers(system):
    return []


print(prefix_breakers(SYSTEM))
In the lesson, your code is checked as you write it.

Seeing the cache work

The second call sends the same tools and system prompt, so that prefix is read from the cache. (The practice server follows the same rules: it caches prefixes of 512 tokens or more.)

import requests

PROMPT = "You are a careful coding agent for the gradient-shop project. " * 60
SYSTEM = [{"type": "text", "text": PROMPT, "cache_control": {"type": "ephemeral"}}]

def call(question):
    r = requests.post("https://api.anthropic.com/v1/messages",
        headers={"x-api-key": "added-by-the-academy-server",
                 "anthropic-version": "2026-10-21"},
        json={"model": "claude-opus-5-5", "max_tokens": 200, "system": SYSTEM,
              "messages": [{"role": "user", "content": question}]},
        timeout=60)
    r.raise_for_status()
    return r.json()["usage"]

for q in ["List the test files.", "Which tests are slow?"]:
    u = call(q)
    print(q, "| new:", u["input_tokens"],
          "| written to cache:", u["cache_creation_input_tokens"],
          "| read from cache:", u["cache_read_input_tokens"])

In an engineer's week, the symptom is a bill that climbs every turn, or an agent that forgets its task after a compaction. Check the usage line first, then whether the summary kept the task.

In your own words
What keeps the cacheable prefix stable?

Write a sentence or two, then compare it with a good answer in the lesson.

Choose how to practice

Start with a short baseline or choose guided, independent, or AI-assisted practice.

Practice what you just read

  • 5 code examples you can edit and run
  • a practice exercise that checks your code
  • a 5-question quiz
  • 9 review cards for spaced repetition

Try a quiz question

Where is it safe to cut a conversation when compacting?

  1. Right before an assistant message, with the summary as the new first user message
  2. Right before a user message that holds tool results, so the summary replaces their calls
  3. Anywhere at all, as long as the summary is good enough to cover what was removed from it
  4. In the middle of an assistant message, so that the model can finish what it was saying

Answer it at the end of the lesson to see if you're right, and why.

Before this lesson

Keep learning

Where this lesson leads.

575 lessons in thirteen phases. 176 are free without an account, and a free account opens the rest. See every lesson.

Phase 10 · about 20 hours of study

Agent harnesses

Build the software around a model that turns it into a capable, safe agent 24 lessons 1 free
  1. What an agent harness is FreeThe software around a model that turns it into an agent.35 min
  2. The core loop, built properlyStop reasons, parallel tool calls, errors and turn budgets.40 min
  3. A tool registry for agentsSchemas from functions, validation, output limits and helpful errors.40 min
  4. File and search toolsRead, write, edit by exact replacement, glob and grep inside one folder.45 min
  5. Running code safelyExecution tools, step limits, output caps and real sandboxes.45 min
  6. Giving an agent a databaseSchema as context, a query tool with caps and readable errors, guards in layers, and execution accuracy.45 min
  7. Permissions and approvalsRules, modes and approval prompts that keep a person in control.40 min
  8. Hooks and skillsExtend a harness at lifecycle events, and load know-how on demand.40 min
  9. Multi-agent systemsCoordinating many agents on one large job.35 min
  10. Managing the context windowBudgets, clearing old tool results, compaction and a cacheable prefix.45 min
  11. Memory, plans and long tasksTo-do lists, progress notes, memory files and checkpoints.45 min
  12. SubagentsHand a focused task to a fresh context with fewer tools.40 min
  13. Streaming, interrupts and sessionsLive output, stopping safely, and saving and resuming transcripts.40 min
  14. Agents as graphsState, reducers and routing, a checkpoint after every step, and pausing for a person's approval.45 min
  15. Evaluation harnessesRun agents on tasks in fresh environments and grade what they leave behind.45 min
  16. Tracing, budgets and guardrailsSee what an agent did, cap what it spends, and stop it when it loops.40 min
  17. Attack your own harnessRun fourteen attacks against a harness with switches, read which layer stops each one, score attacks stopped against ordinary tasks done, and keep every finding as a release test.40 min
  18. Capstone: build a coding agentA harness that edits a project, runs its tests and stops when they pass.45 min
  19. The same agent on the real SDKsPut the parts you built beside the tool runner and the Agent SDK, choose a surface for a job, and take an MCP server's tools into your registry with prefixed names, one rule per server and a capped result.35 min
  20. Agents that use a computerAn agent with a screen, a mouse and a keyboard: the observe-decide-act loop, what a click lands on, why a wrong hit is worse than a miss, what happens when the screen changes under a plan, and what screenshots cost.45 min
  21. Sandboxes for agents that browseTreat every page as untrusted input: check hosts properly, gate actions by their effect, and layer the defenses.45 min
  22. Protocols between agentsHand a task to an agent someone else built: agent cards, the life of a task, the messages on the wire, safe retries, and whom to trust.45 min
  23. Tracing a run end to endFollow one run across an orchestrator, subagents and tool servers: trace ids, the traceparent header, the critical path, tokens by branch, and which traces to keep.45 min
  24. Retrieval over a graphAnswer questions that hop between documents: facts as triples, a walk out from the entities a question names, and the hubs and missed facts that limit it.45 min
Practice for interviews 21 questions

AI agent interview questions and answers

Questions on designing and running agents: tools, the agent loop, permissions, context, multi-agent systems, security and evaluation.

Part of a free course 29 lessons

Free AI agents course

Learn how to build AI agents by building one: tools, the agent loop, MCP, permissions, context management and evals, ending with a coding agent that stops when its tests pass.

Part of a free course 13 lessons

LLM Harness

Build a bounded run loop, test it with scripted model responses, and recover interrupted work from an event log.

Never trained an AI? Teach a small one to write, right in your browser. It takes about 20 seconds and needs no account. Teach it to write