Compaction
Compaction keeps an agent’s conversation history within a model’s context window. Each strategy is a capability that edits the message history just before a model request. The edits persist into the run’s history, so a trim, clear, or summary carries forward instead of being recomputed every turn.
Across runs, the run’s result.conversation keeps the whole history, including what a strategy dropped, so a ConversationStore stores every message. Carried into the next run, it is compacted again, which for SummarizingCompaction and RelevanceCompaction means another model call over the whole, growing history. To carry the compacted history instead, pass result.all_messages() as message_history=.
Every strategy keeps tool calls paired with their returns: core does not validate this, and a provider rejects an orphaned call or return. Only SummarizingCompaction and RelevanceCompaction (and TieredCompaction when it escalates to one) call a model.
On OpenAI and Anthropic, core also ships provider-native compaction, where the provider summarizes server-side. These strategies work with every model and keep the logic and its costs under your control.
While Pydantic AI Harness is on 0.x releases, the API may change between minor releases; when it does, deprecation warnings and release-note migration guidance tell you (or your agent) exactly how to upgrade. See the version policy.
flowchart TB
accTitle: Compaction: keep the history inside the context window
accDescr: When the message history is over target_tokens, TieredCompaction runs in before_model_request, starting with DeduplicateFileReads, which makes no model call. If the history is still over, ClearToolResults runs, also with no model call, and if still over, SummarizingCompaction makes one model call. The history goes to the model once it fits, or after SummarizingCompaction.
history["message history<br/>over target_tokens"]
subgraph tiers["TieredCompaction()"]
dedupe["DeduplicateFileReads<br/>no model call"]:::capability
clear["ClearToolResults<br/>no model call"]:::capability
summary["SummarizingCompaction<br/>one model call"]:::capability
end
model(["model"])
history -->|"before_model_request"| dedupe
dedupe -->|"still over"| clear
clear -->|"still over"| summary
dedupe -->|"fits"| model
clear -->|"fits"| model
summary --> model
classDef capability stroke:#E520E9,stroke-width:2px
A long run accumulates tool outputs, file reads, and reasoning until the history outgrows the window and the next request fails. Pick a strategy by where the bloat is and what you can spend reclaiming it.
| Component | Cost | What it does | Reach for it when |
|---|---|---|---|
ClampOversizedMessages | zero-LLM | Head/tail-truncates one oversized part (response text, tool-call args) | One runaway generation exceeds the context cap |
SlidingWindowCompaction | zero-LLM | Drops the oldest whole messages down to a tail | Only the recent turns matter |
ClearToolResults | zero-LLM | Blanks old tool results in place, keeping the last keep_pairs or keep_turns | Tool outputs dominate and can be re-fetched |
DeduplicateFileReads | zero-LLM | Blanks file reads superseded by a newer read of the same file | The agent re-reads files and only the latest version matters |
SummarizingCompaction | one LLM call | Summarizes older messages, keeping the recent tail | Old context matters but must shrink; use behind the cheap tiers |
RelevanceCompaction | one judge request per new step, plus an optional summary | Keeps, reduces, or drops each older step by a judge model’s answers | Some old tool results are needed verbatim, others are dead weight |
ResetCompaction | zero-LLM | Clears the history down to the first request, the user’s later turns and a short tail, with a notice pointing the model at a WorkLog | A long autonomous run can look up its earlier tool results instead of keeping them in context |
TieredCompaction | escalates | Runs cheap passes first, summarizes only if still over target_tokens | The sensible default: pay for a summary only when needed |
FallbackCompaction | depends on chain | Tries the next strategy when one raises | Summarization can fail and truncation must keep the run alive |
CompactOnRequest | depends on strategy | Gives the model a tool to request compaction before its next request | The model knows when a phase of work ends better than a size trigger |
PruneToolResults | zero-LLM | Gives the model a tool to replace a result it just received with its own summary | A tool can return far more than the model needs, and only the model can tell after reading it |
WarnNearLimits | zero-LLM | Injects an URGENT/CRITICAL warning as limits approach | The agent should wrap up rather than have its history rewritten |
ReportContextUsage | zero-LLM | Reports context usage to your application; never edits history | You want a live context gauge in a UI |
Compaction updates the persisted run history and replaces the current request view, discarding earlier request-only edits even when ClampOversizedMessages has nothing to shorten. List request-only injectors such as Memory after compaction so they apply to the compacted request.
Size-based strategies trigger on max_messages, max_tokens (estimated as in What counts toward the fraction), or max_fraction. Exceptions: DeduplicateFileReads runs on every request when no trigger is set (it is cheap and near-lossless), TieredCompaction triggers and stops on one target_tokens / target_fraction budget, and ClampOversizedMessages triggers per part (max_part_tokens / max_part_chars), since its failure is one oversized part, not a large total.
Without a tokenizer, history that provider usage doesn’t cover is measured with a text estimate of about 4 characters per token for English-like prose. Non-ASCII text, emoji, base64-like runs, and compact JSON count as denser. The estimate errs high on dense content, since an undercount can send a request over the context window, but some scripts, such as Hebrew, Thai, and Indic scripts, can still use more tokens than it counts; pass a tokenizer if your history is mostly in one of them. The same estimate measures keep_tokens, max_part_tokens, ToolOutputLimits(over_tokens=True) bands and the compaction.tokens_* span attributes.
An absolute max_tokens fits one model: at 180_000, a 1M-context model compacts at a fifth of its capacity and pays for needless summaries; at 1_000_000, a 128K model never compacts before the provider rejects the request. max_fraction resolves per request against the model’s real window:
from pydantic_ai import Agent
from pydantic_ai_harness import SummarizingCompaction
agent = Agent(
'anthropic:claude-sonnet-5-5',
capabilities=[SummarizingCompaction(max_fraction=0.9, keep_messages=20)],
)
That compacts at 900K on a 1M model and at 115K on a 128K one. WarnNearLimits has max_context_fraction and TieredCompaction has target_fraction. max_tokens and max_fraction are mutually exclusive, so it is always clear which budget applies.
The window is the model’s context_window: its profile’s value (including profile={'context_window': ...}), else the one genai-prices records. A FallbackModel reports the smallest window among its models, since any may answer. resolve_context_window is exported. Nothing is cached, and only a window the model or registry states counts as real.
The model consulted is ModelRequestContext.model, the one the request goes to; if a capability ordered earlier replaces it, the budget follows.
Local endpoints, bespoke deployments, registry models without a recorded window, and a FallbackModel with no windowed model resolve to nothing. The fraction is then taken of fallback_context_window, by default a conservative 200K (DEFAULT_CONTEXT_WINDOW): compacting early costs one summary, overestimating costs the request. Every capability that takes a fraction accepts it, and it is used only when resolution fails:
from pydantic_ai import Agent
from pydantic_ai_harness import SummarizingCompaction
agent = Agent(
'ollama:qwen3',
capabilities=[SummarizingCompaction(max_fraction=0.9, fallback_context_window=40_000)],
)
TestModel (model_id test:test) does not resolve, so max_fraction=0.9 becomes a 180,000-token trigger that a test may never reach. Pass context_window= or fallback_context_window= in tests.
fallback_context_window cannot help when resolution succeeds with the wrong number:
-
The registry entry is wrong. Harness cannot validate
genai-prices. Measured against 0.1.3:model id registry records real window anthropic:claude-sonnet-4-51,000,000 200,000 anthropic:claude-opus-4-6200,000 1,000,000 An over-recorded window breaks a run: on
anthropic:claude-sonnet-4-5,max_fraction=0.9gives a 900,000-token trigger for a 200,000-token window, so compaction never fires and the provider rejects the request. Passcontext_window=200_000explicitly onclaude-sonnet-4-5.claude-sonnet-5’s recorded 1,000,000 matches Anthropic’s documentation; check other Sonnet ids against it. An under-recorded window is safe but compacts early. -
The registry records the maximum a model accepts. Where that is gated (a beta header, a pricing tier), ordinary requests get less, and the fraction never triggers before the provider rejects the request.
-
A self-hosted or proxied endpoint reports a model id whose registry entry describes someone else’s deployment.
context_window overrides resolution on every capability that takes a fraction:
from pydantic_ai import Agent
from pydantic_ai_harness import SummarizingCompaction
agent = Agent(
'openai:gpt-6-luna', # served by a local endpoint with a smaller window than the registry records
capabilities=[SummarizingCompaction(max_fraction=0.9, context_window=32_000)],
)
Token counts anchor on the provider-reported usage of the latest model response, which covers everything billed for that request, including instructions, tool definitions, and FilePart payloads. When billed usage sums several model requests, the anchor is the input tokens of the one that measures the context, plus the output: the first request of a Google long decode (its billed input re-counts earlier requests’ output), or the last sampling pass of an Anthropic response that reports its passes (its billed input re-counts each pass’s context).
Messages after the anchor, or a history with no anchor, are estimated with tokenizer or the text estimate. The estimate cannot see FilePart payloads and counts a file in a tool return as its See file <identifier>. reference. Instruction replacement and withdrawal records count their full rendered system text; superseded updates before a new instruction baseline are excluded. Instructions changed since the anchor replace the old set in the estimate rather than adding to it, since a request sends one. Tool schemas newly revealed for the pending request are estimated conservatively, since the anchor does not cover them.
If you already set an absolute max_tokens, re-check it. Besides user and system prompts, tool returns, response text, and tool calls, the estimator now counts ThinkingPart / CompactionPart content, retry content, NativeToolCallPart / NativeToolReturnPart, and the latest ModelRequest.instructions, so a history measures higher and an unchanged max_tokens compacts earlier. On a thinking-heavy, tool-calling history it can be several times the old count, depending on how much of it is thinking blocks, retries, and instructions. What each strategy clears is unchanged.
The retained tail is measured per message with estimate_message_tokens, in provider-counted tokens. A response counts at least its reported output_tokens, which includes thinking some providers return as an empty, signature-only part. Messages between two responses with usage share the difference of their input_tokens, exactly what the provider counted for them. A multi-request response enters that difference with the input tokens of the request that measures its context, as above; Anthropic’s last pass also read the response’s earlier passes, which the difference credits to the preceding messages, so the tail measures high. tokenizer or the text estimate applies before the first such response, after the last, where the history did not grow between two (as across an earlier compaction), and with no provider usage. Instructions are not part of the tail.
If you set keep_tokens, re-check it. Before, it was measured with the heuristic alone, which can see a third or less of a thinking-heavy history’s real tokens, so a budget kept several times more history than it named. It now keeps the named amount, so fewer messages.
ReportContextUsage reports how full the context is, for a gauge such as context: 73%, using the strategies’ estimator and resolved window. It never edits history:
from pydantic_ai import Agent
from pydantic_ai_harness import ReportContextUsage, SummarizingCompaction
from pydantic_ai_harness.compaction import ContextUsageMeasuredEvent
agent = Agent(
'anthropic:claude-sonnet-5-5',
capabilities=[
SummarizingCompaction(max_fraction=0.9, keep_messages=20),
ReportContextUsage(),
],
)
@agent.on_event(ContextUsageMeasuredEvent)
async def show(ctx, event):
print(f'{event.fraction:.0%}')
Each reading carries used_tokens, window_tokens, fraction, and resolved (False when the window is the fallback, so the percentage is a guess). used_tokens follows the accounting above. Register the monitor after a compaction capability to see the history after same-cycle compaction (it subtracts the rewrite’s heuristic reclaim and keeps the anchor’s fixed provider overhead), or before it to see what triggered compaction. on_usage still works but is deprecated; move its callback body to a ContextUsageMeasuredEvent subscription.
A strategy’s compact needs a RunContext, which an application doesn’t have between runs, such as when a user types /compact. compact_now builds a throwaway one so a command handler can run the agent’s strategy:
from pydantic_ai_harness import SummarizingCompaction
from pydantic_ai_harness.compaction import compact_now
strategy = SummarizingCompaction(max_fraction=0.9, keep_messages=20)
history = await compact_now(
strategy,
history,
model='anthropic:claude-sonnet-5-5',
focus='the auth refactor, not the earlier CSS work',
)
compact_now applies no trigger, so an unconditional compact runs at any history size. A strategy’s own stop condition still applies: TieredCompaction returns a history already under its target unchanged; pass the tier directly to run it regardless.
focus steers SummarizingCompaction and RelevanceCompaction through the exported SupportsFocus protocol’s with_focus; rule-based strategies that drop or blank content ignore it. TieredCompaction is focusable when any of its tiers is, so the focus reaches the summarizing tier.
A compaction that changes the history emits the in-run compact_messages span; pass tracer= to record it, otherwise it goes to a no-op tracer.
Pass conversation_id= so the SummarizingCompaction summary run is recorded under that conversation (its messages and gen_ai.conversation.id span attribute) instead of a fresh id. Inside a run, it takes the parent run’s conversation_id.
Summarization turns input tokens into output tokens, which cost more and are generated serially; the zero-LLM strategies touch only the cheaper input side. TieredCompaction runs its tiers in order, re-measures after each, and stops once the history fits target_tokens, so order tiers cheap to expensive:
from pydantic_ai import Agent
from pydantic_ai.messages import ToolCallPart
from pydantic_ai_harness import ClearToolResults, DeduplicateFileReads, SummarizingCompaction, TieredCompaction
def my_file_key(call: ToolCallPart) -> str | None:
if call.tool_name != 'read_file':
return None
return call.args_as_dict().get('path')
agent = Agent(
'openai:gpt-6-luna',
capabilities=[
TieredCompaction(
tiers=[
DeduplicateFileReads(file_key=my_file_key),
ClearToolResults(keep_pairs=3),
SummarizingCompaction(keep_messages=20), # model inherits the run's
],
target_tokens=120_000,
)
],
)
TieredCompaction calls each tier’s compact directly, re-measuring after each and stopping once under target_tokens, so a tier needs no max_* trigger of its own. Registered directly on an agent without a trigger, ClearToolResults, SlidingWindowCompaction, SummarizingCompaction and ResetCompaction raise UserError. Any object with async def compact(messages, ctx) -> list[ModelMessage] (the CompactionStrategy protocol) can be a tier.
Each tier keeps some messages as they are: its keep_tokens or keep_messages tail (which holds the whole current turn), the first user message under preserve_first_user_message, pinned parts, and the latest response when it names a workspace (its workspace_ref) and only requests follow it, as the next run finds its workspace there (kept whatever its size). That sets a floor on how far the chain can shrink the history, and a target_tokens below it can’t be reached. A SummarizingCompaction tier with keep_tokens whose only candidates are messages it keeps anyway makes no model call and leaves the history unchanged. When the last tier leaves the history above the target, the outermost TieredCompaction logs a warning on each attempt and sets compaction.target_unreached on its span when the history changes; if no tier changes it, no span is emitted, but the warning still reports the estimate and target. Pass preserve_first_user_message=False to a tier that may drop or summarize the first user message.
On its own trigger, TieredCompaction skips a tier that raises one of its skip_on exceptions and moves on to the next. By default these are ModelAPIError, FallbackExceptionGroup and UnexpectedModelBehavior, such as a summarizer whose provider is down or that exhausted its retries, the same selection as FallbackCompaction’s fallback_on. The skipped tier’s receipts are discarded, a warning is logged, and a compact_messages span records the tier as compaction.strategy, with compaction.skipped='tier_failed' and error.type. Other exceptions, such as programming errors and UsageLimitExceeded, propagate, as does every exception on a direct compact() call, so a FallbackCompaction around it still falls back. Pass skip_on=() to propagate every tier failure.
TieredCompaction advances when a tier does not reclaim enough; FallbackCompaction advances when a strategy raises an exception in fallback_on, by default ModelAPIError, FallbackExceptionGroup (raised when every model in a FallbackModel fails) and UnexpectedModelBehavior. When its own trigger runs the chain, it also advances past a SummarizingCompaction whose result isn’t smaller, and leaves the history unchanged if no strategy shrinks it. Each attempt gets a fresh list of the original message objects, so a failed strategy’s list changes do not reach the next; strategies must still not mutate message objects (the CompactionStrategy contract). If every strategy fails, the last exception is re-raised. Other exceptions, cancellation, and other BaseException subclasses pass through immediately; fallback_on accepts only Exception subclasses.
Register it with Agent(..., capabilities=[fallback]), here falling back from summarization to deterministic truncation:
from pydantic_ai_harness import FallbackCompaction, SlidingWindowCompaction, SummarizingCompaction
fallback = FallbackCompaction(
max_fraction=0.85,
fallback_chain=[
SummarizingCompaction(keep_tokens=20_000),
SlidingWindowCompaction(keep_tokens=20_000),
],
)
Its optional max_tokens or max_fraction trigger runs the chain when estimated context tokens exceed it; with neither, its request hook does nothing. context_window, fallback_context_window, and tokenizer work as on the other strategies. The hook preserves pinned parts, persists the result, and emits a compact_messages span when history changes. Direct compact() and compact_now() calls ignore the threshold, so it also works inside other composing strategies and for manual compaction. The chain calls each child’s compact() directly, bypassing the child’s trigger, so a child needs none.
Set background_start to start the chain’s first strategy before the trigger fires, so a summary is usually ready when compaction is due and the run does not wait for it.
from pydantic_ai_harness import FallbackCompaction, SlidingWindowCompaction, SummarizingCompaction
compaction = FallbackCompaction(
max_fraction=0.85,
background_start=0.85,
fallback_chain=[
SummarizingCompaction(keep_tokens=20_000),
SlidingWindowCompaction(keep_tokens=20_000),
],
)
- Start. Before each model request and at the end of each run, once the context passes
background_startof the trigger (here 85% of the 85% threshold), the first strategy compacts a copy of the history in a background task, blocking neither. It requires amax_tokensormax_fractiontrigger. A run that ends already over the trigger starts none; its next request compacts normally. - Hold. The result is held, not applied, so the history and its prompt cache stay unchanged until compaction is due.
- Swap. When the trigger fires, the chain waits for a pending result and swaps it in: the compacted copy replaces the messages it was made from, followed verbatim by every message added since. Pairs stay intact: the copy keeps them paired, and the added messages start where a model request or a run did.
- Fall back. The held result is dropped and the chain runs normally when the history no longer starts with the copy (rewritten, rewound, or compacted another way), the request goes to another model, the strategy raised or was cancelled, or the swapped-in history would still exceed the trigger. Instructions are not compared: the summary is written from the messages alone.
- Lifetime. Each conversation (
RunContext.conversation_id) holds at most one, which can outlive the run that started it until it is used, replaced, or cancelled. Below the start, one whose conversation was rewritten (same first message) or moved to another model is cancelled at the next check; a run whose history starts elsewhere, such as a side run with an emptymessage_historyunder the same conversation ID, leaves it alone. Otherwise it is kept until you calldiscard_background_compaction(conversation_id), as you should for a conversation that will not continue (such as a finished delegated task), or until it is the oldest of eight held and another starts.aclose()cancels them all; call it when done with the instance. - Outside a run.
take_background_compaction(messages, model=..., conversation_id=...)waits for the held result and returns the history with it swapped in, orNonewhen it does not apply, so you can fall back tocompact_now. Calldiscard_background_compaction(conversation_id)when rewriting the history another way.background_conversationslists the conversations holding one. - Usage. The work runs on the starting run’s context, so a summary call counts toward that run’s usage and limits like a blocking one; if it finishes after the run ended, its usage is added to that run’s
RunUsagethen. An unused result still cost its tokens.
Only the first strategy runs in the background, so put the model-backed one first. A with_focus() copy holds nothing. Background compaction is not a durable operation, so a durable workflow or flow run with background_start set raises UserError before its first request.
A size trigger can fire mid-sub-task and summarize away the file the model was about to edit, or stay quiet after a phase whose output is no longer needed. CompactOnRequest gives the model a compact_context(focus=None) tool and runs your strategy before the next model request of the same run:
from pydantic_ai import Agent
from pydantic_ai_harness import CompactOnRequest, SummarizingCompaction, TieredCompaction
agent = Agent(
'openai:gpt-6-luna',
capabilities=[
# Automatic size-based compaction stays as is.
TieredCompaction(tiers=[SummarizingCompaction()], target_fraction=0.8),
CompactOnRequest(
# `compact` is called directly, so the strategy needs no trigger of its own.
SummarizingCompaction(keep_messages=6),
min_tokens=30_000, # refuse requests that would save little
max_per_run=2,
),
],
)
The tool only records the request and acknowledges it. Compaction runs in the next before_model_request, with the same messages and context automatic compaction gets; the tool call and return, as the newest messages, stay paired in the kept tail, so the model sees that it asked. The model’s focus reaches the strategy through with_focus if it implements SupportsFocus (SummarizingCompaction, RelevanceCompaction, TieredCompaction, FallbackCompaction), and is ignored otherwise.
The tool return tells the model when a request is refused:
- the history is below
min_tokens, estimated the way the token triggers estimate; max_per_runrequests were already accepted in the run;- a request is already scheduled, such as from two parallel calls in one response.
CompactOnRequest runs after the agent’s automatic compaction capabilities, wherever you list it. If one already compacted for this request, the model’s request is dropped rather than compacting twice, and does not count against max_per_run.
Under durable execution, the guards run in a capability hook, not the tool function, because the tool may run in an activity that sees neither the history nor the run’s state. The strategy runs as the compact durable operation of CompactOnRequest, so a replay reuses the recorded history instead of calling the summarizer again. Under Temporal that operation is an activity whose run context omits tracer and capabilities, so strategies that read them fail there: RelevanceCompaction, and receipts=True on SummarizingCompaction or SlidingWindowCompaction. For the same reason, receipts recorded inside the activity, or skipped on a DBOS replay, add no compaction.receipt span events.
A tool’s output size is not known until it returns: a search can match build artifacts, a test run can print thousands of lines around one traceback. ClearToolResults keeps the newest keep_pairs results, which is where such a result sits. Whether it is useless is a judgement the model can make once it has read it. PruneToolResults gives it a prune_tool_result(tool_call_id, summary) tool to replace that result with [tool result pruned] followed by its summary:
from pydantic_ai import Agent
from pydantic_ai_harness import ClearToolResults, PruneToolResults
agent = Agent(
'openai:gpt-6.1-sol',
capabilities=[ClearToolResults(max_fraction=0.7), PruneToolResults()],
)
The replacement happens as soon as the call is accepted, in a hook after the tool runs, so it holds even when the run then ends or pauses for an approval. It persists in the run’s message history as a cleared result does, and the tool call stays paired with it. Only results the model’s latest response answered can be pruned, so the edit lands at the end of the history and the cached prefix before it is kept. The tool return tells the model when a call is refused: for an ID that is not one of those results, a typed result that ClearToolResults would also leave intact, or a summary that is not shorter than the result.
Compaction on the next request works on the pruned history. Its max_tokens and max_fraction triggers, and ReportContextUsage, anchor on the usage of the latest response, which still counts the pruned result, so a prune lowers those estimates from the following response on. A prune emits the standard compact_messages span with compaction.strategy set to PruneToolResults and compaction.model_requested set. The original result is not kept in the history; with instrumentation that includes content, the tool’s execution span still records it.
A response of repeated whitespace or a tool call with a giant payload can make one part so large the next request exceeds the context cap. No other strategy reaches it. The offender is the newest message, but SlidingWindowCompaction drops the oldest; it is not a tool result, which is all ClearToolResults touches; WarnNearLimits never edits history; and summarizing hits the same cap.
ClampOversizedMessages truncates the part in place to a head and tail slice joined by a [clamped: removed N of M characters] marker. Degenerate generations are low-entropy repetition, so little is lost.
from pydantic_ai import Agent
from pydantic_ai_harness import ClampOversizedMessages
agent = Agent(
'openai:gpt-6.1-sol',
capabilities=[ClampOversizedMessages(max_part_tokens=50_000, keep_head_chars=2_000, keep_tail_chars=2_000)],
)
A part is clamped only when oversized and the clamp shrinks it, so keep keep_head_chars + keep_tail_chars well below the per-part threshold. A clamped part loses its item ID (TextPart.id, ToolCallPart.id), since the OpenAI Responses API would use its stored copy of an item sent with its ID and ignore the clamped content.
It clamps two kinds of part in each ModelResponse:
- Response text (
TextPart): the critical case, a runaway text part. - Tool-call args (
ToolCallPart), whenclamp_tool_call_args=True(the default), such as a runawaywrite_plan. The args become{"_clamped": "<head>...<tail>"}so they stay valid function arguments; the call already executed, so only the history copy shrinks. Setclamp_tool_call_args=Falseto clamp response text only. Core’s framework-typedsearch_toolsandload_capabilitycalls are never clamped: their typed args are validated when persisted history is restored (for example aStepPersistenceresume), which the_clampedobject would fail.
Request-side parts (user prompts, tool returns, system prompts) are out of scope: user input should not be rewritten, and oversized tool returns are for ToolOutputLimits, which reduces a return when the tool produces it. ClearToolResults keeps the newest keep_pairs results intact, and with keep_pairs=0 blanks a fresh return rather than shrinking it.
Use it as the first tier of TieredCompaction, before ClearToolResults:
from pydantic_ai_harness import ClampOversizedMessages, ClearToolResults, TieredCompaction
TieredCompaction(
tiers=[
ClampOversizedMessages(max_part_tokens=50_000),
ClearToolResults(keep_pairs=3),
],
target_tokens=120_000,
)
Tool outputs usually dominate context, and the agent can re-run a tool to get the data again. ClearToolResults replaces the oldest tool results with a short placeholder, keeping the newest keep_pairs call/return pairs intact and every call paired. A retried return, which asks the model to call again, isn’t a result: it is never cleared or counted toward keep_pairs, and DeduplicateFileReads doesn’t let a retried read supersede an earlier one.
Core’s framework-typed search_tools and load_capability returns are left intact (a small token floor): their structured content is re-parsed later, and rewriting it via dataclasses.replace would bypass validation and corrupt the part. FileSystem’s typed read_file results (ReadFileReturnPart) are cleared and keep their type, unless their metadata is neither None nor a dict: clearing marks the metadata, so a result that can’t hold the mark stays uncleared.
from pydantic_ai import Agent
from pydantic_ai_harness import ClearToolResults
agent = Agent(
'openai:gpt-6-luna',
capabilities=[ClearToolResults(max_tokens=100_000, keep_pairs=3)],
)
clear_tool_inputs=True also blanks the cleared calls’ arguments, and those calls lose their item ID as a clamped part does. A load_capability call keeps its argument, which Pydantic AI reads to know which capability is loaded. exclude_tools names tools whose results are never cleared; tools names the only ones that are, and keep_pairs then counts only their pairs, shared across the listed tools, so tools=['retrieve'], keep_pairs=2 keeps the newest two retrieve results whatever ran in between. Setting tools with exclude_tools raises UserError.
keep_turns keeps by user turn instead: the results of the last keep_turns completed turns plus the current one, which is never cleared, so keep_turns=0 clears every earlier turn’s. Only the user’s own prompt starts a turn, not harness-added prompts (pinned messages, receipts) or a ToolReturn’s content, and a run resumed without a prompt counts the history’s last turn as current. A keep_pairs other than its default of 3 alongside it raises UserError.
placeholder can also be a function of the ToolReturnPart being cleared, for example to keep its first line so the ids it listed survive:
from pydantic_ai import Agent
from pydantic_ai.messages import ToolReturnPart
from pydantic_ai_harness import ClearToolResults
def first_line(part: ToolReturnPart) -> str:
return part.model_response_str().partition('\n')[0]
agent = Agent(
'openai:gpt-6-luna',
capabilities=[ClearToolResults(max_tokens=50_000, tools=['search'], keep_turns=0, placeholder=first_line)],
)
The function runs once per result, when it is cleared, and the history stores its output; a clear that min_clear_tokens drops calls it again later. It must be deterministic, or a history cleared again on a resumed or replayed run comes out different and the prompt cache misses. A result whose metadata is neither None nor a dict isn’t cleared with a function, and an agent spec only takes a string.
With max_messages, the count starts after the last cleared result, since clearing removes no messages. Clearing thus happens in batches: the next clear waits until more than max_messages messages follow the last cleared result, and the requests in between extend the cached prefix instead of rewriting it. Right after a clear, about 2 * keep_pairs messages (the kept pairs) follow the last cleared result and each tool step adds two, so the next clear comes after about (max_messages - 2 * keep_pairs) / 2 tool steps; at or below 2 * keep_pairs, it clears on every request. With keep_turns, the kept turns’ messages count the same way.
When a file is read more than once, only the latest read keeps its content; earlier reads are blanked, keeping pairing. There is no default file_key, since identifying a file read is agent-specific and a wrong guess would drop live data. Pass a callable mapping a ToolCallPart to a stable key, or None for a call that is not a file read:
from pydantic_ai import Agent
from pydantic_ai.messages import ToolCallPart
from pydantic_ai_harness import DeduplicateFileReads
def file_key(call: ToolCallPart) -> str | None:
if call.tool_name != 'read_file':
return None
return call.args_as_dict().get('path')
agent = Agent('openai:gpt-6.1-sol', capabilities=[DeduplicateFileReads(file_key=file_key)])
With no max_messages or max_tokens trigger, it runs on every request, usually what you want for a cheap, near-lossless pass.
Once the history exceeds its trigger, SlidingWindowCompaction discards the oldest whole messages down to a tail, keeping tool calls paired.
from pydantic_ai import Agent
from pydantic_ai_harness import SlidingWindowCompaction
agent = Agent(
'openai:gpt-6.1-sol',
capabilities=[SlidingWindowCompaction(max_messages=80, keep_messages=40)],
)
preserve_first_user_message=True (the default) keeps the first user turn, besides system prompts, even outside the window, so the agent keeps the original task. keep_messages=0 still keeps the newest message, the request being answered. Pass keep_tokens instead of keep_messages to retain a minimum amount of original text rather than a message count.
max_tokens decides when compaction runs; a positive keep_tokens decides how much original recent history survives. SlidingWindowCompaction and SummarizingCompaction include the whole message that crosses the target, extending backward for matching tool calls and tool-specific retry responses.
For example, with max_tokens=170_000 and keep_tokens=50_000, a 190k-token history of 139k older tokens, a recent 48k-token message, and a 3k-token newest tail keeps the 51k-token suffix. SummarizingCompaction summarizes the older prefix; SlidingWindowCompaction discards it.
The suffix is measured as in What counts toward keep_tokens, falling back to tokenizer or the character-based estimate over message-part text, system-prompt parts included. Attached ModelRequest.instructions don’t count toward the target. A history below the target is left unchanged without a summary call. keep_tokens=0 is a zero-token target, not a minimum-retention floor; None uses keep_messages.
Whole messages and tool dependencies can overshoot the target. Summaries, receipts, reinserted pins, and retained older user turns are added on top without displacing the protected suffix; receipts inside it stay unchanged. This does not guarantee the request fits the window: check the remaining budget and stop, switch models, or lower the target if needed. Set the same target on each fallback that must preserve it.
A large message can keep the suffix plus summary above max_tokens. Until newer messages meet the target without it, everything before the suffix is already accounted for (an earlier summary, receipts, pins, and verbatim messages such as the preserved first user turn), so SummarizingCompaction leaves the history unchanged without a summary call instead of re-summarizing its own summary every request. The request still goes out above the trigger; ClampOversizedMessages can shorten an oversized message.
SummarizingCompaction replaces older messages with one structured summary from a dedicated model call, keeping the recent tail and tool-call pairing. It is the expensive tier, so put it behind the cheaper passes (see TieredCompaction).
from pydantic_ai import Agent
from pydantic_ai_harness import SummarizingCompaction
agent = Agent(
'anthropic:claude-opus-5-5',
capabilities=[
SummarizingCompaction(
model='anthropic:claude-sonnet-5-5',
max_messages=60,
keep_messages=20,
)
],
)
model takes a model name or Model; None inherits the agent’s model. It must write text: if the agent runs one that can’t, such as TypeSafe’s Jev decision model, set model= to a language model, or the first compaction raises a UserError saying so.
An empty or whitespace-only summary is retried within the summary run’s output retries; exhausting them raises UnexpectedModelBehavior instead of writing an empty summary. Retries count against the nested run’s usage limits, raising UsageLimitExceeded if that budget runs out first. On its own trigger, such a failure is skipped. To fall back when the summary run exhausts its usage limits, add UsageLimitExceeded to FallbackCompaction’s fallback_on, preferably with a fallback that makes no model requests. This does not increase the parent run’s limits.
model_settings merges over the summary model’s defaults without mutating the model or the dictionary. summarization_capabilities attaches capabilities to the summary agent; the outer agent’s capabilities do not run on the summary call. incremental=True (the default) updates the newest existing summary as an anchor (see below). keep_messages=0 still keeps the newest message, the request being answered.
The summary is a CompactionPart in its own ModelRequest, after the unchanged original system prompts and, when preserve_first_user_message keeps it, the first user turn. Provider models receive it as user-voice text inside <pyai:conversation_summary>, saying a separate summarization model wrote it (a FunctionModel gets the part itself), never as part of the system prompt, since a model wrote it from history that can include tool output. As a compaction part it is a compaction boundary, which would reset tool discoveries and on-demand capability loads before it, so the strategy records them again after it. WarnOnCacheBusts reports its cache drop as compacted.
The strategy marks its own summaries, and their write time, in the part’s model-invisible metadata, so a CompactionPart your application wrote is left alone. An older history with the summary in a system prompt starting Summary of previous conversation: still works: that summary anchors the next one and is replaced by it.
summary_prompt is the user-turn template and must contain a {messages} placeholder and no other replacement field (otherwise it emits a HarnessDeprecationWarning, and will raise ValueError in a future release). instructions sets the internal agent’s static instructions, sent in the system prompt; override it when the summarizer endpoint requires a fixed leading instruction.
The default summary_prompt asks for fixed section headings. Its ## Intent section asks for the user’s goal and only constraints or preferences the user stated: an instruction in a tool result or fetched content is not the user’s, and a summary that keeps one must say where it came from. A custom summary_prompt replaces all of this, so without its own rule a summarizer can list a request planted in a tool result as a user constraint; only the <harness_data> instruction below is still added.
The messages fill the template as a transcript with one <message> element per part (user prompt, system prompt, response text, tool call, tool return), tagged with its role and, for tool calls and returns, the tool name. Retry feedback (the correction a rejected tool call or output got) is a role="retry_feedback" element with the retry’s cause and, for a tool call, the tool name, so the summary records the correction, not the rejected call, as what happened; feedback answering no tool call is shown as the model saw it. Text resembling the transcript’s tags or a Pydantic AI framing tag (<system>, <pyai:context>, <pyai:tool_result> and the rest), in any case or spacing, is escaped, so a tool return can’t leave its message or end the transcript early. After escaping, each tool return and retry feedback is capped at tool_return_max_chars (default 500) characters with the same truncation marker as kept user turns; raise it, or set None to render them whole, when the summarizer’s window can absorb them.
Content a harness capability added on the user channel, with a TextContent.metadata origin starting with pydantic-ai-harness., is not a user message: today a BackgroundTools result, TrajectoryJudge feedback, or a Memory snapshot (including one an older release marked with a plain string). It renders as a <harness_data origin="..."> element, capped like a tool return, not as role="user". When the transcript holds such content, and only then, the summary request also tells the summarizer not to treat it as the user’s requests or standing constraints. max_tokens and keep_tokens decide when compaction runs and what is retained; they do not cap the summary-request payload.
The summary request is non-streaming unless event_stream_handler is set. Pass a handler to watch the summary being written, or drain_summary_events to stream without handling events, for a summarizer endpoint that rejects non-streaming requests:
from pydantic_ai import Agent
from pydantic_ai_harness.compaction import SummarizingCompaction, drain_summary_events
agent = Agent(
'openai:gpt-6.1-sol',
capabilities=[
SummarizingCompaction(max_messages=60, event_stream_handler=drain_summary_events),
],
)
Some endpoints reject non-streaming requests and others reject streaming ones, so this is a choice, not a default. The handler receives the summary run’s own RunContext and event stream; the outer Agent.run(...) handler is not inherited and never sees the summary’s token deltas.
A summarizer with a smaller context window than the run’s model, such as a cheap model summarizing for a large one, can be handed more history than it accepts. When the summary request wouldn’t fit the summarizer model’s window with room left for the summary, the history is summarized in chunks instead of in one request. Chunks end on message boundaries, each tool call kept with its returns. The oldest chunk is summarized first, and each next request updates the summary so far the way an incremental compaction updates an earlier summary, until the rest fits in one request. No message is left out, and a history that fits is still summarized in one request, as before.
- The window is the summarizer model’s own
context_window: its profile’s (setprofile={'context_window': ...}on the model to correct it), else the pricing registry’s. When neither knows it, the request goes out whole. - The room left for the summary is the summarizer’s
max_tokensmodel setting, frommodel_settingsor the model’s own settings, else a quarter of the window, at most 8,192 tokens. - Requests are measured with the
tokenizer, or the text estimate without one, as the triggers are. - A single message, or a tool call with its returns, too large for a request on its own has its tool output and harness data cut further, with the truncation marker, until it fits. It is never dropped.
- When the request’s fixed part (the prompt template,
instructionsand the summary so far) doesn’t fit on its own, the request goes out whole, for the provider to accept or reject. - A summary is written in at most 32 requests. A history that needs more fails with
ModelContextWindowExceededError, as an overflowing request does: before any request when its estimated size already needs more, and otherwise once the rest can’t fit the requests left. On the capability’s own trigger, that’s a summary that fails like any other: the history is left unchanged, the span recordscompaction.skipped='summary_failed'witherror.typeModelContextWindowExceededError, and the trigger tries again on the next request. A directcompact()orcompact_now(), or aTieredCompactiontier, raises it, and aFallbackCompactionfalls back on it by default. Summarize such histories with a model with a larger window.
Each chunk is a summary request of the run, counted in its usage, and the compact_messages span records how many there were as compaction.summary_calls. A RelevanceCompaction summarizer fits its request the same way.
On its own trigger, SummarizingCompaction treats a summary that fails with UnexpectedModelBehavior (exhausted retries, an empty or truncated summary), ModelAPIError or FallbackExceptionGroup as a skipped attempt, not a failed run: the history and its receipts are left as they were, and a compact_messages span records compaction.skipped='summary_failed' and error.type. UsageLimitExceeded and programming errors such as UserError still propagate. The summary call’s usage still counts, and while the trigger stays exceeded, each next request tries again. A direct compact() or compact_now() on a SummarizingCompaction, or a TieredCompaction tier, raises the error; a FallbackCompaction follows its fallback_on, which by default includes UnexpectedModelBehavior, and re-raises the last error if every strategy fails.
Under Temporal, a failed summary currently arrives as ActivityError wrapping an ApplicationError, so it still propagates (#12291). Under AWS Lambda and Azure Durable Task, it reaches the run as the engine’s own error type too, so it propagates rather than being skipped (#13318). DBOS and Prefect re-raise it with its type, so the attempt is skipped there.
System prompts, the first user turn, the recent tail, pinned parts and receipts are kept, so with a short summarized span or a long summary, the result can be larger than the original. On its own trigger, SummarizingCompaction keeps the result only if it is estimated smaller, using the tokenizer of the capability whose trigger fired (FallbackCompaction’s inside a chain) or the text estimate. Otherwise the request goes out unchanged, any receipt the attempt wrote is dropped, and a compact_messages span with compaction.skipped set to not_smaller records the attempt and its estimated size. The summary call’s usage still counts, and while the trigger stays exceeded, each next request in the run makes another summary call. Inside FallbackCompaction the next strategy runs instead, so a SlidingWindowCompaction after the summarizer bounds both the history and that cost. A direct compact(), compact_now(), or a TieredCompaction tier returns the summary either way.
The summary call’s usage, tokens and the request, is added to the run’s ctx.usage, so a UsageLimits request limit can catch a runaway compaction and request or iteration limiters count compaction calls. The nested summary run inherits the parent usage limits, with a finite request limit reduced by one so it can’t spend the slot approved for the pending parent request. It is filed under the parent run’s conversation_id, so its requests, spans, and cost group with that conversation.
With a durable-execution capability attached, the summary call runs as a contributed durable operation, so replay uses the recorded summary instead of calling the model again; with model unset, it uses the run’s model. Durable execution recovers the operation by the capability’s stable default id. Overriding it orphans recorded operations of in-flight workflows, so keep it fixed once a workflow is live.
RelevanceCompaction asks a judge model about each older step of the history, then keeps it verbatim, reduces it, or drops it. Use it when some older tool results are needed exactly (code, error text) and others are dead weight, so one summary would lose the exact parts.
from pydantic_ai import Agent
from pydantic_ai_harness.compaction import RelevanceCompaction, SummarizingCompaction
agent = Agent(
'anthropic:claude-opus-5-5',
capabilities=[
RelevanceCompaction(
'system-one:nimble',
summarizer=SummarizingCompaction(model='anthropic:claude-haiku-5-5'),
max_fraction=0.8,
)
],
)
The judge, model, is required. A decision model, such as system-one:<model> on System One (including models Ollama runs locally) or TypeSafe’s typesafe:jev-latest, answers with a probability; any model with structured output fills the same two fields, so a FallbackModel from a decision model to a language model also works.
A step is a model response plus the requests answering it: its tool results, retry feedback, and the next user prompt. Steps are kept or removed whole, so a tool call never loses its result. Everything before the first response (system prompt, first user message, an earlier summary) and the most recent keep_tokens (default 8,000) are never judged. Pinned content survives even when its step is removed.
Each remaining step is judged in one request with two questions:
needed_verbatim: “Will the agent need the exact content of this earlier step, such as code, file contents, identifiers, numbers, commands or error text, to finish the current task?”still_matters: “Does this earlier step record a fact, decision, change, result or user instruction that still matters for the current task?”
The judge sees the current task (the first and latest user prompts, plus any focus passed to compact_now), the recent conversation, and the step with its tool results. A step longer than judge_step_tokens (default 2,000) is shown by its start and end; the task and recent conversation are each clamped to judge_context_tokens (default 500). These defaults fit the 8,192-token input of small local decision models, since code and JSON take about twice the tokens the ~4-characters-per-token estimate suggests. The judge is told all of it is untrusted data, and text resembling the prompt’s own tags is escaped.
Steps are chosen by rank against a token budget, not by a fixed probability threshold: a judge’s probabilities shift together with the shape of the request, but its ordering holds. The history is compacted to target_tokens (or target_fraction), by default half the trigger:
- Steps are kept verbatim in order of
needed_verbatimwhile they fit the target. - The rest are reduced in order of
still_matters: with asummarizer, written into one summary after the head of the history, up tosummary_input_tokens(default 30,000) of steps per compaction; without one, each tool result is cut to its firsttruncated_result_chars(default 300) characters plus a note that the tool can be called again, while that fits the target. - Whatever is left is dropped, except a step holding a user prompt: without a summarizer it is cut, and with one it is summarized while it fits
summary_input_tokensand kept verbatim otherwise.
The summarizer is a SummarizingCompaction used for its model, prompts and settings; its trigger and keep_* fields are ignored, so it needs no trigger. With its incremental=True (the default) the earlier summary is updated; with incremental=False it is re-summarized with the steps. receipts=True adds a receipt when steps were summarized or dropped.
Up to judge_concurrency (default 8) judge requests run at once. Judgements are remembered on the instance by task and step content, so a later compaction with the same task judges only new steps. A compaction’s judge requests count as one request against a UsageLimits request limit, checked before any is sent; their tokens are added to run usage and checked against token and cost limits on return. A long history’s first compaction sends many judge requests, so with a slow judge model it can take minutes.
A judge error propagates, like a summary error on an explicit call. Wrap the strategy in FallbackCompaction to fall back to one that makes no model requests:
from pydantic_ai_harness.compaction import FallbackCompaction, RelevanceCompaction, SlidingWindowCompaction
compaction = FallbackCompaction(
max_fraction=0.8,
fallback_chain=[
RelevanceCompaction('system-one:nimble', max_fraction=0.8),
SlidingWindowCompaction(keep_tokens=20_000),
],
)
As a TieredCompaction tier, set target_tokens explicitly: the tier’s compact uses its own target, and half of a trigger that only satisfies the constructor means nothing.
With a durable-execution capability attached, the judgements and summary run as the durable operations judge and summarize under the stable default id, relevance_compaction, so replay reuses them instead of calling the models again.
The two-question split and concurrent per-step requests come from fast-jev-compaction (MIT), which compacts Claude Code transcripts with TypeSafe’s Jev; its measurements also motivated showing the judge each step’s content and ranking steps. No code is shared.
A long autonomous run can fill its context window many times. Clearing old tool results a few at a time rewrites the cached prefix on every clear, and the model often runs the same reads again to get back what was cleared. ResetCompaction clears the history in one step instead, down to the task and the latest step, and leaves the model a notice saying where its earlier work is: a WorkLog, which keeps every tool call with its full result and the model’s replies, and which the model searches and reads with its own tools.
from pydantic_ai import Agent
from pydantic_ai.capabilities import LocalWorkspace
from pydantic_ai_harness import ToolOutputLimits, WorkLog
from pydantic_ai_harness.compaction import ResetCompaction
from pydantic_ai_harness.work_log import WorkspaceWorkLogStore
work_log = WorkLog(WorkspaceWorkLogStore())
agent = Agent(
'anthropic:claude-sonnet-5-5',
capabilities=[
LocalWorkspace('.'),
work_log,
ResetCompaction(work_log, max_fraction=0.6),
ToolOutputLimits(), # keeps one large result from filling the kept tail
],
)
Pass the WorkLog that is on the agent: the notice names its log. Agent(...) raises a UserError when no WorkLog is registered, and a run raises one at its start when the agent’s WorkLog under that id is not the one ResetCompaction holds. A WorkLog passed only to agent.run(capabilities=...) does not satisfy the check for a ResetCompaction on the agent. The WorkLog needs an id (the default 'work_log'): with id=None the run raises, since the check can’t find it.
The reset keeps, in order:
- the first user request, as it was, with its system prompt; harness data merged into it, such as an earlier notice, is left out;
- the notice, then the
restatetext when there is any; - pinned parts the reset would otherwise drop;
- the records of loaded on-demand capabilities and tool search discoveries, as the other strategies that drop history keep them;
preserve_loaded_capabilities=Falseunloads them instead; - what the user wrote in each later turn older than the tail, all in one request and without the tool results or harness data that came in the same requests, when
keep_user_prompts=True(the default); - the newest
keep_messagesmessages (default2), with each tool call kept with its return.keep_messages=0still keeps the newest message, the request being answered. The tail also reaches back to the latest response that names a workspace (itsworkspace_ref) when only requests follow it, as the other strategies’ tails do.
Everything else leaves the history. The work log holds the tool calls and replies among it that WorkLog recorded: it is for results that are expensive to get again and for what the model already did, not for a file’s current contents, which the model reads again before it edits. With keep_user_prompts=False only the first request and the tail keep the user’s words, and the log doesn’t hold the rest. An earlier notice and its restate text in the kept tail are removed, so each reset replaces the last notice rather than adding one.
Before it clears them, the reset checks the log for each tool call it clears that has its result in the history, matching the run the result came in, the tool call ID and the tool name, as WorkLog records them. When the log never recorded one, such as a call in history the run was given that this store never saw, or an external call’s result passed back in DeferredToolResults, the reset sets ResetNotice.work_log_incomplete, and the default notice then says that some of the cleared calls are not in the log, so a call the model can’t find there may still have run. The work log’s own search_work_log and read_work_log calls, and calls that were denied and never ran, are left out. A call that core skipped because a final result was already processed sets it too, though it never ran, because its result part doesn’t mark it as skipped (#13390): with the default end_strategy='graceful', an output tool call after the one that produced the result in the same response; with 'early', also every function tool call in that response. The check reads the whole log once, through WorkLog’s count_unlogged durable operation, and only when the reset clears a tool call. When the log can’t be read, any cleared call sets it: when no conversation ID is known, or when compact_now runs with a WorkspaceWorkLogStore that keeps logs in the run’s workspace, since there is no run. Each notice records it, and once it is set, later resets keep it set without reading the log: a call an earlier reset cleared is gone from the history but still missing from the log, so a later reset that clears only logged calls still says some are missing. Like the number, it starts over when no notice is in the history the run gets.
The notice is a ResetNoticePart, an instruction capability part in the application’s voice, like a receipt: the model gets it as a mid-conversation system message, and a later compaction or summary doesn’t take it for the user’s words. Its typed fields number, work_log (the log’s handle), kept_responses and work_log_incomplete are never sent to the model; find notices in history by the type. The default text tells the model that the conversation before this point was cleared and it is continuing the same task, how many times this conversation has been cleared, that the work log holds its earlier tool calls and replies (the replies only when WorkLog.record_text is on), how to pick up where it left off with the tools that search and read the log (under the names the model sees), to read a file again before editing it, since a log entry can be out of date, and what the reset kept. When the log lacks some of the cleared calls, it adds that a call missing from the log may still have run. Its mentions of calls made inside code and of calling the tools from code apply when Code Mode is on the agent. That wording, without the sentence about missing calls, was measured live across providers. The handle is what the store’s locate returns: a file path or a workspace directory, and none for the in-memory store or a store given its own workspace=, whose log the agent can reach only through the tools.
To write your own, pass notice=, a function from a ResetNotice to the text:
| Field | Meaning |
|---|---|
number | Resets in this conversation, this one included, counting from 1 |
work_log | The log’s handle, or None for the in-memory store or when no conversation ID is known: not from the run, compact_now’s conversation_id=, or any message in the history |
search_tool, read_tool | The names the model sees for search_work_log and read_work_log |
replies_logged | Whether the work log records the model’s replies (WorkLog.record_text) |
cleared_messages | Messages this reset removed |
kept_first_request | Whether the first user request was kept |
kept_user_prompts | User prompts after the first kept ahead of the tail |
kept_messages | Messages kept in the tail |
kept_tool_calls | Tool calls kept with their results in the tail |
work_log_incomplete | Whether the work log lacks a tool call this conversation’s resets cleared, this one included |
default_reset_notice renders the default text from the same facts.
restate adds the state of the task after the notice: an async function of the RunContext that returns text, a CurrentStatePart, or None or an empty string to add nothing. It reaches the model in a <current_state> frame. Text is recorded as the output of the restate callable (a ToolResultSource named after it), so text in it that looks like a frame gets a note naming its author, as command output such as git status should. Return CurrentStatePart(content=..., source=OperatorSource()) for text your application wrote itself, or another source for text from elsewhere. It runs as the restate durable operation of the stable default id='reset_compaction', so a replay reuses the recorded result. An exception it raises fails the request, as any hook error does; as a TieredCompaction tier, when TieredCompaction runs on its own trigger, one of its skip_on errors skips the tier instead, and as a FallbackCompaction entry one of its fallback_on errors moves on to the next entry.
Each notice records its number, and the next reset counts on from the highest number in the history, so the count continues in a run resumed from saved history, such as a StepPersistence snapshot. The work log records the same number in each entry’s context. result.conversation holds the cleared messages too, so a run continued from it resets again on its first request, as the other strategies compact it again; pass result.all_messages() to carry the reset history and its cached prefix instead. The count starts over at 1 when no notice is in the history the run gets, such as a ConversationStore.load(limit=...) window that leaves it out, or history a UI client sends back, which carries no capability parts.
Triggers. It takes the triggers of SlidingWindowCompaction: max_messages, max_tokens, or max_fraction with context_window and fallback_context_window. Like SlidingWindowCompaction, it needs a trigger when it’s registered on an agent, and a run raises a UserError at its start without one. As a strategy, in TieredCompaction, FallbackCompaction, CompactOnRequest or compact_now, it needs none: their calls to its compact reset whenever the history is longer than the kept tail.
Repeats. After a reset it doesn’t reset again until the model has added a response beyond what the reset kept. If the kept history alone is over the trigger, though, it resets after every new response. The kept user turns share one request, so they don’t add to a max_messages count, but their text adds to a token trigger with every turn (#14959). Set the trigger well above what keep_messages keeps, and add ToolOutputLimits, which reduces a large result when the tool returns it, so one oversized tool result in the tail doesn’t keep the history over the trigger. ToolOutputLimits leaves the work log’s own results alone, and a read_work_log page can reach 50,000 characters, so keep the trigger above that too.
With other capabilities.
- Don’t combine it with
SlidingWindowCompactionorSummarizingCompaction, on the agent or as a tier. The notice’s request holds no user turn, soSlidingWindowCompactiondrops the notice andSummarizingCompactionsummarizes it.RelevanceCompactionkeeps it, since it keeps every request before the first response as it was. InTieredCompaction, put it last, after passes that blank content in place such asClearToolResults, so it runs only when they didn’t free enough. - It orders itself ahead of
Planning, so after a reset Planning records the current plan again in the same request. CompactOnRequestorders itself after it, and stands down for a request it already reset.- Used as a strategy (a tier, a fallback entry,
CompactOnRequest’s strategy orcompact_now), itsWorkLogcheck doesn’t run. TheWorkLogmust still be on the agent, or the log stays empty. - A reset moves the cached prefix like any rewrite, so
WarnOnCacheBustscan warn on the request after it.
It holds a WorkLog instance and callables, so it can’t be loaded from an agent spec: get_serialization_name() returns None. Build it in Python.
WarnNearLimits never edits history. As the run nears a configured limit, it adds an URGENT, then CRITICAL, warning to each request so the model wraps up. Each warning is a LimitWarningPart, a request-scoped capability part in the application’s voice, which the model sees as a request-scoped system prompt: it sees it only with its own request, and it stays in the message history, so earlier requests are sent unchanged and the prompt cache and earlier reasoning stay valid. Warnings older versions sent as user prompts are left out of requests when a saved history still holds them; they are recognized by part metadata, not text, so a user prompt quoting a warning is never removed.
from pydantic_ai import Agent
from pydantic_ai_harness import WarnNearLimits
agent = Agent(
'google:gemini-4-hydrogen',
capabilities=[WarnNearLimits(max_iterations=40, max_context_tokens=100_000)],
)
Warnings start at warning_threshold (default 0.7 of the limit) and turn CRITICAL for iterations once the remaining request count drops to critical_remaining_iterations (default 3). It warns on whichever of max_iterations, max_context_tokens (or max_context_fraction), and max_total_tokens are set; narrow that with warn_on.
To tell the model on every request how much of the run’s UsageLimits and spend budgets is left, from the first request rather than past a threshold, use Report Remaining Budget.
Clearing, deduplicating, clamping, and summarizing rewrite message content, invalidating the provider’s prompt cache from the edit onward, so the next request pays a cache write. ClearToolResults’ min_clear_tokens skips a clear that reclaims too little to be worth it. For ClampOversizedMessages the bust is unavoidable: the alternative is a failed request.
ResetCompaction keeps the messages up to and including the first user request as they were, so the cached prefix stays valid through them, and rewrites what follows, which after a reset is short. Between resets the history only grows, so each request extends the previous one’s prefix. Where ClearToolResults rewrites the prefix from the oldest result it clears on every clear, a reset rewrites it once, and the model reads back from the work log only what it still needs.
With core instrumentation active (the Instrumentation capability, agent.instrument, or Agent.instrument_all()), a strategy emits a compact_messages span on the run’s tracer when it compacts in before_model_request (ClampOversizedMessages only when it clamps a part). TieredCompaction emits one span for the whole escalation, since it drives each tier’s compact directly. An automatic summary discarded for not being smaller also emits one, with compaction.skipped. Without instrumentation the tracer is a no-op.
The span name is always compact_messages, with the strategy as an attribute, to keep span cardinality low:
| Attribute | Type | Meaning |
|---|---|---|
gen_ai.conversation.compacted | bool | true when the history was compacted, absent on a skipped attempt |
compaction.strategy | str | Strategy class name, such as SummarizingCompaction |
compaction.messages_before | int | Message count before compaction |
compaction.messages_after | int | Message count after compaction |
compaction.tokens_before | int | Estimated token count before compaction |
compaction.tokens_after | int | Estimated token count after compaction |
compaction.model_requested | bool | true when the model asked through CompactOnRequest or PruneToolResults; absent otherwise |
compaction.background | str | Only with background_start: used, stale, or failed, what became of the background result |
compaction.skipped | str | summary_failed when an automatic summary failed, tier_failed when a TieredCompaction tier raised and was skipped, or not_smaller when an automatic summary was discarded for not being smaller; with not_smaller, the *_after attributes describe the discarded result. Absent otherwise |
error.type | str | With compaction.skipped='summary_failed' or 'tier_failed': the exception’s fully qualified class name |
compaction.summary_calls | int | When the summarized history was split into chunks to fit the summarizer’s window: the number of summary requests. Absent when one request was enough |
compaction.target_unreached | bool | TieredCompaction only: true when every tier ran and the history is still estimated above the target. Absent otherwise |
compaction.target_tokens | int | With compaction.target_unreached: the resolved target |
compaction.estimate | int | With compaction.target_unreached: the estimate the stop decision used, anchored on provider-reported usage when there is any |
compaction.reset.number | int | ResetCompaction only: the reset’s number in the conversation, this one included. Set when the reset ran, including when its restate then raised and TieredCompaction skipped the tier |
Only gen_ai.conversation.compacted comes from the OpenTelemetry GenAI semantic convention; the rest are harness-specific. Token counts use the strategy’s tokenizer, else the text estimate. Raw message content is not recorded.
SummarizingCompaction runs its summarizer as a nested Agent named summarizing_compaction, so under Agent.instrument_all() (or logfire.instrument_pydantic_ai()) filter on agent_name = summarizing_compaction to track summarization usage and cost separately.
FallbackCompaction with background_start also emits a background_compaction span around the background work, with compaction.strategy and compaction.messages_before. It ends with the work, possibly after the run that started it, and records a failure. The summary run inside it is the same summarizing_compaction agent run.
RelevanceCompaction adds a select compaction steps span inside compact_messages, recording the step count and how many were judged rather than remembered (relevance_compaction.steps, relevance_compaction.steps_judged), each tier’s steps and tokens (relevance_compaction.keep.steps, relevance_compaction.keep.tokens, and likewise for reduce and drop), and one relevance_compaction.step event per step with its position, size, both answers, whether it was remembered, and its tier. No message content is recorded. The judge’s own runs are not instrumented, because their prompts carry the conversation.
After compaction, the model can’t see what was removed and may not notice that anything was, so it can carry on as if it still had the full history. With receipts on, a boundary-crossing strategy appends a short, deterministic note saying how much was compacted, that what survives is secondhand, and, with a handle provider attached, where the persisted run history is.
from pydantic_ai_harness import SlidingWindowCompaction, SummarizingCompaction
SummarizingCompaction(max_messages=60, keep_messages=20, receipts=True)
SlidingWindowCompaction(max_messages=80, keep_messages=40, receipts=True)
The receipt text has no timestamp, so it is a pure function of the compaction; the message part keeps its ordinary request timestamp.
SummarizingCompaction’s receipt says the summary above is secondhand; SlidingWindowCompaction’s says the dropped context is gone. ClearToolResults, DeduplicateFileReads, and ClampOversizedMessages blank in place, keep every message, and cross no boundary, so they emit none.
Each receipt is a CompactionReceiptPart, a capability part in the application’s voice that stays with the compacted history: the model sees it where the compaction cut, as a mid-conversation system message, or as a <system> block on a model without one, never as the user’s words, so it doesn’t start a user turn. Its text is only the strategy’s own wording with counts, the by attribution and the handle filled in. Find receipts in history by this type. Earlier versions wrote receipts as user prompts; one in a saved history is still recognized, by its metadata, never its text, and replaced at the next compaction, which already moves the cached prefix. With a UI adapter in its default manage_system_prompt='server' mode, the dump leaves out capability parts, so history the client sends back has no receipts.
SlidingWindowCompaction counts its receipt toward keep_messages (keep_messages=40 keeps the receipt and 39 messages), but the receipt never takes the last slot: keep_messages=1 keeps the receipt and the newest message.
Attach a capability exposing compaction_transcript_handle() -> str | None (the TranscriptHandleProvider protocol), such as StepPersistence, which returns its run_id, and the receipt gains a Persisted run handle: <handle> line. Each receipt is also a compaction.receipt event on the compact_messages span, with compaction.receipt.strategy, compaction.receipt.messages_dropped, compaction.receipt.tokens_dropped, compaction.receipt.by, and compaction.receipt.handle when a handle was found.
The handle points to the persisted run, not a pristine transcript: compaction’s edits persist, so the run’s latest snapshot holds the compacted history and does not recover what was dropped. A store keeping per-step snapshots may still hold pre-compaction steps, subject to its retention (max_snapshots_per_run on the shipped stores); check it before promising an agent it can read the original.
The receipt’s by attribution uses the bridge prefix’s coarse family heuristic, with the same approximations.
Receipts are opt-in (receipts=False by default) because they add a message the model reads.
pin marks content that every shipped strategy must preserve verbatim:
from pydantic_ai_harness.compaction import pin
# In a ModelRequest placed in the run's message history (by a capability or the user):
pinned = pin('Durable task state the model must never lose across compaction.')
# Content a tool or the model wrote, framed so the model doesn't read it as the user's words:
scratchpad = pin('Port 8421 is taken; use 8422.', source='model')
A pinned part is never summarized away or dropped; a strategy that would discard it re-injects it verbatim near the top of the surviving history. is_pinned checks for the marker, which lives in model-invisible TextContent.metadata so compaction can tell pins apart from user turns. A pin with the default source='user' reaches the model as ordinary user context. Pass source='tool' or source='model' for content the user didn’t write: it reaches the model on the user channel as <pinned source="tool"> or <pinned source="model"> data, with any framing tags inside it escaped.
Planning does not need pinning: when compaction removes or clears the plan tools’ results showing the latest plan, the next request records the plan from its store. Pinning is for durable task state and scratchpads that live in the history.
Pydantic AI counts an on-demand capability as loaded while its load record is in the history after the latest compaction: the model’s load_capability exchange, or the CapabilityLoadDeltaPart a load from code leaves. Removing that record would unload the capability (its tools leave the request and its instructions stop) while the summary may still say it’s loaded.
So when SummarizingCompaction, SlidingWindowCompaction, RelevanceCompaction or ResetCompaction removes a load, it records it again the way a load from code is recorded, right after the summary (or before the kept messages when there’s none): a CapabilityLoadDeltaPart naming the capability, then the ToolAvailabilityDeltaPart revealing its tools, if any. This is a framework record of what’s loaded, not a load_capability call the model never made. The capability stays loaded, its tools stay in the request, and Pydantic AI restates its current instructions in the system voice. Summaries leave out every load record, the model’s own exchanges included: the re-recorded records, never the summary, say what is loaded. Only capabilities the run still registers as on-demand are recorded; compact_now, with no run to ask, records every load, and the next run ignores loads of capabilities it doesn’t register.
Set preserve_loaded_capabilities=False on the strategy to let them unload. It then leaves a note in the same place naming the unloaded capabilities, so the model can reload what it needs instead of hitting a refused tool call. The note is marked as harness content, so a later summary treats it as data, not the user’s words.
ClearToolResults, DeduplicateFileReads and ClampOversizedMessages keep every message and its load records, so loads survive them. Provider-native compaction (OpenAICompaction, AnthropicCompaction) runs no harness strategy, so it still unloads them.
A tool found through tool search stays discovered while its discovery record is in the history after the latest compaction: the model’s search_tools exchange, the provider’s native search result, or a ToolReturn.tools reveal. When SummarizingCompaction, SlidingWindowCompaction, RelevanceCompaction or ResetCompaction removes that record, it re-records the discovery as a ToolAvailabilityDeltaPart naming the tools, where it records capability loads. This is a framework record of what the model was shown, not a search it never made, so a provider’s native search result is kept the same way as a local one. The tools stay in the request and the model can call them without searching again. A tool revealed by a capability load is left to that load, so preserve_loaded_capabilities=False unloads it with its capability. Provider-native compaction still drops discoveries, so the model searches again.
User turns carry the most signal per token. SummarizingCompaction(keep_user_messages=True) keeps the newest user turns from the summarized prefix next to the summary, superseding preserve_first_user_message, which keeps only the first.
from pydantic_ai_harness import SummarizingCompaction
SummarizingCompaction(max_tokens=120_000, keep_messages=20, keep_user_messages=True)
In message-count mode, kept turns share the keep_messages tail budget, so at most that many kept user and tail messages survive together, except that one tail slot is reserved for the request being answered when kept turns would otherwise take it; retained copies don’t grow each cycle. The tail messages the kept turns leave no room for are summarized with the rest of the prefix, and the kept turns are the newest user turns of everything summarized. With a positive keep_tokens, the original suffix takes precedence: keep_messages caps only the additional older user turns, which don’t shrink the retained tail. With keep_tokens=0, kept user copies must fit a zero-token budget, and the newest tail message still survives.
Each kept turn is cut to keep_user_messages_max_chars (default 20k) with an explicit truncation marker, per part and shared across a multi-part prompt’s text items; images, audio, and cache points pass through. A kept copy is recognized by a marker on its text items, never by request metadata, which isn’t trusted as provenance, so a turn marked only there is summarized and bounded like any other. Copies kept by releases before 2.60 carry only that request-level marker, as does a copy whose text items had non-dict metadata, so the first compaction after upgrading summarizes them once more and keeps them again.
Harness-added content on the user channel, such as a background tool’s result, isn’t a user turn: keep_user_messages and preserve_first_user_message don’t carry it over from the summarized prefix (including from a turn an earlier compaction kept), and it is summarized as data, not user intent. The unsummarized recent suffix is kept as is, harness content included.
Kept user turns and any receipt become adjacent ModelRequests after the summary. Providers that require one request per turn, such as Bedrock Converse and Gemini, never see that: after the before_model_request hooks, Pydantic AI merges adjacent requests into one turn before dispatch, so keep_user_messages needs no provider-specific handling.
With incremental=True (the default), a prior summary is not re-summarized, since summaries of summaries decay. It is fed back in a <previous-summary> block with an update instruction: keep still-true details, remove stale ones, merge in new facts, under a fixed structure.
bridge_prefix=True prepends a one-line note to the summary only when the summarizer’s model family differs from the history’s (from its model_name and the summarizer config), marking a cross-model handoff so the resuming model builds on the summary rather than assuming it did the work itself. It never fires in the common same-model case, and defaults to False because the note is prompt content.
The family is a coarse approximation: drop any provider: prefix, then take the token before the first - or /. That separates gpt from claude on ordinary ids (openai:gpt-5.6-luna -> gpt, google:gemini-3.6-flash -> gemini) but misreads some: us.anthropic.claude-sonnet-4-5-v1:0 becomes 0, ollama/llama3 becomes ollama, and a fallback: model string reads as its last listed model rather than its first (a FallbackModel object is read correctly, from its first model). Bridge and receipt attribution are best-effort: a misread family can suppress a bridge note or add one between same-family models, but never changes what compaction keeps or drops.
These strategies compress or drop context inside the window. Moving large tool outputs out of it, to a file the agent (or a subagent) can query on demand, is the job of tool output limits. SummarizingCompaction’s tool_return_max_chars only tunes how much of each return the summarizer reads (None renders returns whole); prefer tool output limits when a payload must stay queryable in full.
The recommended default is TieredCompaction; the other strategies below work standalone or as its tiers.
Bases: AbstractCapability[AgentDepsT]
Escalation orchestrator over a sequence of compaction strategies.
Runs each tier in order, re-measuring the token count after each, and stops as soon as
the conversation fits target_tokens. Order tiers cheap-to-expensive (e.g. clear
tool results, deduplicate reads, then summarize) so the expensive summarization tier is
only reached when the cheap passes cannot reclaim enough.
Each tier’s own trigger is bypassed — TieredCompaction drives the tiers directly via
their compact method and decides when to stop — so tiers need none.
On its own trigger, a tier that raises a skip_on exception is skipped and escalation
moves on to the next tier; other exceptions propagate. A direct compact call lets
every exception propagate.
Strategies to apply in order, cheap-to-expensive. The last is typically a summarizer.
Type: Sequence[CompactionStrategy[AgentDepsT]]
Stop escalating once the estimated token count is at or below this value.
Mutually exclusive with target_fraction; exactly one of the two must be set.
Type: int | None Default: None
Target expressed as a fraction of the model’s context window, resolved per request.
Use this instead of target_tokens when the same agent runs on models with
different windows. Mutually exclusive with target_tokens.
Type: float | None Default: field(default=None, kw_only=True)
Window override in tokens. None resolves it from the request’s model.
Unlike fallback_context_window, this applies whether or not resolution succeeds. Reach
for it when the registry is confidently wrong: a beta- or tier-gated window it records as
the maximum, or a self-hosted endpoint whose model id describes someone else’s
deployment. Only consulted alongside target_fraction.
Type: int | None Default: field(default=None, kw_only=True)
Window assumed when the model is not in the pricing registry.
Only consulted alongside target_fraction. Supply the real number for a deployment the
registry cannot resolve.
Type: int Default: field(default=DEFAULT_CONTEXT_WINDOW, kw_only=True)
Optional tokenizer for accurate token counting.
A callable that returns the token count for a given string.
When None, uses the built-in text estimate, which counts dense text such as non-ASCII
scripts, base64 and compact JSON higher than prose.
Type: Callable[[str], int] | None Default: None
Exceptions that skip a failing tier on this capability’s own trigger, rather than failing the run.
Defaults to model failures, so programming errors and usage limits propagate. Pass () to
propagate every exception. Includes UnexpectedModelBehavior, which a summary tier raises when
it exhausts its retries, so the next tier can still shrink the history without that tier’s
model; FallbackCompaction.fallback_on uses the same selection.
Type: tuple[type[Exception], …] Default: field(default=(ModelAPIError, FallbackExceptionGroup, UnexpectedModelBehavior), kw_only=True)
def with_focus(focus: str) -> TieredCompaction[AgentDepsT]
Return a copy whose focus-capable tiers prioritize focus.
A tiered strategy is focusable when any of its tiers is: the summarizing tier writes the prose, so the hint has to reach it rather than stopping at this wrapper. Tiers that cannot honour a focus are passed through unchanged.
TieredCompaction[AgentDepsT]
@async
def compact(
messages: list[ModelMessage],
ctx: RunContext[AgentDepsT],
) -> list[ModelMessage]
Apply tiers in order until the history fits the target or tiers run out.
@async
def before_model_request(
ctx: RunContext[AgentDepsT],
request_context: ModelRequestContext,
) -> ModelRequestContext
Escalate through the tiers when the conversation exceeds the target.
Bases: AbstractCapability[AgentDepsT]
Zero-cost head/tail truncation of any single oversized message part.
A runaway generation — a model response of repeated whitespace, a giant tool-call
payload — can produce one part so large the next request exceeds the provider’s context
cap. The size-based strategies cannot help: SlidingWindowCompaction drops the oldest messages
(the offender is the newest), ClearToolResults only touches tool results, and feeding
the history to SummarizingCompaction hits the same cap. This strategy truncates the
offending part in place: it keeps a head slice and a tail slice and inserts a marker for
the removed middle. Degenerate generations are low-entropy repetition, so a head/tail
slice loses little. No LLM calls are made.
What it clamps, in each ModelResponse:
TextPartcontent (the critical case — a runaway model-response text part).ToolCallPartargs, whenclamp_tool_call_argsis set (the same failure shape for a giant tool-call payload). The args are replaced with a small JSON object so they stay valid function arguments; the original call already executed, so this only shrinks the history copy. Framework-typed subclasses (ToolSearchCallPart,LoadCapabilityCallPart) are never clamped: their typed args must survive theModelMessagesTypeAdapterround-trip that persistence relies on.
Request-side parts (user prompts, tool returns, system prompts) are out of scope: user
input should not be silently rewritten, and oversized tool returns are the job of
ToolOutputLimits, which reduces a return when the tool produces it. ClearToolResults keeps
the newest keep_pairs results intact, and with keep_pairs=0 it blanks a fresh return
outright rather than shrinking it.
Clamping rewrites message content, so it invalidates the provider’s prompt cache from the clamped message onward. That is unavoidable here — the alternative is a failed request.
A clamped part also loses its item ID (TextPart.id, ToolCallPart.id): the OpenAI Responses
API uses its stored copy of an item sent with its ID and ignores the content sent alongside.
A part is clamped only when it is oversized and the clamp actually shrinks it, so set
keep_head_chars + keep_tail_chars well below your per-part threshold.
Composes as the first tier of a TieredCompaction (run it before ClearToolResults):
it is the only zero-LLM way to keep a run alive after a runaway generation.
Clamp a part whose estimated token count exceeds this value. None disables this trigger.
Type: int | None Default: None
Clamp a part whose character count exceeds this value. None disables this trigger.
Type: int | None Default: None
Characters of the part’s head to retain.
Type: int Default: 2000
Characters of the part’s tail to retain.
Type: int Default: 2000
When True, also clamp oversized ToolCallPart args, not just response text.
Type: bool Default: True
Optional tokenizer for accurate token counting.
A callable that returns the token count for a given string.
When None, uses the built-in text estimate, which counts dense text such as non-ASCII
scripts, base64 and compact JSON higher than prose.
Type: Callable[[str], int] | None Default: None
@async
def compact(
messages: list[ModelMessage],
ctx: RunContext[AgentDepsT],
) -> list[ModelMessage]
Clamp every oversized response text part (and tool-call args, if enabled).
@async
def before_model_request(
ctx: RunContext[AgentDepsT],
request_context: ModelRequestContext,
) -> ModelRequestContext
Clamp any oversized response part before the request is sent.
Bases: AbstractCapability[AgentDepsT]
Zero-cost in-place clearing of old tool results.
Replaces the content of the oldest tool results with a short placeholder while
keeping the most recent keep_pairs tool-call / tool-return pairs, or the results of the
last keep_turns user turns, intact. Tool calls remain paired with their (now-blanked)
results, so the history stays valid. No LLM calls are made.
This is the cheap first tier of compaction — tool results typically dominate context, and the agent can re-run a tool if it needs the data again.
Cache tradeoff: clearing rewrites message content, which invalidates the provider’s
prompt cache from the clear point onward (the next request pays a cache-write). Use
min_clear_tokens to skip clearing that reclaims too little to be worth busting the
cache.
Trigger clearing when the messages since the last cleared tool result exceed this value. None disables.
Clearing blanks content but removes no messages, so a plain message count would stay above
the threshold and clear one more result on every request, rewriting history (and busting the
prompt cache) each step. Counting from the last cleared result instead makes clearing happen
in batches, and the requests between two clears extend the cached prefix. Before the first clear
the count is the whole history. The kept pairs count toward it: right after a clear about
2 * keep_pairs messages follow the last cleared result, and each tool step adds two more, so
the next clear comes after about (max_messages - 2 * keep_pairs) / 2 tool steps. At or below
2 * keep_pairs it clears on every request. With keep_turns, the messages of the kept turns
count toward it the same way.
Type: int | None Default: None
Trigger clearing when estimated token count exceeds this value. None disables.
Type: int | None Default: None
Trigger when estimated tokens exceed this fraction of the model’s context window.
Resolved per request from the request’s model, so one setting behaves correctly on any
model. Mutually exclusive with max_tokens.
Type: float | None Default: field(default=None, kw_only=True)
Window override in tokens. None resolves it from the request’s model.
Unlike fallback_context_window, this applies whether or not resolution succeeds. Reach
for it when the registry is confidently wrong: a beta- or tier-gated window it records as
the maximum, or a self-hosted endpoint whose model id describes someone else’s
deployment. Only consulted alongside max_fraction.
Type: int | None Default: field(default=None, kw_only=True)
Window assumed when the request’s model is not in the pricing registry.
Only consulted alongside max_fraction. Supply the real number for a deployment the
registry cannot resolve.
Type: int Default: field(default=DEFAULT_CONTEXT_WINDOW, kw_only=True)
Number of most-recent tool-call / tool-return pairs left untouched.
keep_turns replaces the pair count when set; setting both to a keep_pairs other than the
default raises a UserError.
Type: int Default: 3
Replacement content for a cleared tool result, or a function that builds it from the result.
A function is called when the result is cleared, and its return value is stored as the result’s
content; an already-cleared result is not passed to it again. With min_clear_tokens, it’s called
before the reclaim is measured, so a clear that reclaims too little is dropped and the function
is called for the same results again on a later request. It must be deterministic:
the same result has to produce the same text on every run, or a history cleared again from its
original (a resumed or replayed run) is sent with different content and the provider’s prompt
cache misses from that point on. A result whose metadata is something other than None or a
dict is not cleared with a function, because the mark that records the clear can’t be stored.
A function can’t be expressed in an agent spec, so a spec only accepts a string here.
Type: str | Callable[[ToolReturnPart], str] Default: '[tool result cleared]'
Tool names whose results are never cleared. Mutually exclusive with tools.
Type: frozenset[str] Default: frozenset()
When True, also blank the arguments of the cleared tool calls.
Type: bool Default: False
Only clear if doing so reclaims at least this many estimated tokens.
Protects the prompt cache from being invalidated for a trivial gain. None always clears.
Type: int | None Default: None
Optional tokenizer for accurate token counting.
A callable that returns the token count for a given string.
When None, uses the built-in text estimate, which counts dense text such as non-ASCII
scripts, base64 and compact JSON higher than prose.
Type: Callable[[str], int] | None Default: None
Tool names whose results are cleared; the results of other tools are kept. None clears every tool’s.
When set, keep_pairs counts only the listed tools’ pairs, so tools=['retrieve'], keep_pairs=2
keeps the newest two retrieve results whatever other tools ran in between. With several listed
tools, the window is shared across them. Mutually exclusive with exclude_tools.
Type: Sequence[str] | None Default: field(default=None, kw_only=True)
Keep the tool results of the last keep_turns completed user turns, plus the current one.
A user turn starts at a request carrying the user’s prompt, and runs until the next one. The
current turn, the one the model is answering, is never cleared, so 0 clears the results of
every earlier turn. Prompts added by harness capabilities, such as pinned messages and
compaction receipts, don’t start a turn, and neither does user content sent with tool results,
such as a ToolReturn’s content. Replaces the keep_pairs count when set.
Type: int | None Default: field(default=None, kw_only=True)
@async
def compact(
messages: list[ModelMessage],
ctx: RunContext[AgentDepsT],
) -> list[ModelMessage]
Blank the oldest tool results beyond the most recent keep_pairs, or before the last keep_turns.
@async
def before_run(ctx: RunContext[AgentDepsT]) -> None
Reject a registration without a trigger.
@async
def before_model_request(
ctx: RunContext[AgentDepsT],
request_context: ModelRequestContext,
) -> ModelRequestContext
Clear old tool results if the conversation exceeds the configured threshold.
Bases: AbstractCapability[AgentDepsT]
Zero-cost in-place clearing of superseded file reads.
When the same file is read more than once, only the latest read keeps its content; earlier reads are blanked with a placeholder. Tool-call pairing is preserved. No LLM calls are made.
File identity is supplied by the file_key seam — given a ToolCallPart it returns
a stable key for the file being read, or None if the call is not a file read. There
is no default: file-read identification is agent-specific, and a wrong guess would drop
live data.
Map a tool call to a stable file key, or None if it is not a file read.
Type: Callable[[ToolCallPart], str | None]
Replacement content for a superseded file read.
Type: str Default: '[superseded file read]'
Optional message-count trigger. When both triggers are None, runs whenever invoked.
Type: int | None Default: None
Optional token-count trigger. When both triggers are None, runs whenever invoked.
Type: int | None Default: None
Trigger when estimated tokens exceed this fraction of the model’s context window.
Resolved per request from the request’s model, so one setting behaves correctly on any
model. Mutually exclusive with max_tokens.
Type: float | None Default: field(default=None, kw_only=True)
Window override in tokens. None resolves it from the request’s model.
Unlike fallback_context_window, this applies whether or not resolution succeeds. Reach
for it when the registry is confidently wrong: a beta- or tier-gated window it records as
the maximum, or a self-hosted endpoint whose model id describes someone else’s
deployment. Only consulted alongside max_fraction.
Type: int | None Default: field(default=None, kw_only=True)
Window assumed when the request’s model is not in the pricing registry.
Only consulted alongside max_fraction. Supply the real number for a deployment the
registry cannot resolve.
Type: int Default: field(default=DEFAULT_CONTEXT_WINDOW, kw_only=True)
Optional tokenizer for accurate token counting.
A callable that returns the token count for a given string.
When None, uses the built-in text estimate, which counts dense text such as non-ASCII
scripts, base64 and compact JSON higher than prose.
Type: Callable[[str], int] | None Default: None
@async
def compact(
messages: list[ModelMessage],
ctx: RunContext[AgentDepsT],
) -> list[ModelMessage]
Blank every file read that is later superseded by a newer read of the same file.
@async
def before_model_request(
ctx: RunContext[AgentDepsT],
request_context: ModelRequestContext,
) -> ModelRequestContext
Deduplicate file reads, optionally gated on a size threshold.
Bases: AbstractCapability[AgentDepsT]
Zero-cost sliding-window trimmer.
When the conversation exceeds a configurable threshold (message count or estimated token count), the oldest messages are discarded while preserving tool-call / tool-return pairs. No LLM calls are made.
Trimming happens in before_model_request so it is transparent to the
rest of the agent run.
Trigger trimming when message count exceeds this value. None disables.
Type: int | None Default: None
Trigger trimming when estimated token count exceeds this value. None disables.
Type: int | None Default: None
Trigger when estimated tokens exceed this fraction of the model’s context window.
Resolved per request from the request’s model, so one setting behaves correctly on any
model. Mutually exclusive with max_tokens.
Type: float | None Default: field(default=None, kw_only=True)
Window override in tokens. None resolves it from the request’s model.
Unlike fallback_context_window, this applies whether or not resolution succeeds. Reach
for it when the registry is confidently wrong: a beta- or tier-gated window it records as
the maximum, or a self-hosted endpoint whose model id describes someone else’s
deployment. Only consulted alongside max_fraction.
Type: int | None Default: field(default=None, kw_only=True)
Window assumed when the request’s model is not in the pricing registry.
Only consulted alongside max_fraction. Supply the real number for a deployment the
registry cannot resolve.
Type: int Default: field(default=DEFAULT_CONTEXT_WINDOW, kw_only=True)
Number of tail messages to retain after trimming (message-count trigger).
The newest message is always kept, so 0 keeps one. With receipts=True, the receipt
counts as one of these, but never displaces the newest message.
Type: int Default: 40
Minimum original message-content tokens to retain in an unchanged recent suffix.
Whole messages and tool dependencies can exceed this floor. Attached instructions do
not count. When None, falls back to keep_messages; zero keeps legacy edge behavior.
Type: int | None Default: None
Optional tokenizer for accurate token counting.
A callable that returns the token count for a given string.
When None, uses the built-in text estimate, which counts dense text such as non-ASCII
scripts, base64 and compact JSON higher than prose.
Type: Callable[[str], int] | None Default: None
When True, the first ModelRequest containing a UserPromptPart
is always kept after trimming, in addition to system prompts.
Type: bool Default: True
When True, a deferred capability loaded in the dropped messages stays loaded.
Core counts a capability as loaded while the record of its load is in the history, so dropping
the record would unload it. Each such load is recorded again ahead of the kept
messages instead, and the capability’s tools and current instructions are sent again. When
False, those capabilities are unloaded, and a note names them so the model can load the ones
it still needs.
Type: bool Default: field(default=True, kw_only=True)
When True, prepend a deterministic compaction receipt recording how much history
was dropped, with a transcript handle when a TranscriptHandleProvider capability is attached.
Type: bool Default: False
@async
def compact(
messages: list[ModelMessage],
ctx: RunContext[AgentDepsT],
) -> list[ModelMessage]
Drop the oldest messages down to the configured tail.
@async
def before_run(ctx: RunContext[AgentDepsT]) -> None
Reject a registration without a trigger.
@async
def before_model_request(
ctx: RunContext[AgentDepsT],
request_context: ModelRequestContext,
) -> ModelRequestContext
Trim the message list if it exceeds the configured threshold.
Bases: AbstractCapability[AgentDepsT]
Compact the conversation by summarizing older messages with a model call.
When the conversation exceeds a configurable threshold, older messages are replaced with a structured summary message, preserving recent context and tool-call integrity.
Summarization turns input tokens into output tokens, which cost more, so it is best
used behind cheaper passes (see TieredCompaction).
The summary call’s usage is folded into the parent run’s usage and counts as a request, so request-count limits apply to it.
Model used to generate summaries.
When None, inherits the model the request being compacted is going to. Core starts
that as the run’s model, so the two differ only where a capability replaced
ModelRequestContext.model; set this explicitly to pin the summarizer regardless.
Type: str | Model | None Default: None
Settings for the dedicated summary model call.
These merge over defaults carried by model, allowing the summary call to use a
policy that differs from the running agent without mutating the model.
Type: ModelSettings | None Default: field(default=None, kw_only=True)
If set, this handler is passed to the nested summary run, so the summarizer’s own model-streaming events surface to the caller.
Setting it also selects the streaming request path, which is what a summarizer endpoint
that rejects non-streaming requests needs; pass drain_summary_events to take that path without
handling the events. Left None, the summary request is non-streaming, which is what an
endpoint that rejects streaming requests needs. The handler receives the summary run’s own
RunContext, never the outer run’s, and the outer Agent.run(...) handler is not inherited.
Type: EventStreamHandler[object] | None Default: field(default=None, kw_only=True)
Capabilities attached to the agent that writes the summary.
The summary runs on its own Agent, so capabilities on the outer agent do not run on it.
Capabilities listed here do, with every hook of that run.
The summary agent has no deps, so these are AbstractCapability[None].
Type: Sequence[AbstractCapability[None]] Default: field(default=(), kw_only=True)
Retry budget for the summary agent, covering output retries and tool calls alike.
Core’s default of 1 absorbs one failure: a whitespace-only summary, or one imitation of a tool
call read from the transcript it summarizes. A second consecutive failure raises
UnexpectedModelBehavior: on this capability’s own trigger the attempt is discarded and the
history left unchanged, FallbackCompaction moves on to its next strategy, and an explicit
compact() or compact_now() call raises it. The agent is toolless, so raising this burns nothing but
requests — every retry is a real request charged to the run’s usage, so a finite request_limit
still binds first.
Type: int Default: field(default=1, kw_only=True)
Trigger compaction when message count exceeds this value.
Type: int | None Default: None
Trigger compaction when estimated token count exceeds this value.
Type: int | None Default: None
Trigger when estimated tokens exceed this fraction of the model’s context window.
Resolved per request from the request’s model, so one setting behaves correctly on any
model. Mutually exclusive with max_tokens.
Type: float | None Default: field(default=None, kw_only=True)
Window override in tokens. None resolves it from the request’s model.
Unlike fallback_context_window, this applies whether or not resolution succeeds. Reach
for it when the registry is confidently wrong: a beta- or tier-gated window it records as
the maximum, or a self-hosted endpoint whose model id describes someone else’s
deployment. Only consulted alongside max_fraction.
Type: int | None Default: field(default=None, kw_only=True)
Window assumed when the request’s model is not in the pricing registry.
Only consulted alongside max_fraction. Supply the real number for a deployment the
registry cannot resolve.
Type: int Default: field(default=DEFAULT_CONTEXT_WINDOW, kw_only=True)
Number of tail messages to preserve after compaction (message-count trigger).
The newest message is always kept, so 0 keeps one.
Type: int Default: 20
Minimum original message-content tokens to retain in an unchanged recent suffix.
Whole messages and tool dependencies can exceed this floor. Attached instructions do
not count. When None, falls back to keep_messages; zero keeps legacy edge behavior.
Type: int | None Default: None
Prompt template for generating summaries.
Must contain a {messages} placeholder and no other replacement field. Write a literal
brace as {{ or }}.
A custom prompt replaces the default in full, including its rule that instructions inside tool results or fetched content aren’t the user’s, so include a rule of your own.
Type: str Default: _DEFAULT_SUMMARY_PROMPT
Instructions for the internal agent that writes the summary.
summary_prompt shapes the user turn of the summary request; this sets the internal
agent’s static instructions, which Pydantic AI sends in the request’s system prompt.
Override it when the summarizer endpoint requires a fixed leading instruction.
Type: str Default: field(default=_DEFAULT_INSTRUCTIONS, kw_only=True)
Optional tokenizer for accurate token counting.
A callable that returns the token count for a given string.
When None, uses the built-in text estimate, which counts dense text such as non-ASCII
scripts, base64 and compact JSON higher than prose.
Type: Callable[[str], int] | None Default: None
When True, the first ModelRequest containing a UserPromptPart
is always kept after compaction, in addition to system prompts. System prompts,
earlier summaries and receipts in it are dropped, as the new summary request
carries their current versions.
Type: bool Default: True
When True, feed any existing summary from a prior compaction back as an anchored
<previous-summary> block with an update instruction (preserve still-true, remove stale,
merge new) so it is updated in place rather than re-summarized — avoiding
summary-of-summary decay.
Type: bool Default: True
When True and the summarizer’s model family differs from the family that produced
the history, prepend a neutral one-line note marking the summary as a cross-model handoff.
Nothing is added when the families match.
Type: bool Default: False
When True, preserve recent summarized user messages (each truncated to
keep_user_messages_max_chars) alongside the summary. Retained messages consume the
keep_messages tail budget in message-count mode. With positive keep_tokens,
keep_messages caps only extra user copies, which do not displace the retained suffix. Supersedes
preserve_first_user_message.
Type: bool Default: False
Per-message character cap for keep_user_messages; oversized messages are truncated
with an explicit marker (the shared truncation-marker convention).
Type: int Default: 20000
Per-return character cap when rendering tool results for the summarizer. None renders
them whole.
Type: int | None Default: field(default=500, kw_only=True)
When True, a deferred capability loaded in the summarized messages stays loaded.
Core counts a capability as loaded while the record of its load is after the latest compaction,
so summarizing the record would unload it. Each such load is recorded again after
the summary instead, and the capability’s tools and current instructions are sent again. When
False, those capabilities are unloaded, and a note after the summary names them so the model
can load the ones it still needs.
Type: bool Default: field(default=True, kw_only=True)
When True, append a deterministic compaction receipt after the summary noting how
much history was summarized, that the summary is secondhand, and — when a
TranscriptHandleProvider capability is attached — a persisted-run handle.
Type: bool Default: False
def with_focus(focus: str) -> SummarizingCompaction[AgentDepsT]
Return a copy whose summary prompt prioritizes focus.
Used by compact_now so a user-invoked compaction can say what the summary must not
lose. The prompt is later run through str.format, so braces in a user- or
model-supplied focus are escaped to survive it.
SummarizingCompaction[AgentDepsT]
@async
def compact(
messages: list[ModelMessage],
ctx: RunContext[AgentDepsT],
) -> list[ModelMessage]
Summarize older messages, replacing them with a single summary message.
@async
def before_run(ctx: RunContext[AgentDepsT]) -> None
Reject a registration without a trigger.
@async
def before_model_request(
ctx: RunContext[AgentDepsT],
request_context: ModelRequestContext,
) -> ModelRequestContext
Summarize older messages when the threshold is exceeded.
Bases: AbstractCapability[AgentDepsT]
Compact by judging each older step of the history: keep it verbatim, reduce it, or drop it.
A step is a model response together with the requests that answer it (its tool results, retry
feedback, and the next user prompt), so removing one never splits a tool call from its result. The
system prompt and first user message, and the most recent keep_tokens of history, are never
judged. Pinned content survives even when its step is removed.
For every other step, the judge (model) is shown the task (the first and latest user prompts), the
recent conversation and the step, and asked two questions in one request: will the agent need the
step’s exact content, and does it record anything that still matters. On a decision model, such
as system-one:<model> or TypeSafe’s typesafe:jev-latest, each answer is the model’s probability of
yes; any other model fills the same two fields as structured output. Steps are kept verbatim in order
of the first answer until the history fits the target, the rest are ranked by the second answer and
reduced while they fit, and whatever is left is dropped. A step holding a user prompt is never
dropped: it is reduced, or kept when it does not fit the summarizer’s input.
Reducing writes the reduced steps into one summary at the front of the history when a summarizer
is configured; without one, each tool result in a reduced step is cut to its first
truncated_result_chars characters and a note, and everything else in the step is kept.
Judge failures propagate, as a summarizer failure does: wrap this in FallbackCompaction to fall back
to another strategy. Inside a durable workflow the judgements and the summary are durable operations,
addressed by this capability’s id.
The judge: the model that judges each step, a decision model or any model that supports structured output.
Type: Model | KnownModelName | str
Writes the reduced steps into a summary, with its own model, prompt and settings.
Only its summary settings are used; its trigger and keep_* fields are not. None reduces a step by
truncating its tool results instead, which needs no language model.
Type: SummarizingCompaction[AgentDepsT] | None Default: None
Trigger when the estimated context exceeds this many tokens. Mutually exclusive with max_fraction.
Type: int | None Default: None
Trigger above this fraction of the request model’s context window. Mutually exclusive with max_tokens.
Type: float | None Default: None
Size to compact down to, in tokens. Defaults to half the trigger. Mutually exclusive with target_fraction.
Type: int | None Default: None
Size to compact down to, as a fraction of the request model’s context window.
Type: float | None Default: None
Window override in tokens, consulted only alongside a fraction.
Type: int | None Default: None
Window assumed when the request model cannot be resolved, alongside a fraction.
Type: int Default: DEFAULT_CONTEXT_WINDOW
Message tokens at the end of the history that are kept unchanged and never judged.
Type: int Default: 8000
Most tokens of reduced steps handed to the summarizer in one compaction; lower-ranked steps are dropped.
Type: int Default: 30000
Most tokens of a step the judge is shown: a longer step is shown by its start and end.
Type: int Default: 2000
Most tokens of the current task, and separately of the recent conversation, the judge is shown with a step.
A judge request holds at most judge_step_tokens plus twice this, as estimated at ~4 characters per
token. Code and JSON tokenize nearer 2 characters per token, so the defaults keep a request under
the 8,192-token input of small local decision models.
Type: int Default: 500
Most judge requests in flight at once.
Type: int Default: 8
Characters of a tool result kept when a step is reduced without a summarizer.
Type: int Default: 300
Keep a deferred capability loaded when the step that loaded it is summarized or dropped.
Core counts a capability as loaded while the record of its load is after the latest compaction,
so removing the step would unload it. Each such load is recorded again ahead of the
kept steps instead, and the capability’s tools and current instructions are sent again. When
False, those capabilities are unloaded, and a note names them so the model can load the ones
it still needs.
Type: bool Default: True
Insert a deterministic note after the head of the history saying how much was summarized or dropped.
Type: bool Default: False
Optional token counter; defaults to the built-in text estimate.
Type: Callable[[str], int] | None Default: None
Stable identity for durable operations; two on one agent merge into one.
Type: str | None Default: 'relevance_compaction'
def with_focus(focus: str) -> RelevanceCompaction[AgentDepsT]
Return a copy whose judge, and summarizer if any, give particular weight to focus.
RelevanceCompaction[AgentDepsT]
@async
def before_model_request(
ctx: RunContext[AgentDepsT],
request_context: ModelRequestContext,
) -> ModelRequestContext
Compact when the estimated context exceeds the trigger.
@async
def compact(
messages: list[ModelMessage],
ctx: RunContext[AgentDepsT],
) -> list[ModelMessage]
Judge the steps between the protected head and tail, then keep, reduce or drop each one.
Bases: AbstractCapability[AgentDepsT]
Clear the conversation down to a small kept shape, and leave a notice pointing the model at its work log.
When the history passes a trigger, everything is cleared except the first user request, what
the user wrote in later turns, pinned content, loaded capabilities and the last keep_messages
messages. A notice in the application’s voice says the conversation was cleared and names the
WorkLog’s tools, so the model can search and read the full results of its earlier work instead
of running it again. No model is called. A later reset replaces the notice rather than adding
another.
work_log must be the WorkLog registered on the same agent. It is passed explicitly because
used as a strategy, such as through compact_now, the reset has no agent to find it on.
The WorkLog registered on the same agent, whose log the notice points at.
Type: WorkLog[AgentDepsT]
Reset when the history has more messages than this. None disables.
Type: int | None Default: None
Reset when the history’s estimated tokens exceed this. None disables.
Type: int | None Default: None
Reset when estimated tokens exceed this fraction of the request’s model’s context window.
Resolved per request from the request’s model. Mutually exclusive with max_tokens. Registered on an
agent, it needs one of max_messages, max_tokens or max_fraction, and a run raises UserError at its
start without one; as a strategy (a TieredCompaction tier, a FallbackCompaction entry, or the strategy
of CompactOnRequest or compact_now) it needs none.
Type: float | None Default: None
Window override in tokens. None resolves it from the request’s model.
Only consulted alongside max_fraction.
Type: int | None Default: None
Window assumed when the request’s model is not in the pricing registry.
Only consulted alongside max_fraction.
Type: int Default: DEFAULT_CONTEXT_WINDOW
Messages kept at the end of the conversation, after the notice.
Tool calls stay with their results, and the newest message is always kept, so 0 keeps one.
Type: int Default: 2
Keep what the user wrote in each turn after the first, ahead of the kept messages, when they don’t hold it.
Only the user’s own parts, all in one request, so the kept history grows by no message per turn: tool
results and harness data in the same requests are cleared. With False, only the first request and the
kept messages hold the user’s words.
Type: bool Default: True
Write the notice’s text from what the reset did. Defaults to default_reset_notice.
The text is sent in the application’s voice, so build it from the facts and your own wording, never from text a user or a tool supplied.
Type: Callable[[ResetNotice], str] Default: default_reset_notice
Return the task’s current state to put after the notice, in a <current_state> frame.
A string is recorded as the output of the restate callable (a ToolResultSource named after it), so text in
it that looks like a frame gets a note. Return a CurrentStatePart to give it another source, such as
OperatorSource() for text your application wrote. None or an empty string adds nothing. Runs as a durable
operation, and an error it raises fails the request.
Type: Callable[[RunContext[AgentDepsT]], Awaitable[str | CurrentStatePart | None]] | None Default: None
When True, a deferred capability loaded in the cleared messages stays loaded.
Its load is recorded again ahead of the kept messages. When False, a note names the capabilities that
were unloaded, so the model can load the ones it still needs.
Type: bool Default: True
Optional tokenizer for the token trigger and the span. When None, uses a ~4 characters-per-token heuristic.
Type: Callable[[str], int] | None Default: None
Stable capability ID: durable execution names the restate operation by it.
Type: str | None Default: 'reset_compaction'
@classmethod
def get_serialization_name(cls) -> str | None
Not spec-serializable: work_log is a live capability, and notice and restate are callables.
@async
def before_run(ctx: RunContext[AgentDepsT]) -> None
Reject a registration without a trigger, or with a work_log the agent doesn’t register under its id.
With another WorkLog, the notice would name a log that nothing writes to.
@async
def compact(
messages: list[ModelMessage],
ctx: RunContext[AgentDepsT],
) -> list[ModelMessage]
Clear all but the first request, the notice, pins, loaded state, the user’s later turns and the tail.
The notice is built here, not enqueued, so a use as a strategy gets it too. It checks the cleared tool calls against the work log, so it doesn’t promise the model results the log lacks.
@async
def before_model_request(
ctx: RunContext[AgentDepsT],
request_context: ModelRequestContext,
) -> ModelRequestContext
Reset when the history passes the trigger and the model has responded since the last reset.
What a reset did, handed to ResetCompaction.notice to write the text of the notice it leaves.
How many times the conversation has been reset, this reset included.
Type: int
Where the work log is, from its store’s locate: None for a store the agent can’t open, such as
InMemoryWorkLogStore, or when the conversation is not known.
The name the model sees for search_work_log.
Type: str
The name the model sees for read_work_log.
Type: str
Whether the work log records the model’s replies, as WorkLog.record_text sets.
Type: bool
Messages this reset removed.
Type: int
Whether the conversation’s first user request is still in it.
Type: bool
User prompts after the first request still in the conversation, besides one in the kept messages.
Type: int
Messages kept after the notice, at the end of the conversation.
Type: int
Tool calls kept with their results among those messages.
Type: int
Whether the work log lacks a tool call the conversation’s resets cleared, such as a call in history passed to
the run that the log never recorded, or a result passed in through DeferredToolResults. Unlike the other
fields, which cover this reset only, it covers every reset of the conversation: a call an earlier reset cleared is
still missing from the log. A denied call never ran and doesn’t count.
Type: bool Default: False
def default_reset_notice(notice: ResetNotice) -> str
The default text of the notice a reset leaves: that the conversation was cleared, and where the earlier work is.
It says the task continues and how many times the conversation has been cleared, names the work log and the tools that search and read it, with a first move: list the newest entries or search, then read only the entries needed. It asks the model to read a file again before editing it, since an entry shows the file as it was, and says what the reset kept. It leaves out the model’s replies when the work log doesn’t record them. When the log lacks some of the cleared tool calls, it says so, and that a call missing from the log may still have run.
Bases: AbstractCapability[AgentDepsT]
Give the model a compact_context tool to ask for a compaction when its task reaches a break.
Size-based triggers do not know where the task is: they can fire in the middle of a sub-task,
or not fire right after a phase whose output is no longer needed. The model often knows that
moment. This capability lets it say so, and runs strategy before the next model request of
the same run.
The tool compacts nothing itself. It records the request, and the compaction runs in the next
before_model_request, so the tool call and its return stay paired in the kept tail and the
model can see that it asked. A focus the model passes reaches a strategy that implements
SupportsFocus, and is ignored by one that does not.
It runs after the automatic compaction capabilities on the same agent, wherever it is listed.
When one of those has already compacted the history for the request, the model’s request is
dropped rather than compacting twice in one step, and does not count against max_per_run.
Under durable execution the strategy runs as this capability’s compact operation. Under
Temporal that is an activity, whose context omits tracer and capabilities, so a strategy
that reads them (RelevanceCompaction, or receipts=True on a summarizing or sliding-window
strategy) fails there.
The strategy to run when the model asks. Its compact is called directly, so its own trigger is bypassed.
Type: CompactionStrategy[AgentDepsT]
Refuse a request while the history is estimated at fewer tokens than this. None disables the check.
Type: int | None Default: field(default=None, kw_only=True)
Refuse requests once this many have been accepted in the run. None disables the check.
Type: int | None Default: field(default=None, kw_only=True)
Optional token counter for min_tokens and the span; defaults to the built-in text estimate.
Type: Callable[[str], int] | None Default: field(default=None, kw_only=True)
@async
def for_run(ctx: RunContext[AgentDepsT]) -> CompactOnRequest[AgentDepsT]
Return a copy with no pending request and no accepted requests counted.
CompactOnRequest[AgentDepsT]
def get_toolset() -> AgentToolset[AgentDepsT] | None
Register the compact_context tool, in the toolset shared with every per-run copy.
AgentToolset[AgentDepsT] | None
@async
def after_tool_execute(
ctx: RunContext[AgentDepsT],
*,
call: ToolCallPart,
tool_def: ToolDefinition,
args: ValidatedToolArgs,
result: Any,
) -> Any
Accept or refuse a compact_context call, answering with the reason when refused.
The decision is made here rather than in the tool function: under durable execution the tool can run in an activity that sees neither the message history nor this run’s state, while hooks run with the run itself.
@async
def before_model_request(
ctx: RunContext[AgentDepsT],
request_context: ModelRequestContext,
) -> ModelRequestContext
Run the strategy when the model asked for a compaction in the previous step.
Bases: AbstractCapability[AgentDepsT]
Give the model a prune_tool_result tool to replace a tool result it just received with a summary.
Rule-based clearing keeps the newest results, which is where an unexpectedly large or irrelevant
result sits right after it arrives. Whether a result is useless is a judgement the model can make
once it has read it. This capability lets it make that judgement, and replaces the result’s content
with placeholder followed by the model’s summary as soon as the call is accepted.
Only results from the step the model just answered can be pruned, so the edit lands at the end of
the history and the cached prefix before it is kept. The tool call stays paired with its result,
and the replacement persists in the run’s message history, as ClearToolResults does.
Token-based compaction triggers and ReportContextUsage anchor on the usage of the latest response,
which still counts the pruned result, so a prune lowers their estimates from the following response on.
Prefix of the content that replaces a pruned result; the model’s summary follows it.
Type: str Default: '[tool result pruned]'
def get_toolset() -> AgentToolset[AgentDepsT] | None
Register the prune_tool_result tool.
AgentToolset[AgentDepsT] | None
@async
def after_tool_execute(
ctx: RunContext[AgentDepsT],
*,
call: ToolCallPart,
tool_def: ToolDefinition,
args: ValidatedToolArgs,
result: Any,
) -> Any
Replace the result a prune_tool_result call names, or answer with the reason it was refused.
This runs in a hook rather than in the tool function: under durable execution the tool can run in an activity that sees neither the message history nor this run’s state.
Bases: AbstractCapability[AgentDepsT]
Warns the model when the run approaches configured limits.
Each warning is enqueued as a request-scoped
LimitWarningPart, in the application’s voice: the model sees it for the request it’s part of
only, and it stays in the message history, so the cached prefix and the model’s earlier
reasoning stay valid.
Older versions sent the warning as a user prompt marked with metadata instead. Those are stripped from the request when a history still holds them; a user prompt that quotes a warning is left alone, since they’re recognized by that metadata, never by their text.
Maximum allowed requests for the run.
Type: int | None Default: None
Maximum context-window size to warn against.
Type: int | None Default: None
Context limit as a fraction of the model’s real context window, resolved per request.
Use this instead of max_context_tokens when the same agent runs on models with
different windows. Mutually exclusive with max_context_tokens.
Type: float | None Default: field(default=None, kw_only=True)
Window override in tokens. None resolves it from the request’s model.
Unlike fallback_context_window, this applies whether or not resolution succeeds. Reach
for it when the registry is confidently wrong: a beta- or tier-gated window it records as
the maximum, or a self-hosted endpoint whose model id describes someone else’s
deployment. Only consulted alongside max_context_fraction.
Type: int | None Default: field(default=None, kw_only=True)
Window assumed when the request’s model is not in the pricing registry.
Only consulted alongside max_context_fraction. Supply the real number for a deployment
the registry cannot resolve.
Type: int Default: field(default=DEFAULT_CONTEXT_WINDOW, kw_only=True)
Maximum cumulative run token budget to warn against.
Type: int | None Default: None
Which limits should emit warnings. Defaults to all configured limits.
Type: list[WarningKind] | None Default: None
Fraction of a limit at which warnings begin (between 0 and 1).
Type: float Default: 0.7
Remaining request count at which iteration warnings become CRITICAL.
Type: int Default: 3
@async
def before_model_request(
ctx: RunContext[AgentDepsT],
request_context: ModelRequestContext,
) -> ModelRequestContext
Strip user-prompt warnings older versions sent, then enqueue a warning if a threshold is crossed.
Enqueued from before_model_request, the warning goes into this request and into the run’s
history, as a ModelRequest of its own that’s sent merged into the request it follows.
Bases: AbstractCapability[AgentDepsT]
Report context usage to the application before each model request.
A compaction strategy knows when to act but says nothing about how close the run is to the limit, so an application that wants to show “context: 73%” has to re-count the history itself and guess the denominator. This capability does neither: it reuses the same estimator the strategies use and the model’s real context window.
It only observes — it never edits the history.
Order matters: register it after a compaction capability to see the compacted history, or before it to see what triggered the compaction. After a preceding compactor rewrites anchored history, the reading subtracts that compactor’s heuristic reclaim while retaining the anchor’s fixed provider overhead.
Deprecated callback with a fresh reading before every model request.
Subscribe to ContextUsageMeasuredEvent instead. A coroutine function is awaited and an exception
raised here propagates and fails the run.
Type: Callable[[ContextUsage], None | Awaitable[None]] | None Default: None
Window override in tokens. None resolves it from the request’s model.
Type: int | None Default: None
Window assumed when the request’s model is not in the pricing registry.
Type: int Default: DEFAULT_CONTEXT_WINDOW
Optional tokenizer, matching the one your compaction strategy uses.
Type: Callable[[str], int] | None Default: None
@async
def before_run(ctx: RunContext[AgentDepsT]) -> None
Reset the request correction even when the caller reuses a run ID.
@async
def before_model_request(
ctx: RunContext[AgentDepsT],
request_context: ModelRequestContext,
) -> ModelRequestContext
Measure the pending history, emit it, and invoke the compatibility callback.
A single reading of how full the context is.
Estimated tokens in the message history about to be sent.
Counted by estimate_context_tokens: the provider-reported usage of the most recent model
response (tool schemas included) plus an estimate of messages and newly revealed tool schemas
added since. With no reported usage, message text falls back to the character heuristic;
schemas named by availability deltas are still estimated from the pending request
parameters, but other tool schemas remain outside that heuristic.
Type: int
Context window the reading is measured against.
Type: int
Whether window_tokens is the model’s real window or the fallback.
A gauge can render an unresolved window differently — the percentage is a guess when the model is not in the pricing registry.
Type: bool
used_tokens as a fraction of the window.
Type: float
def pin(content: str, *, source: PinSource = 'user') -> UserPromptPart
Mark content so every shipped compaction strategy preserves it.
The returned UserPromptPart can be placed in a ModelRequest in the run’s message
history (e.g. by a capability or by the user); compaction keeps it verbatim. A 'user' pin
reaches the model as the user’s own words. Any other source is framed as
<pinned source="..."> data, so the model doesn’t read a tool’s or its own text as the user’s.
Who wrote pinned content: the user, a tool, or the model.
Default: Literal['user', 'tool', 'model']
def is_pinned(part: object) -> bool
Return True if part carries the pin metadata marker.
def reinject_pinned(
original: Sequence[ModelMessage],
compacted: list[ModelMessage],
*,
protected_tail: int = 0,
insert_at: int | None = None,
) -> list[ModelMessage]
Re-inject any pinned parts from original that compacted dropped.
Pinned parts already present in compacted are left where they are; missing ones are
gathered into a single ModelRequest placed right after any leading system/summary
messages, so they sit near the top of the surviving history. A no-op when original has
no pins or all pins survived, so it is always safe to call. protected_tail bounds
insertion to the prefix before that many unchanged trailing messages. insert_at places the
recovered pins at that index instead, for a strategy whose leading messages must stay as they were.
Bases: Protocol
A capability that can hand out a handle for its persisted run history.
Any capability implementing this method is discovered from RunContext.capabilities; the
first non-None handle is used. StepPersistence implements it by returning its run_id.