By Abhijith N M · Reviewed 24 October 2026 · Editorial standards
Your agent is 41 turns into a customer conversation. The API rejects the request because the context is too long, and you have to remove about 6,000 tokens. You do the obvious thing and send only the last 20 turns.
Twenty minutes later the next tool call fails with a 404. The account id was in turn 3. The model now asks the customer for their email a second time, then apologises for a problem that does not exist. You removed tokens and lost a fact.
There are only three ways to free space, and they differ in cost. Learn the order.
Prune. Shrink text before it enters the window. A tool result can lose 30 fields with no model call at all.
Compact. Replace a span of turns with a short structured summary. This costs one model call and one careful instruction.
Isolate. Move a unit of work into a subagent with its own window, then bring back only the result.
Truncation, the habit most teams reach for, is absent on purpose. It removes text without deciding what matters.
The best place to prune is where a tool result enters your loop. Your code already knows which fields the agent uses, because the tool schema describes them. Drop the rest, and tell the model what you dropped.
ORDER = {
"id": "A-4471",
"status": "delivered",
"total_cents": 34900,
"currency": "USD",
"items": [{"sku": "V-1", "name": "Vase", "qty": 1, "cents": 34900}],
"shipping": {"carrier": "NWL", "events": [{"code": "SCAN"}] * 22},
"notes": "leave at door " * 60,
}
KEEP = ("id", "status", "total_cents", "currency", "items")
def prune(record, keep):
kept = {key: record[key] for key in keep if key in record}
dropped = [key for key in record if key not in kept]
return kept, dropped
kept, dropped = prune(ORDER, KEEP)
print("kept:", len(kept), "fields")
print("dropped:", len(dropped), "fields ->", ", ".join(dropped))
print(f"[{len(dropped)} fields omitted from get_order; ask again if needed]")Two details make this safe. The note tells the model that fields are missing, so it asks again instead of assuming they are empty. The full record stays in your database, so pruning removes tokens, not data.
Compaction replaces a range of turns with a summary. A good summary is not a summary of the conversation; it is the state a new reader would need in order to continue the work.
Keep four things: decisions already made, constraints that still apply, identifiers in flight, and open questions. Drop pleasantries, raw payloads and dead ends, unless the dead end stops a repeated search.
COMPACTION_INSTRUCTION = """Rewrite the transcript below as SESSION STATE.
Use these six headings and no others. Quote every constraint word for word.
Never invent an identifier. Never round a number.
DECIDED: what has been agreed, one line each
CONSTRAINTS: rules that still bind this session, quoted exactly
IDS: order, customer, ticket and thread identifiers
TRIED: approaches that failed, and why, in one line each
OPEN: questions that still need an answer
NEXT: the single next action
Do not summarise the customer's tone. Do not include raw tool output."""
def compaction_request(transcript):
return COMPACTION_INSTRUCTION + "\n\n--- transcript ---\n" + transcriptStore the original span under an id before you compact. If a later question depends on an exact quote, your code can re-read the source instead of trusting the summary.
Some content must survive any compaction untouched:
A subagent is a separate model run with its own window and its own instruction. The parent sends a narrow task and receives a short result. The 40,000-token log never touches the parent's budget, and the parent's rules never compete with it.
Isolation has a cost: the parent cannot see why the subagent decided something. Ask for the answer plus the two or three facts it used, not a transcript. If the parent needs the reasoning, the work belongs in the parent.
Compaction loses state unless the state lives somewhere stable. A scratchpad is a small block of structured text that the model rewrites rather than appends. Put it near the end of the prompt, where your rules and the current question sit.
STATE = {
"customer_id": "C-88",
"order_id": "A-4471",
"hard_rule": "refund over $200 needs a human approver",
"decided": "customer rejected the replacement",
"open": "approval for $349 is still missing",
"next": "escalate to the billing queue",
}
def render(state):
lines = [f"- {key}: {value}" for key, value in state.items()]
return "SESSION STATE (rewrite, do not append)\n" + "\n".join(lines)
print(render(STATE))Six fields is enough for most agents. The value is not the format; it is that the block is replaced instead of growing. When you compact, the scratchpad is the part you copy forward verbatim.
Pick one long session. Prune one tool result down to five fields, write the compaction instruction for turns 1 to 12, and add the six-field scratchpad. Run the same question against the pruned session and the original. Record two numbers: tokens sent, and whether the answer still respects the $200 limit.
Key takeaways
Free space in order: prune, then compact, then isolate. Truncation is not on the list.
Prune tool results where they enter the loop, and say what you dropped.
Compact into decisions, constraints, ids, open questions and the next action.
Isolate bulk work in a subagent and bring back evidence, not a transcript.
A rewritten six-field scratchpad carries state across compaction.
Written and edited by the nexGenCoders team. Spotted a mistake? Tell us and we will fix it.
Don't lose this lesson
Create a free account to save your progress, keep your streak, and work toward a shareable certificate.