Add `Agent.compact_history()` to compact a message history without continuing the conversation

Merged
DO
8d ago
+2105-51

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, so WrapperAgent gets it.
    • It calls self.run(..., compact={'reason': ..., 'focus': ...}), so there's no second compaction path. A durable agent's or wrapper's run() sees an ordinary run.
  • It's a real run that ends after its compaction step:
    • wrap_run, before_run, before_model_request, the start and end compaction events, and after_run all fire. after_run gets the real AgentRunResult, whose output is None.
    • No model request is sent, so after_model_request doesn't run, and usage.requests stays 0. The compaction's usage is still billed.
    • The run is marked compaction-only by a context variable. _prepare_run consumes it at the start, like take_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 with FinalResult(None).
    • A failed compaction is still the attempt's error, so ModelFallback and the error hooks act on it as before, and the next attempt compacts again.
  • CompactionRunResult, exported from pydantic_ai and pydantic_ai.agent:
    • all_messages(): the compacted history.
    • new_messages(): the messages the compaction wrote, up to its record's kept_from. It's empty when nothing compacted.
    • compactions, usage, run_id, conversation_id, metadata, and the _json variants.

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_from and replaced describe the history as given and as returned, so summarized is 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.
  • Histories it refuses, with a UserError before any handler runs: an empty history, unanswered tool calls (running them would continue the conversation), and a suspended response.
  • reason= is a keyword next to focus=, so a host compacting before the cache expires can report 'cache_expiry'.
  • No sync variant. iter(), run_stream_events() and realtime() don't have one either, and a host compacting while the user is idle already has an event loop.
  • Not included: a conversation= input or conversation property for ConversationStore. 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_history handler on a FunctionModel agent, and a FunctionModel's compact_messages through NativeCompaction.
    • 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 a DBOS.workflow with DBOSDurability, the only step is compact_messages, and after_run sees an output of None.

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.