Add `RetryOnModelErrors` capability to retry the same model on transient model API errors
Adds a core RetryOnModelErrors capability. When a request fails with an error that waiting may fix, it attempts the same model again within the request step, through the attempt loop from #9348. It is separate from ModelFallback: retrying sends the request to the same model again, falling back sends it to a different model. The two compose, and the docs explain how and when to use which.
agent = Agent('openai:...', capabilities=[RetryOnModelErrors(max_attempts=4), ModelFallback('anthropic:...')])
What it does
- What it retries.
retry_ondecides, in the same forms asfallback_on: exception types, sync or async exception handlers, response handlers, or a list mixing them. The predicate parsing is shared withModelFallback, not copied. - Default
retry_on:ModelRateLimitError,ModelUnavailableError(includingModelOverloadedError),ModelServerError, andModelConnectionError(includingModelTimeoutError). It's exported aspydantic_ai.capabilities.TRANSIENT_MODEL_ERRORS, the actual default, so applications can extend it (retry_on=(*TRANSIENT_MODEL_ERRORS, MyError)) or check an error withisinstance(error, TRANSIENT_MODEL_ERRORS). - Never retried:
- an
x-should-retry: falseheader (ModelHTTPError.provider_retry_hint is False).ModelFallbackcan still move on to another model. UsageLimitExceeded.- non-default categories unless
retry_onnames them.
- an
- Waits use the error's
retry_after. Without one, the wait is exponential backoff frominitial_delay(doubling, capped atmax_delay), with up to half of it taken off as jitter.- The jitter is derived from
run_id, step and attempt, not drawn at random, so a replay waits the same delay. - Waits go through
_agent_graph_sleep: a durable timer on Temporal,DBOS.sleepon DBOS, and a plain sleep on Prefect (#11178). - The request isn't retried, and the error is raised, when the wait would be longer than
max_delayor would end after the request deadline or the run deadline. That letsModelFallbackmove on while there is still time.
- The jitter is derived from
- Retry budget.
max_attemptscounts consecutive attempts at one model within a step, whichever capability asked for each attempt. Wrappers such as durable models are unwrapped before comparing.- With
ModelFallback, every model gets its own budget, whichever order the two capabilities are listed in.RetryOnModelErrorsisinnermostandwrapped_by=(ModelFallback,), so it judges each failure first. - Two
RetryOnModelErrorsinstances count the same attempts.
- With
- Attempt records.
ModelRequestAttemptgets two new defaulted fields,kind: Literal['retry', 'fallback'] = 'fallback'andretry_after: float | None = None.- The core sets
kind='retry'for any hook that raisesRetryModelRequest()without a model. - Retries and fallbacks share one ordered
failed_attemptslist. - Attempts count towards token and cost limits, but not towards
request_limit.
- The core sets
- Streaming. A stream is retried only if it fails before its first event has reached the consumer.
Decisions for sign-off
-
retry_ontakesfallback_on's forms, including response handlers. A response handler rejects a non-streamed response and the same model is attempted again. Whenmax_attemptsis used up, the response is accepted, so an outerModelFallbackcan judge it. -
Default categories are the four transient ones above.
ModelRequestTimeout(a request whose whole deadline ran out) is not retried by default.- Neither is a plain uncategorized
ModelAPIError, nor any rejection or quota error. x-should-retry: truedoes not overrideretry_on.
-
Waiting. A
retry_afterlonger thanmax_delaygives up rather than waiting, on the reasoning that a provider asking for minutes usually means a quota reset. The defaults aremax_attempts=3,initial_delay=1,max_delay=30. -
Request deadline covers all retries of a model. On main,
request_timeoutis started for each attempt the agent makes, which until now meant each fallback model. Following #9333 ("one logical request to one concrete model: every attempt at every layer"):- each retry is sent with whatever is left of the deadline the first attempt at that model started, and a wait that would end after it isn't made;
- a model
ModelFallbackmoves to still gets a fresh deadline.
This is done inside the capability, not in the core. It measures time on
anyio.current_time(), the same clockRequestDeadlineuses, which Temporal replays. The module is added to the workflow-side determinism check, with a pragma on that call. -
The capability owns SDK retries. In
prepare_model_request, for each attempt, it setsmax_retries=0unless:- the attempt's settings already set it, including the serving model's own
settings, so a fallback model's ownmax_retriesis kept; or - the serving model lists
max_retriesin its unsupported settings (Bedrock, xAI, Hugging Face, ā¦), so those models don't warn.
Setting it in
get_model_settingsinstead would override fallback models' own settings, warn on those models, and break batching. Batching is fixed separately in #11931. - the attempt's settings already set it, including the serving model's own
-
Retries cover the non-streamed request and the opening of a stream, nothing later. A stream that fails after events reached the consumer is not retried.
-
Refusals are left to
ModelFallbackby default. A response withfinish_reason='content_filter'isn't retried with the defaultretry_on, since the same model usually refuses again, andModelFallbackfalls back on refusals by default (#12039). NamingContentFilterErrorinretry_onretries one, empty or with partial text, the same way naming it infallback_onfalls back from one; a streamed refusal is accepted without a warning, asModelFallbackdoes. The spec name listretry_onandfallback_onshare now includesContentFilterError. -
On Temporal, the agent has to be built with the capability. An agent built with
RetryOnModelErrorsmakes every model error non-retryable in the model activity, whatevernon_retryable_model_errorssays, because that's set when the agent is bound. ARetryOnModelErrorsthat only aDynamicCapabilityreturns for the run raises aUserErrorinside a workflow, so the activity and the capability can't both retry. One passed to a run was already rejected by the generic per-run capability check. -
When retries run out and there is no fallback, the last error is raised as is. The earlier attempts are recorded as spans, but are not attached to the error.
Also in this PR
docs/retries.mdnow opens with a one-lineRetryOnModelErrors()example (and the retrying transport for code outside an agent), anddocs/production.mdpoints at it for 429/5xx (#11923).FallbackPredicates.parsetakesparamanddefaultarguments, andshould_fallbackis renamedmatches. The spec name list and parsing helpers move to_fallback.py(SpecModelError,spec_error_types). All of these are private, andModelFallback's messages are unchanged.- Docs:
- a new page,
capabilities/retry-on-model-errors.md, with a "Retry or fall back" section; - in
retries.md: a new layers-table row, a "Retrying the same model" section, and an updatedFmultiplier; - cross-links from
model-fallback.md,custom.mdand the overview, plusagent-spec.md, navigation, and the skill.
- a new page,
- Tests:
tests/test_capability_retry_on_model_errors.py: composition withModelFallbackin both orders, response handlers, streaming before vs after output,max_retriesownership (explicit values kept, unsupported models not warned), the request and run deadlines,BatchModelRequestsretrying into a new batch, the spec form, and replay-stable jitter;- a Temporal test: each retry runs as its own activity, the wait is a workflow timer, and the chain then falls back.
- No API-compat waiver is needed now that #11803 has landed: the
CAPABILITY_TYPESaddition only produces a notice.
Checklist
- No breaking changes in accordance with the version policy.
- Any permitted compatibility impact has a label, warning, migration and release note, and an exact API-check waiver if the gate reports it.
- PR title is fit for the release changelog.
š¤ Generated with Claude Code