Interview's MateAI Engineering
Interview's Mate

AI Engineering

LLMs, RAG, agents & evals

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
AI Engineering topics
Lesson 58/ 160
03. AI Agents

Context Compaction

Summarize and prune history so long agent runs stay within token budgets.

AdvancedSummarize · Prune3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidHands-onQuiz (3)Practice

In plain words

When the AI's notebook gets full, it writes a short summary of what matters and clears the rest, keeping the full record somewhere it can look up.

Think of it like…

Taking meeting minutes: after two hours you don't keep the transcript on the table; you keep a one-page summary of decisions and action items, and file the full recording in case someone needs a detail.

Where you’ve seen it

A research agent running for 3 hours reaches 160,000 of 200,000 tokens. The harness triggers compaction: it first clears the content of tool results older than the last 10 (keeping a one-line description of each), then asks a model to write a summary containing the user's goal and constraints, the sources already checked with verdicts, findings so far with citations, and next steps. The new context is the system prompt, the 1,800-token summary and the last 10 steps (about 25,000 tokens). Full transcripts are saved to a file for lookup, and an evaluation shows the agent still recalls early constraints in 96 percent of probes.

Words you’ll hear

Compaction
Replacing a long history with a shorter representation that preserves what's needed.
Tool-result clearing
Removing old, bulky tool outputs while keeping a note that the call happened.
Structured summary
A summary with fixed sections: goal, constraints, decisions, progress, open items.
Trigger threshold
The context fill level at which compaction runs.

Visual diagram

Loading interactive diagram

Theory & deep dive

What to prune and what to keep

Start with the cheapest, safest reduction: clear stale tool results. Once the agent has used a search result or file listing, the raw output rarely needs to stay; replace it with a stub ("search('refund policy') → 5 results, top: policy.md; details cleared") so the agent knows it can re-run the call. Then summarise older conversation into a structured record. Preserve: the user's goal and constraints, key decisions and their reasons, work completed and where artefacts are, facts learned (with sources), failed approaches to avoid repeating, and the next steps.

Move detail out of context: write notes to a scratchpad or memory file the agent updates as it works (a TODO list, findings, design decisions), and archive full transcripts and tool outputs to storage with ids the agent can fetch. Some provider APIs offer server-side context editing or automatic compaction features; otherwise implement it in your harness. Keep the most recent steps verbatim, since they contain the immediate working state.

A summary template

"GOAL: … CONSTRAINTS: … DECISIONS (with why): … DONE: … FINDINGS (source): … DEAD ENDS: … OPEN QUESTIONS: … NEXT STEPS: … FILES/ARTEFACTS: …" Fixed sections reduce the chance of dropping critical items.

Key takeaway: Clear old tool results first, then summarise with a fixed template, and archive originals.

Risks, triggers and evaluation

Risks: information loss (a constraint or detail disappears), summary drift (errors accumulate when summarising summaries), hallucinated summaries (facts the agent never found), and cache invalidation (changing the early context breaks prompt-cache prefixes, raising cost). Mitigate by pinning critical items outside the summarised region (the goal and constraints in the system prompt or a pinned block), compacting at coarse intervals rather than every turn, using a strong model for summaries with instructions to use only information present, and keeping full archives for re-lookup.

Choose triggers: a fill threshold (70 to 80 percent of the window or a fixed token count), step counts, or task phase boundaries (after finishing a sub-task). Evaluate empirically: run long tasks with and without compaction, probe recall ("what was the budget constraint?") after each compaction, compare task success, tokens and cost, and review summaries manually on samples. If compaction frequently loses critical information, shorten tasks with sub-agents (each with its own clean context returning a summary) or change the summary template.

A recall probe

After compaction, inject a hidden test question such as "List the constraints the user gave at the start." Compare the answer with the true list; track the percentage correct across many runs to catch summaries that lose constraints.

Key takeaway: Pin essentials, compact coarsely, and test recall after compaction.

How it works, step by step

Step 1 of 4
Design

1. Choose triggers and budgets

Pick a fill threshold, the number of recent steps to keep verbatim and the summary size.

compact at 80% · keep last 10 steps · summary ≤ 2K
Key numbers at this step
Coarse
intervals

When to use it & trade-offs

What it is

Context compaction keeps long agent runs inside the token budget by shrinking the history: summarise older turns into a short record, prune content that's no longer needed (especially bulky tool results), and externalise details to files or memory the agent can re-read. A common design triggers compaction when the context reaches a threshold (for example 70 to 80 percent of the window), writes a structured summary of what matters (goal, decisions, progress, open tasks, key facts), and continues with a fresh context containing the summary plus the most recent steps.

Why it matters: Agents that run for hundreds of steps would otherwise hit the window limit, or earlier, slow down and degrade as the history fills with stale output. Compaction extends how long an agent can work, but it's lossy: a poor summary drops a constraint or a decision and the agent silently goes off course. Good compaction preserves what the next steps need and keeps an escape hatch to the original details.

When to reach for it

  • Coding and research agents running for hours
  • Long customer conversations with tool use
  • Any agent approaching its context limit

When to avoid or be careful

  • Summarising constraints only in prose with no pinned copy
  • Compacting on every turn
  • Discarding the original transcripts

Ways to handle long histories

Clear old tool results
Best for: Quick, low-risk reduction

Strengths: Large savings; little information loss.

Watch out: Needs stubs so the agent knows what it cleared.

Summarise and restart context
Best for: Very long runs near the limit

Strengths: Keeps working indefinitely.

Watch out: Lossy; breaks cache; summary errors.

Sub-agents with clean contexts
Best for: Exploratory work generating lots of intermediate data

Strengths: Keeps the main context lean.

Watch out: Coordination overhead and extra tokens.

Interview signals & numbers to know

When this topic comes up

  • “The agent forgets early instructions in long runs”
  • “Context limit reached mid-task”
  • “Summarise or prune?”
  • Context editing
  • Long-horizon agents

Benchmarks & rules of thumb

70 – 80% -
typical compaction trigger
160K → 27K -
tokens before and after in the example
96% -
constraint recall after compaction in the example

Common mistakes & follow-ups

Common interview mistakes

  • Summarising away a budget constraint and recommending options that violate it.
  • Compacting repeatedly so summaries of summaries drift from the truth.
  • Not archiving raw tool outputs, so details can't be recovered later.

Likely interviewer follow-ups

  • What would you keep when compacting a long agent run?
  • How do you test that compaction didn't lose important information?
  • How does compaction affect prompt caching?
Interview tip: Describe the order: clear tool results, then summarise, with goal and constraints pinned and originals archived. That sequence shows practical experience.
Loading hands-on exercise

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Context Compaction with generative AI interview Q&A and hands-on practice.

Open Generative AI Q&A →Tech Learn Q&A
Previous topic
Context Engineering
Next topic
Stop Conditions