Add a `ModelFallback` capability, a per-attempt `prepare_model_request` hook, and `RetryModelRequest`
[!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:
- Part of #6575 (fallback as a capability), #5347 (
prepare_model_requesthook), #9335 (model request reliability) - Groundwork for #7453 (compaction across a provider switch) and #9334 (
RetryOnModelErrors) - Related: #4882, #4140, #4006, #3023, #7139, #4221, #4538 / #4611 (
context_window), #7018 (fallback span attribution), #9580 (Temporal model errors)
Decisions for sign-off
- New public API:
RetryModelRequest;- the
prepare_model_requesthook, which runs per attempt and doesn't persist to history; ModelRequestContext.attempt;- the
ModelFallbackcapability, withfallback_ontaking the same forms asFallbackModel's.
FallbackModelgets no deprecation warning yet. The docs makeModelFallbackthe way to fall back in an agent, and keepFallbackModelfor direct model requests and APIs that take a model rather than an agent, such asApprovalReviewer, as withInstrumentedModelnext to theInstrumentationcapability. A runtime deprecation can follow once those cases have a capability path.RunContext.modelis unchanged. A hook readsrequest_context.modelto see the model serving the attempt.- Limits:
request_limitcounts steps, not attempts;- a step is capped at 100 attempts;
- a rejected response's usage counts towards token and cost limits.
- The behavior changes below.
- Docs choices:
ApprovalReviewer's low-confidence example stays onFallbackModel, since it takes a model;- the native web-fetch fallback example stays a realistic recipe rather than a
FunctionModelmock.
Why
FallbackModel sits in ctx.deps.model, so it's the model every hook reads, and it can't answer the questions hooks ask:
| Read | Under FallbackModel |
|---|---|
model.profile | raises 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.model | the 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) orafter_model_request(reject the response). - Or raise it from
prepare_model_requestto switch model before anything is sent. - Raising it from
before_model_requestorwrap_model_request, which run before any attempt, is aUserError. - With no model, the same model runs again; that is the primitive for #9334.
- Raise it from
prepare_model_requestruns per attempt and only shapes the request that goes on the wire; its changes are not persisted to history.before_model_requeststays once per step, so history processors don't start running N times. Instruction history, including loaded capabilities' instructions, andModelSettingsDeltaParts are recorded once per step, as the before-chain left them. When aprepare_model_requesthook 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.attemptis 1-based within the step and survivesdataclasses.replace(). It crosses the durable boundary inModelRequestContextProjection, so a durable model-request hook reads it as it would in-process. The loop is capped at 100 attempts and raisesUserErrorbeyond that.- Usage:
usage.requestscounts the step once, sorequest_limitstays 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. ModelFallbackcapability: the chain is[the model selected for the step, *the capability's models], so it composes with the agent's model,run(model=...)andSelectModel.- 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 outerafter_model_requesthooks 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, whateverfallback_onsays.
FallbackModelshares one implementation (pydantic_ai/_fallback.py) and keeps working fordirectand 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), andRetryModelRequestfromafter_model_requeston a streamed request raisesUserError. A run stopped while a stream is being opened records the step as aninterruptedresponse with its billed usage, as one stopped after the stream opened does. - Suspended responses:
ModelFallbackpins a suspended response to the candidate that served it, under its ownfallback_candidatekey so aFallbackModelcandidate 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 raisesUserError.FallbackModelnow applies response handlers to its pinned continuations too (#11085, ported to the shared core). - Batching (#10672):
get_wrapper_modelis applied to the modelprepare_model_requestpicked 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 answercontinuation_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:
FallbackModelcancels 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_cancelledfor the streamed case). - Durable execution: durability repairs the model in
prepare_model_requesttoo, and orders itself insideModelFallback, so every attempt runs as a durable model operation. With #9580, model errors reach Temporal workflow code as their own types, so the defaultfallback_onworks under Temporal; the end-to-end tests use it. RunContext.modelis unchanged (decided):request_context.modelnames the serving model.
Behavior changes
-
Durability capabilities accept an agent without a model when a capability can supply one (it overrides
get_model), such asModelFallback,SelectModelor one of your own. An agent with neither still gets the sameUserError. -
A
ModelFallbackcandidate doesn't inherit the step model's ownsettings, such as itsmax_retries. Settings from the agent, capabilities or run, and whatwrap_model_request/before_model_requesthooks change or remove, apply to every candidate, as withFallbackModel. 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_erroris 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. -
FallbackModelfalls back on a stream error raised before the first event (#10386's change, here via the shared core). -
FallbackModelkeeps the usage of the responses it rejected when its request then ends with a cancellation, a timeout or an errorfallback_ondoesn't cover: it carries those attempts on the error (carry_attempts), and the agent counts them. AFallbackModelthat another model calls only reaches the run's usage this way when its error escapes the outer model. -
FallbackModelcancels 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, afterprepare_model_request, instead of once per request afterbefore_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. AFallbackModel's spans keepResponse rejected by afallback_onresponse handler. -
A pickled
ModelAPIError(as DBOS records a failed step) keeps the attributes Pydantic AI attaches to it, such asFallbackModel's carried attempts, andModelRequestTimeoutpickles its state. -
A
RetryModelRequestraised 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_errorandHooks.on_model_request_errorre-raise the newRetryModelRequeststraight away instead of handing it to the next capability or callback as its error.ModelRetryis 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 abefore_model_requesthook 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 (likeAdvisor'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_errorhooks 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) andretry_after, plus richerModelRequestAttemptfields 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
TieredCompactionand other model-agnostic strategies, and anhonors_compactionadapter declaration so attempt-level estimators can account for native compaction. - Skipping candidates whose
ModelProfile.context_windowdoesn'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_messagesinto a built-inRequestPreparationcapability (#5347). XSearch's andImageGeneration's subagent fallback when a native tool factory returnsNonemay 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) toprepare_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 aModelFallback(or anything else an agent can do) applies there too, andFallbackModelcan 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 evaluatingfallback_on.FallbackChain: whetherfallback_onmoves on from an error or response, what the chain moved on from, theFallbackExceptionGroupan exhausted chain raises, and the warning for response handlers on a streamed request (#10066, now emitted byModelFallbacktoo).AttemptLog: theModelRequestAttemptrecords and back-dated attempt spans, built on #8745'sfailed_attempt()andrecord_attempt_span().request_stream_until_first_event: opening a candidate's stream and waiting for its first event (#10386's implementation, moved here frommodels/fallback.py), under the candidate'srequest_timeoutdeadline (#10072), which the agent's primed stream passes too. EachModelFallbackcandidate gets arequest_timeoutdeadline of its own, as eachFallbackModelcandidate does, and aModelRequestTimeoutfalls back by default; a run'sRunTimedOutdoesn't.- Continuation pinning (
stamp_continuation_pin,continuation_pin).
What each keeps:
FallbackModelwalks its candidates inside oneModel.request[_stream]call, so it also works for direct requests and a standaloneModel. It rewinds its own pinned continuations, and refreshes thechatspan it runs under.ModelFallbackdecides which candidate comes next (skipping models already attempted this step, and routing a pinned continuation) and raisesRetryModelRequest. The agent's attempt loop makes the attempt, primes its stream withrequest_stream_until_first_event, and keeps theAttemptLogfor any capability that raisesRetryModelRequest.
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 raisesRetryModelRequestgets the same telemetry (including #9334's futureRetryOnModelErrors). An attempt is recorded when a hook moves on from it withRetryModelRequest(fromon_model_request_errororafter_model_request), or ends the step with aFallbackExceptionGroup. A switch fromprepare_model_requestsent nothing, so it isn't recorded. - Records. Each failed attempt is on the answering response's
failed_attempts, or onFallbackExceptionGroup.attemptswhen every model fails. AFallbackModelcandidate's own attempts are flattened in, and a group aFallbackModelraised 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 ofchat(record_attempt_span(), shared withFallbackModelthrough a newrecord_failed_attempt()helper). chatspan (#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 underFallbackModel. When every model fails, it carries no response and is named after the last model attempted (aFallbackModel's keepsfallback:...).- 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_usagenever sees it again._usage_responsesstill lists every billed response (the accepted one without the attached records), soSpendLimitscharges each rejected response once, also with #9792'sfailed_attempts/_usage_attemptsaccrual. Its totals matchFallbackModel's, and itsSpendRecordedEventhasfailed_attempt=Truetoo:SpendLimitschecks 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,UsageLimitExceededis raised from the group, as underFallbackModel. - 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.mdpresentsModelFallbackas 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 attemptspans,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.
- when to fall back, including the warning that a response handler alone replaces the default
docs/models/overview.mdleads its fallback section withModelFallback, and keepsFallbackModelas the path for direct and standalone use.- The agent recipes in
production.md,retries.md,models/decision.md,harness/trajectory-judge.mdandcapabilities/custom.mduseModelFallback. - 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.mdseparates the agent's attempts,FallbackModel's own candidates, and SDK and transport attempts.timeouts.md,temporal.mdandharness/spend.mdcover the capability next toFallbackModel.
Tests
tests/test_model_request_attempts.pycovers the attempt loop:prepare_model_requestruns per attempt whilebefore_model_requestruns once;RetryModelRequestfrom 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.pycovers #6575's must-preserve list, and runs the same chains under the capability and underFallbackModelto compare:RunUsage(tokens, cost, requests) andfailed_attemptsfor a chain with an error and a rejected response;FallbackExceptionGroup.attemptsand limits when every model fails;- span trees, for non-streamed, exhausted and streamed chains;
SpendLimitstotals (intests/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_messagesand 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;
ModelFallbackwithBatchModelRequests: 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=...)andSelectModelprecedence.
tests/test_capability_wrapper_model.py:get_wrapper_modelis applied to, and entered around, each attempt's own call, the failed primary's and the fallback's.tests/models/test_fallback.pyandtests/test_run_timeout.py:FallbackModelkeeps rejected usage on cancellation, timeout and an uncovered error, for aFallbackModelwrapped or called by another model too, and cancels a pinned job once; the cases that apply toModelFallbackrun 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 gainswith_options, whichAnthropicModelcalls to setmax_retries(#10068). Without it, the FunctionModel prefix check fails for a request carryingmax_retries, which these tests are the first to send.- Durable execution: a recording-durability test, the
attemptprojection, 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