Add a `ModelFallback` capability, a per-attempt `prepare_model_request` hook, and `RetryModelRequest`

Merged
DO
1mo ago
+7780-743

[!IMPORTANT]
#10672 (BatchModelRequests and the get_wrapper_model hook), #7053, #8745, #9792, #10386, #11068, #11081, #11085, #11090 and #11413 (usage limits checked after the response is committed) have merged and are reconciled here.

Stacked on this PR:

  • #11330: sticky fallback.
  • #11582: first_event_timeout.
  • #11679: ModelFallback in agent specs, which closes #9896.
  • The compaction stack: #11454, the per-attempt compact_history hook, and #11581, NativeCompaction on top of it.

Decisions for sign-off

  1. New public API:
    • RetryModelRequest;
    • the prepare_model_request hook, which runs per attempt and doesn't persist to history;
    • ModelRequestContext.attempt;
    • the ModelFallback capability, with fallback_on taking the same forms as FallbackModel's.
  2. FallbackModel gets no deprecation warning yet. The docs make ModelFallback the way to fall back in an agent, and keep FallbackModel for direct model requests and APIs that take a model rather than an agent, such as ApprovalReviewer, as with InstrumentedModel next to the Instrumentation capability. A runtime deprecation can follow once those cases have a capability path.
  3. RunContext.model is unchanged. A hook reads request_context.model to see the model serving the attempt.
  4. Limits:
    • request_limit counts steps, not attempts;
    • a step is capped at 100 attempts;
    • a rejected response's usage counts towards token and cost limits.
  5. The behavior changes below.
  6. Docs choices:
    • ApprovalReviewer's low-confidence example stays on FallbackModel, since it takes a model;
    • the native web-fetch fallback example stays a realistic recipe rather than a FunctionModel mock.

Why

FallbackModel sits in ctx.deps.model, so it's the model every hook reads, and it can't answer the questions hooks ask:

ReadUnder FallbackModel
model.profileraises NotImplementedError
model.count_tokens(...)raises NotImplementedError, so UsageLimits(count_tokens_before_request=True) doesn't work
model.model_id'fallback:a,b', which matches no genai-prices entry
RunContext.modelthe outermost wrapper, read before any candidate has been picked

before_model_request fires once per step, before it's known which candidate will serve the request, so no hook can make a per-model decision. Compaction needs exactly that (#7453).

Design

