New Tool Radar

AI Agents & Automation

How to Compact an Agent Conversation Mid-Run Into a Summary

Compact an agent conversation mid-run into a summary so a long run fits the context window.

Schematic with three steps: Set the compaction trigger before the run; Summarize into the four kept facts only; Check the next step still has what.

Every turn of a run adds messages to the conversation, and a long run eventually outgrows the context window. Compaction replaces the older turns with a summary that keeps the facts the run still needs: the goal, the decisions made, the tool results that matter, and what is still open. The OpenAI Agents SDK ships a compaction session that rewrites stored history this way, checking after each turn whether the history meets the threshold and compacting only when it does. Set the trigger before the run starts, keep the summary short, and never compact away the facts the next step needs.

What you need

  • A run that grows long enough to approach the context window
  • A list of the facts the run must keep: goal, decisions, key tool results, open items
  • A compaction trigger, such as a message count or a token threshold

Step 1: Set the compaction trigger before the run

Choose the point at which compaction runs, such as after a set number of turns or when history passes a token count. A trigger set mid-run is a trigger that arrives too late.

Step 2: Summarize into the four kept facts only

When compaction runs, rewrite the older turns into the goal, the decisions made, the tool results still needed, and the open items. Leave out greetings, dead ends, and repeated attempts.

Step 3: Check the next step still has what it needs

After compaction, run the next step and confirm it uses the kept facts correctly. If it asks for something the summary dropped, the summary was too aggressive.

Worked example: synthetic compaction check

The table below is a synthetic example. It shows the expected result of mid-run compaction; no agent was run.

Check Expected Result
History compacts at the trigger Yes Pass
Summary keeps goal and decisions Yes Pass
Next step uses the kept facts Yes Pass
Context fits the window again Yes Pass

Expected result (UNTESTED). the conversation compacts at the trigger, the summary keeps the goal and decisions, and the next step runs inside the window. This check was not run live; the table shows the expected result for the synthetic example.

Limits

  • A summary loses detail by design; a fact the summary drops is a fact the run no longer has.
  • Compaction costs a model call of its own, so triggering it too often wastes tokens.
  • A bad summary can invent decisions, so check the summary against the run log the first few times.
  • Compaction rewrites history, so keep the original log elsewhere if you need an audit trail.

Sources

See all