Add `Agent.compact_history()` to compact a message history without continuing the conversation
- Part of #11395
This builds Douwe's decision B from the design for compacting before the prompt cache expires: a dedicated method, built on a run that ends after its compaction step.
result = await agent.compact_history(messages, focus='the infrastructure decisions', reason='cache_expiry')
result.all_messages() # the compacted history
result.compactions # the `CompactionRecord`, empty when nothing compacted
What it is
AbstractAgent.compact_history(message_history, *, focus=None, reason='manual', conversation_id, run_id, model, instructions, deps, model_settings, usage_limits, cancellation_token, timeout, usage, metadata, infer_name, toolsets, event_stream_handler, capabilities, spec) -> CompactionRunResult.- It's on
AbstractAgent, soWrapperAgentgets it. - It calls
self.run(..., compact={'reason': ..., 'focus': ...}), so there's no second compaction path. A durable agent's or wrapper'srun()sees an ordinary run.
- It's on
- It's a real run that ends after its compaction step:
wrap_run,before_run,before_model_request, the start and end compaction events, andafter_runall fire.after_rungets the realAgentRunResult, whoseoutputisNone.- No model request is sent, so
after_model_requestdoesn't run, andusage.requestsstays 0. The compaction's usage is still billed. - The run is marked compaction-only by a context variable.
_prepare_runconsumes it at the start, liketake_run_binding(), so it reaches the run through any wrapper's run methods unchanged, and a run started inside it (for example a summarizer agent run from a handler) is an ordinary run.
- The graph change:
- After
_compact_attempt, a compaction-only run commits the compaction and raises a private_Compacted. The request step catches it next to_OutputSubmitted, on the streamed and the non-streamed path, and ends the run withFinalResult(None). - A failed compaction is still the attempt's error, so
ModelFallbackand the error hooks act on it as before, and the next attempt compacts again.
- After
CompactionRunResult, exported frompydantic_aiandpydantic_ai.agent:all_messages(): the compacted history.new_messages(): the messages the compaction wrote, up to its record'skept_from. It's empty when nothing compacted.compactions,usage,run_id,conversation_id,metadata, and the_jsonvariants.
Choices to review
- The empty request. Like
compact=, the run adds an empty request to compact the history with (the request being answered). Nothing answers it, so the run removes it when it ends.- The record is adjusted to match:
messages_before,messages_after,kept_fromandreplaceddescribe the history as given and as returned, sosummarizedis still right. - A history that ends with a request keeps that request, as with
compact=. Like any run continuing from such a request, the run stamps it with its own IDs.
- The record is adjusted to match:
- Histories it refuses, with a
UserErrorbefore any handler runs: an empty history, unanswered tool calls (running them would continue the conversation), and a suspended response. reason=is a keyword next tofocus=, so a host compacting before the cache expires can report'cache_expiry'.- No sync variant.
iter(),run_stream_events()andrealtime()don't have one either, and a host compacting while the user is idle already has an event loop. - Not included: a
conversation=input orconversationproperty forConversationStore. That fits the harness scheduling helper (piece 3), so it can come with it.
Tests
tests/test_compact_history.py:- The lifecycle hooks and events, streamed and not.
- Focus and reason reach a
compact_historyhandler on aFunctionModelagent, and aFunctionModel'scompact_messagesthroughNativeCompaction. - The records, compacted messages and usage.
- Nothing to compact: declined, and a cancelled start.
- A history that ends with a request.
- The histories it refuses.
- A failed compaction falling back.
- A handler's own nested run.
WrapperAgent.
tests/durable_exec/test_dbos.py::test_dbos_compact_history_runs_the_compaction_as_a_step: inside aDBOS.workflowwithDBOSDurability, the only step iscompact_messages, andafter_runsees anoutputofNone.
Checklist
- No breaking changes in accordance with the version policy.
- Any permitted compatibility impact has a label, warning, migration and release note, and an exact API-check waiver if the gate reports it.
- PR title is fit for the release changelog.
Opened by Claude (Douwe's coding agent).
Summary by cubic
Adds Agent.compact_history() to compact a message history without continuing the conversation or sending a model request. It returns a CompactionRunResult with the compacted history, compaction records, and usage.
The run fires the usual hooks and events but ends after its compaction step: the result's output is None, and a capability that answers the request itself, a retry, or a submitted output never continues the conversation. The internally added request is removed by identity (including any appended system prompt statement), whether the compaction kept it or summarized it away, so the returned history and records match the input. CompactionRunResult.new_messages() returns every message not in the given history, including one a hook queued.
Works with wrappers and durable agents (DBOS, Prefect, Temporal), staying compaction-only across Prefect flow retries and DBOS workflow recovery, and rejects empty histories, unanswered tool calls, and suspended responses with UserError. Raises when a custom AbstractAgent's run() never reaches the core Agent run, and emits the unserved-compaction warning when the agent has no compact_history hook. CompactionRunResult now has a useful repr and identity equality.