wrap_model_request                          once per step
  before_model_request                      once per step (model may still change)
  for each attempt:
    prepare_model_request                   NEW: request_context.model is the model about to serve it
    get_wrapper_model                       per attempt, entered around the attempt's call
    prepare_messages / reveal state / count_tokens / usage-limit checks
    model request
      on error   -> on_model_request_error  ─┐
      on success -> after_model_request    ──┴─ may raise RetryModelRequest -> next attempt
  • No new lifecycle stage. An attempt is something the core tracks, and a capability asks for another one by raising RetryModelRequest(model=None | Model | str).
    • Raise it from on_model_request_error (the attempt raised) or after_model_request (reject the response).
    • Or raise it from prepare_model_request to switch model before anything is sent.
    • Raising it from before_model_request or wrap_model_request, which run before any attempt, is a UserError.
    • With no model, the same model runs again; that is the primitive for #9334.
  • prepare_model_request runs per attempt and only shapes the request that goes on the wire; its changes are not persisted to history. before_model_request stays once per step, so history processors don't start running N times. Instruction history, including loaded capabilities' instructions, and ModelSettingsDeltaParts are recorded once per step, as the before-chain left them. When a prepare_model_request hook exists, each attempt gets its own copies of the tool definitions, the native tools and the native-output schema, so an in-place edit doesn't reach the next attempt or the agent's definitions.
  • ModelRequestContext.attempt is 1-based within the step and survives dataclasses.replace(). It crosses the durable boundary in ModelRequestContextProjection, so a durable model-request hook reads it as it would in-process. The loop is capped at 100 attempts and raises UserError beyond that.
  • Usage: usage.requests counts the step once, so request_limit stays a bound on agent steps. A rejected response stays out of history, but its tokens and cost are recorded through #7053's provider-boundary ledger and checked against token and cost limits before the next attempt.
  • ModelFallback capability: the chain is [the model selected for the step, *the capability's models], so it composes with the agent's model, run(model=...) and SelectModel.
    • When the agent has no model, its first candidate is only a stand-in default, which any other selection outranks.
    • It is positioned innermost, so outer after_model_request hooks and instrumentation only see the accepted response.
    • Every attempted model is noted in prepare_model_request, so a model another capability already tried isn't tried again. That includes a candidate given as a string that resolves to a model already attempted, like an alias of the step's own model.
    • It never falls back from the run's own UsageLimitExceeded, whatever fallback_on says.
  • FallbackModel shares one implementation (pydantic_ai/_fallback.py) and keeps working for direct and standalone use. No deprecation warning (decided); the docs point to the capability.
  • Streamed requests: the stream is opened, and its first event pulled (then replayed), before it's handed over (in the consuming task, which also closes it). A first segment that's suspended without any output doesn't count: priming carries on into its continuation, so a continuation that fails before any output still falls back. A failure to open, or one the provider reports before any output (#10123, #10364), reaches on_model_request_error. This only happens when such a hook exists; otherwise streams still open lazily. Mid-stream failures still propagate (#4140), and RetryModelRequest from after_model_request on a streamed request raises UserError. A run stopped while a stream is being opened records the step as an interrupted response with its billed usage, as one stopped after the stream opened does.
  • Suspended responses: ModelFallback pins a suspended response to the candidate that served it, under its own fallback_candidate key so a FallbackModel candidate keeps its inner pin. On resume, it routes the continuation to that candidate. If the continuation fails or is rejected, the suspended response is dropped and the turn moves on to the model after the pinned one, as it would have in the run that started the job, rather than starting the chain over. A pin to an unknown model raises UserError. FallbackModel now applies response handlers to its pinned continuations too (#11085, ported to the shared core).
  • Batching (#10672): get_wrapper_model is applied to the model prepare_model_request picked for each attempt, and the wrapper is entered around that attempt's request, stream or cancellation only, so a fallback candidate goes into a batch on its own model. Under durable execution the workflow side wraps each attempt's model to answer continuation_delay, and the unit wraps the model it rebuilds. The step settles the pending response of the attempt that answers, as #10672 does a request's. A pending response a hook rejected is cancelled when it's rejected (for a batch request, withdrawn from its batch, which is cancelled once nothing else waits on it), so it's settled exactly once.
  • Cancelling a job once: FallbackModel cancels a pinned job before moving on to its chain and marks the error its chain then raises, so the continuation loop that error reaches doesn't cancel the job again (alongside #11090's _job_cancelled for the streamed case).
  • Durable execution: durability repairs the model in prepare_model_request too, and orders itself inside ModelFallback, so every attempt runs as a durable model operation. With #9580, model errors reach Temporal workflow code as their own types, so the default fallback_on works under Temporal; the end-to-end tests use it.
  • RunContext.model is unchanged (decided): request_context.model names the serving model.

Behavior changes

  • Durability capabilities accept an agent without a model when a capability can supply one (it overrides get_model), such as ModelFallback, SelectModel or one of your own. An agent with neither still gets the same UserError.

  • A ModelFallback candidate doesn't inherit the step model's own settings, such as its max_retries. Settings from the agent, capabilities or run, and what wrap_model_request/before_model_request hooks change or remove, apply to every candidate, as with FallbackModel. A hook that sets a value equal to what the step already resolved to counts as leaving it unchanged, so another candidate uses its own value.

  • on_model_request_error is called for a streamed request that fails to open, or that fails before any output, when such a hook exists. Accepted as a fix: open failures reached the hook before #6303 made opening lazy.

  • FallbackModel falls back on a stream error raised before the first event (#10386's change, here via the shared core).

  • FallbackModel keeps the usage of the responses it rejected when its request then ends with a cancellation, a timeout or an error fallback_on doesn't cover: it carries those attempts on the error (carry_attempts), and the agent counts them. A FallbackModel that another model calls only reaches the run's usage this way when its error escapes the outer model.

  • FallbackModel cancels a failed pinned continuation's job once, not again from the continuation loop, when its chain fails too.

  • get_wrapper_model (#10672) is called for every attempt, after prepare_model_request, instead of once per request after before_model_request.

  • In the agent's attempt loop, the span of a rejected attempt has the status Response rejected, since any capability can reject one there. A FallbackModel's spans keep Response rejected by a fallback_on response handler.

  • A pickled ModelAPIError (as DBOS records a failed step) keeps the attributes Pydantic AI attaches to it, such as FallbackModel's carried attempts, and ModelRequestTimeout pickles its state.

  • A RetryModelRequest raised from a capability hook that runs as a durable operation reroutes the request under Temporal too, naming the model by string.

  • CombinedCapability.on_model_request_error and Hooks.on_model_request_error re-raise the new RetryModelRequest straight away instead of handing it to the next capability or callback as its error. ModelRetry is still handed on, as before; whether it should short-circuit too is a separate question for its own issue.

  • Tool calls in a response are checked against the history of the model that served it, not the step's model: ModelFallback's candidate, or the model a before_model_request hook swapped in. This decides where the window of evidence for the response's tool calls starts after a compaction (#11504).

  • Native tool factories run again, with that model as ctx.model, for an attempt at a model other than the step's, so a provider-specific tool (like Advisor's) doesn't reach a candidate that can't use it. The first attempt is unchanged.

  • Whether a streamed request is primed, and whether on_model_request_error hooks are dispatched, is decided per request, so a capability can handle request errors for some models only. Nothing changes for existing capabilities.

  • Under durable execution, a streamed request that fails after its output reached the event handler raises, like it does outside one, instead of falling back; the usage of what it produced is counted.

Follow-ups

  • Same-model retry with backoff on RetryModelRequest (#9334), using the error categories (#9354, #11081) and retry_after, plus richer ModelRequestAttempt fields such as the error's category.
  • Compaction per candidate (#7453): #11454 and #11581, stacked on this PR, move compaction to the attempt. Still to do: the Harness TieredCompaction and other model-agnostic strategies, and an honors_compaction adapter declaration so attempt-level estimators can account for native compaction.
  • Skipping candidates whose ModelProfile.context_window doesn't fit the request (#4538 / #4611, #7139).
  • Falling back after a stream has produced output, by rejecting a streamed response.
  • Resolving string candidates, or importing their provider module, before the event loop, so the first fallback to a provider that hasn't been imported yet doesn't import it inside the loop.
  • Moving Model.prepare_request/prepare_messages into a built-in RequestPreparation capability (#5347).
  • XSearch's and ImageGeneration's subagent fallback when a native tool factory returns None may still decide by the step's model.
  • Temporal re-streams a failed stream's output to the handler when its activity retry policy retries it (with or without fallback).
  • Moving ImageGeneration's dropped-settings notice (_routed_profiles, #9477) to prepare_model_request, so it only warns for the candidate that runs.
  • Letting capabilities that take a model, like ApprovalReviewer, take an agent as well, so a ModelFallback (or anything else an agent can do) applies there too, and FallbackModel can then be deprecated.

Shared core

Like InstrumentedModel and the Instrumentation capability, FallbackModel and ModelFallback share one core, in pydantic_ai/_fallback.py, so a fix lands once:

  • FallbackPredicates: parsing and evaluating fallback_on.
  • FallbackChain: whether fallback_on moves on from an error or response, what the chain moved on from, the FallbackExceptionGroup an exhausted chain raises, and the warning for response handlers on a streamed request (#10066, now emitted by ModelFallback too).
  • AttemptLog: the ModelRequestAttempt records and back-dated attempt spans, built on #8745's failed_attempt() and record_attempt_span().
  • request_stream_until_first_event: opening a candidate's stream and waiting for its first event (#10386's implementation, moved here from models/fallback.py), under the candidate's request_timeout deadline (#10072), which the agent's primed stream passes too. Each ModelFallback candidate gets a request_timeout deadline of its own, as each FallbackModel candidate does, and a ModelRequestTimeout falls back by default; a run's RunTimedOut doesn't.
  • Continuation pinning (stamp_continuation_pin, continuation_pin).

What each keeps:

  • FallbackModel walks its candidates inside one Model.request[_stream] call, so it also works for direct requests and a standalone Model. It rewinds its own pinned continuations, and refreshes the chat span it runs under.
  • ModelFallback decides which candidate comes next (skipping models already attempted this step, and routing a pinned continuation) and raises RetryModelRequest. The agent's attempt loop makes the attempt, primes its stream with request_stream_until_first_event, and keeps the AttemptLog for any capability that raises RetryModelRequest.

The loops themselves stay separate: one runs inside a model request, the other is the agent's per-attempt hook lifecycle.

Telemetry and usage

Failed attempts are recorded with #8745's ModelRequestAttempt and its helpers in _model_request_attempts.py, so the capability and FallbackModel produce the same records and spans:

  • Who records. The agent's attempt loop, not ModelFallback, so any capability that raises RetryModelRequest gets the same telemetry (including #9334's future RetryOnModelErrors). An attempt is recorded when a hook moves on from it with RetryModelRequest (from on_model_request_error or after_model_request), or ends the step with a FallbackExceptionGroup. A switch from prepare_model_request sent nothing, so it isn't recorded.
  • Records. Each failed attempt is on the answering response's failed_attempts, or on FallbackExceptionGroup.attempts when every model fails. A FallbackModel candidate's own attempts are flattened in, and a group a FallbackModel raised keeps its own attempts. A recovered response that is then rejected was never billed, so its attempt records the error it recovered from. A rejected response that resumed a suspended one records only the usage this run billed beyond it.
  • Spans. Each failed attempt gets a back-dated model request attempt <model> ERROR child span of chat (record_attempt_span(), shared with FallbackModel through a new record_failed_attempt() helper).
  • chat span (#7018). It is renamed and re-described for each attempt, so it names the model that answered. It reports only that response's usage: a rejected response's usage is on its attempt span, as under FallbackModel. When every model fails, it carries no response and is named after the last model attempted (a FallbackModel's keeps fallback:...).
  • Usage is counted once. A rejected response's usage is committed at the provider boundary (#7053) when it arrives, before any hook judges it. Its attempt record is attached to the answering response afterwards, so _record_attempts_usage never sees it again. _usage_responses still lists every billed response (the accepted one without the attached records), so SpendLimits charges each rejected response once, also with #9792's failed_attempts/_usage_attempts accrual. Its totals match FallbackModel's, and its SpendRecordedEvent has failed_attempt=True too: SpendLimits checks the request context's rejected responses (_rejected_usage_responses). A group the capability raises is never passed to _record_attempts_usage, which only reads a group the model raised. Token and cost limits are still checked before each attempt. When every model fails and the rejected responses exceed a limit, UsageLimitExceeded is raised from the group, as under FallbackModel.
  • Stopping early. The billed segments of a continued response are recorded however an attempt ends, cancellation and timeout included, in one branch as #11068 does for a single request.

Docs

  • docs/capabilities/model-fallback.md presents ModelFallback as the way to fall back in an agent. It covers:
    • when to fall back, including the warning that a response handler alone replaces the default (ModelAPIError,);
    • how attempts work, failed attempts and telemetry (model request attempt spans, gen_ai.request.model, pydantic_ai.model_request.attempt), and streaming (which entry points stream);
    • suspended responses, request deadlines, batching, and durable execution (each attempt is its own Temporal activity, and activity retries run before fallback_on);
    • migrating from FallbackModel: the support stance, a before/after example, what carries over, and what only the capability does.
  • docs/models/overview.md leads its fallback section with ModelFallback, and keeps FallbackModel as the path for direct and standalone use.
  • The agent recipes in production.md, retries.md, models/decision.md, harness/trajectory-judge.md and capabilities/custom.md use ModelFallback.
  • The capability is listed in:
    • the capabilities table and navigation;
    • the front page;
    • the Harness index and README;
    • the agent skills, including their LangChain and Deep Agents mappings.
  • retries.md separates the agent's attempts, FallbackModel's own candidates, and SDK and transport attempts. timeouts.md, temporal.md and harness/spend.md cover the capability next to FallbackModel.

Tests

  • tests/test_model_request_attempts.py covers the attempt loop:
    • prepare_model_request runs per attempt while before_model_request runs once;
    • RetryModelRequest from each hook, with and without a model;
    • switching models before sending;
    • the attempt ceiling;
    • control flow is never handed to an outer error hook;
    • streamed open failures that are recovered, retried with ModelRetry, or never iterated.
  • tests/test_capability_model_fallback.py covers #6575's must-preserve list, and runs the same chains under the capability and under FallbackModel to compare:
    • RunUsage (tokens, cost, requests) and failed_attempts for a chain with an error and a rejected response;
    • FallbackExceptionGroup.attempts and limits when every model fails;
    • span trees, for non-streamed, exhausted and streamed chains;
    • SpendLimits totals (in tests/harness/spend/test_spend.py), answered and exhausted;
    • exception- and response-based fallback, including async predicates, and FallbackExceptionGroup;
    • stream-opening fallback, including a continuation that fails after a silent suspended segment, and a run stopped while a stream opens;
    • pinning, moving on past a failed pinned continuation, and cancellation of the abandoned job;
    • per-candidate prepare_messages and token counting, and per-attempt copies of the output schema and native tools;
    • aliases of an attempted model, and the run's own usage limit;
    • usage kept on cancellation and timeout, and a rejected resumed continuation's usage;
    • ModelFallback with BatchModelRequests: a failed primary batch moves into a batch on the fallback, within a run and across runs resumed from a pending response; rejected pending responses are cancelled, or withdrawn from their batch;
    • model lifecycle;
    • ordering against other capabilities;
    • usage and token limits;
    • run(model=...) and SelectModel precedence.
  • tests/test_capability_wrapper_model.py: get_wrapper_model is applied to, and entered around, each attempt's own call, the failed primary's and the fallback's.
  • tests/models/test_fallback.py and tests/test_run_timeout.py: FallbackModel keeps rejected usage on cancellation, timeout and an uncovered error, for a FallbackModel wrapped or called by another model too, and cancels a pinned job once; the cases that apply to ModelFallback run for it too.
  • tests/models/test_model_settings_delta.py: a candidate of the same or another provider (Anthropic and OpenAI Responses, with or without a mid-conversation channel) sends a recorded thinking-effort change exactly as it does serving the request on its own.
  • tests/function_model_prefix.py: main's stand-in Anthropic client gains with_options, which AnthropicModel calls to set max_retries (#10068). Without it, the FunctionModel prefix check fails for a request carrying max_retries, which these tests are the first to send.
  • Durable execution: a recording-durability test, the attempt projection, and Temporal end-to-end runs in which each attempt gets its own activity, including a fallback from a failed batch into a batch on the fallback model.

Checklist

  • Any AI generated code has been reviewed line-by-line by the human PR author, who stands by it.
  • No breaking changes in accordance with the version policy.
  • Any permitted compatibility impact has a label, warning, migration, release note, and exact API-check waiver. (No API-check waiver needed.)
  • PR title is fit for the release changelog.

🤖 Generated with Claude Code