Add `NativeCompaction`, run-level compaction requests and generic compaction profile flags
Part of #11395: step 2 of the core compaction design. Stacked on #11454 (base core-compaction-hook).
[!WARNING]
Compatibility impact: DEFAULT_PROFILE gains the supports_compaction_on_demand, compaction_instructions and compaction_result_readable keys, and the agent-spec capability registry gains NativeCompaction. No existing entry changes, but code that compares either mapping exactly sees the new keys. AnthropicModelProfile.anthropic_supports_on_demand_compaction is deprecated in favor of supports_compaction_on_demand, and still works with a warning.
Migration: expect the new keys when comparing exactly, and rename the deprecated profile key. The API check is waived for the DEFAULT_PROFILE additions in .github/api-compatibility-waivers/a6520722….json (against v2.69.0). The registry addition is a growing collection the check allows.
Why. #11454 added the compact_history hook, but nothing in core compacts through it yet. This adds the built-in handler that uses the serving model's own compaction API, ways to request compaction from a run's handles and at its start (compaction is always part of a run, per the design update), and the profile flags the handler decides by, so a handler declines up front instead of probing (a NotImplementedError is retried under Temporal).
New public surface
pydantic_ai.capabilities.NativeCompaction(focus_as_system_prompt=False): callsrequest.conversation_request.model.compact_messages()with the request's messages, settings and parameters (so it reads the cache), when the profile sayssupports_compaction_on_demand;Noneotherwise, including for aFallbackModel. It keeps the turn being answered (the request, plus the response whose tool calls it answers) after the provider'sCompactionPartresponse.ModelProfile.supports_compaction_on_demand,compaction_instructions: CompactionInstructionsMode | None('replaces_prompt'/'system_prompt'),compaction_result_readable.compact: bool | CompactionOptions = Falseonrun(),run_sync(),run_stream(),run_stream_events()anditer()(and the wrapper and durable agents), withCompactionOptionsatotal=FalseTypedDict ofreasonandfocus, likeretries: int | AgentRetries. It compacts before the run's first request; the full lifecycle runs and the record is onresult.compactions.AgentRun.request_compaction(*, reason='manual', focus=None)andAgentRunEvents.request_compaction(...): the same request asRunContext.request_compaction, from the run handle, served by the next attempt. Not onStreamedRunResult:run_stream()yields it once the final response streams, after which no model request follows.- Deprecated:
AnthropicModelProfile.anthropic_supports_on_demand_compaction(released in v2.62.0), translated tosupports_compaction_on_demandwith a warning.
Behavior
- Focus: Anthropic (
'replaces_prompt') gets it asinstructions, which it wraps in a full prompt. On OpenAI ('system_prompt') it would replace the system prompt and lose the cache, soNativeCompactiondeclines and the next handler serves it, unlessfocus_as_system_prompt=True. - Flags: OpenAI Responses on OpenAI and Azure, plus the on-demand Claude models. They're off for
OpenAIChatModel, ChatGPT plan usage and Codex (which only servePOST /v1/responses), and through the Pydantic AI Gateway (probed live: it doesn't serve/responses/compact). xAI has no Responses compaction path in Pydantic AI yet, so it's not flagged. OpenAICompaction(stateless=True)now requests compaction from its trigger and serves it withNativeCompaction's mapping, on anyOpenAIResponsesModelwhatever its profile flag says (LiteLLM and other Responses providers don't set it). Stateful (in-request) mode is unchanged and has nocompact_history.
Verification: tests/test_capability_native_compaction.py (fall-through, focus mapping, request.conversation_request.model vs ctx.model under ModelFallback, compact= with a focus, the full run lifecycle, AgentRun/AgentRunEvents.request_compaction mid-run); recorded OpenAI and Anthropic runs in tests/models/test_native_compaction.py; run(compact=...) as DBOS steps in tests/durable_exec/test_dbos.py; the legacy key in tests/profiles/test_legacy_keys.py.
What changes for existing users: OpenAICompaction in stateless mode now emits the compaction events and records result.compactions, compacts per attempt, and keeps a tool call with its result. The old profile key warns. Under Temporal or DBOS with an event_stream_handler, a stateless OpenAICompaction compaction adds two handler activities or steps (its compaction events), so in-flight workflows that compact this way need worker versioning or a patch (Temporal) or to finish on the old version (DBOS); runs without a handler, and Prefect, are unaffected. Nothing else changes unless you add NativeCompaction, pass compact=, or call request_compaction() on a run handle.
PR decisions
2026-10-27 · Agent.compact return type · iter -
- Decision: Returns CompactionResult | None; the result carries the run-style CompactionRecord as a new CompactionResult.record field (None when no capability compacted or a listener cancelled)
- Why: Follows the CompactionResult of #11454 and the plan that Agent.compact returns a result with the record fields, without adding a new public type
- Source: https://github.com/pydantic/pydantic-ai/pull/11454#issuecomment-6430085596
2026-10-27 · Agent.compact mechanics · iter -
- Decision: Runs agent.iter() and a compact-only ModelRequestNode step through wrap_model_request, before_model_request and prepare_model_request; a history ending in a response gets an empty placeholder request that is stripped from the result
- Why: Same hook chain, events, settings/tools/instructions (cache reads) and durable model as a run; the durability capability only installs DurableModel inside wrap_model_request
- Source: https://github.com/pydantic/pydantic-ai/issues/11395#issuecomment-6428101229
2026-10-27 · NativeCompaction kept tail · iter -
- Decision: Compacts messages before the turn being answered and keeps that turn: the last request, plus the preceding response when it has tool calls
- Why: A tool result cannot be sent without its call (Anthropic rejects it); the old messages[:-1] split of OpenAICompaction could orphan tool results
- Source: https://github.com/pydantic/pydantic-ai/issues/11395#issuecomment-6428101229
2026-10-27 · OpenAI compaction flags · iter -
- Decision: supports_compaction_on_demand set in OpenAIProvider.model_profile and AzureProvider for OpenAI models; OpenAIChatModel and the Pydantic AI Gateway turn it off
- Why: Chat Completions has no compact endpoint; probed the gateway live: POST responses/compact is not an endpoint it serves. OpenRouter 404s per the survey
- Source: https://github.com/pydantic/pydantic-ai/issues/11395#issuecomment-6428101229
2026-10-27 · Legacy anthropic_supports_on_demand_compaction · iter -
- Decision: Translated with a deprecation warning to supports_compaction_on_demand via _LEGACY_PROVIDER_PROFILE_KEYS
- Why: #11432 shipped in v2.62.0, so the key was released
- Source: https://github.com/pydantic/pydantic-ai/pull/11432
2026-10-27 · OpenAICompaction stateless mode · iter -
- Decision: before_model_request now calls ctx.request_compaction(reason='threshold') and compact_history delegates to NativeCompaction; _has_compact_history is False in stateful mode so in-request mode is untouched
- Why: Thin wrapper is non-breaking: existing cassettes replay unchanged, the non-OpenAI UserError is kept
- Source: https://github.com/pydantic/pydantic-ai/issues/11395#issuecomment-6428101229
2026-10-27 · OpenAI kept user messages · iter -
- Decision: The compacted window holds only the compaction item, as OpenAIResponsesModel.compact_messages returns today; the user messages OpenAI keeps are not added
- Why: compact_messages keeps its signature (decision 2) and returns only the item; the trim before compaction would drop messages placed before it anyway
- Source: https://github.com/pydantic/pydantic-ai/issues/11395#issuecomment-6428081488
2026-10-27 · Pre-push review skipped · iter -
- Decision: No pre-push-review subagent dispatched
- Why: Douwe's instructions for this task: do NOT spawn any subagents (no pre-push reviewers, no metadata checkers)
- Source: https://github.com/pydantic/pydantic-ai/issues/11395
2026-10-27 · OpenAICompaction stateless keeps compacting without the generic flag · iter -
- Decision: Stateless OpenAICompaction calls the shared compact_with_model() for any OpenAIResponsesModel, skipping the supports_compaction_on_demand gate NativeCompaction applies
- Why: Review: the gate would silently stop compaction for LiteLLM and other Responses providers that never set the new flag; the user chose an OpenAI-specific capability
- Source: https://github.com/pydantic/pydantic-ai/pull/11581#discussion_r4391486179
- Supersedes: OpenAICompaction stateless mode
2026-10-27 · compact() lifecycle and placement · iter -
- Decision: compact() lives on AbstractAgent; it runs before_run and wrap_run, then ends like an iter() stopped early (after_run does not fire). Returns the committed history (persistent originals) per the base request-view rule
- Why: WrapperAgent/clai2 take AbstractAgent; durability wrap_run/before_run set up workflow safety that a lifecycle-free compact would lose
- Source: https://github.com/pydantic/pydantic-ai/pull/11581#discussion_r4392839330
2026-10-27 · ChatGPT and Codex compaction flag · iter -
- Decision: openai_chatgpt and openai_codex profiles set supports_compaction_on_demand=False
- Why: They serve only POST /v1/responses with streaming and store=false; NativeCompaction would otherwise fail instead of declining
- Source: https://github.com/pydantic/pydantic-ai/pull/11581#discussion_r4394189986
2026-10-27 · Compaction outside a turn is part of a run · iter -
- Decision: Agent.compact(), its CompactionResult.record field and the compact-only graph path are removed; runs request compaction via run handles or compact=
- Why: Douwe's design update: a compact-only run skipped after_run; skipping the lifecycle loses durability and handler setup
- Source: https://github.com/pydantic/pydantic-ai/issues/11395#issuecomment-6455342461
- Supersedes: Agent.compact return type
2026-10-27 · compact= run parameter shape · iter -
- Decision: compact: bool | CompactionOptions | None = None on run/run_sync/run_stream/run_stream_events/iter (and wrapper/durable agents); CompactionOptions is a total=False TypedDict {reason, focus}, True means reason='manual'
- Why: Mirrors the existing retries: int | AgentRetries TypedDict run parameter; seeds state.compaction_requests in _prepare_run so the first attempt serves it
- Source: https://github.com/pydantic/pydantic-ai/issues/11395#issuecomment-6455342461
2026-10-27 · Run-handle request_compaction · iter -
- Decision: Added to AgentRun (UserError once ended) and AgentRunEvents (UserError before start); not to StreamedRunResult
- Why: run_stream() yields StreamedRunResult only once the final response is streaming, after which the run makes no model request, so a request there could never be served; run_stream(compact=...) covers it
- Source: https://github.com/pydantic/pydantic-ai/issues/11395#issuecomment-6455342461
2026-10-28 · compact defaults to False · iter -
- Decision: compact: bool | CompactionOptions = False on every run method; None is gone
- Why: CI Review: None had no meaning of its own, since there's no agent-level compaction default to fall back to
- Source: https://github.com/pydantic/pydantic-ai/pull/11581#discussion_r4406776162
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).