Add `RetryOnModelErrors` capability to retry the same model on transient model API errors

Merged
DO
17d ago
+2027-118

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_on decides, in the same forms as fallback_on: exception types, sync or async exception handlers, response handlers, or a list mixing them. The predicate parsing is shared with ModelFallback, not copied.
  • Default retry_on: ModelRateLimitError, ModelUnavailableError (including ModelOverloadedError), ModelServerError, and ModelConnectionError (including ModelTimeoutError). It's exported as pydantic_ai.capabilities.TRANSIENT_MODEL_ERRORS, the actual default, so applications can extend it (retry_on=(*TRANSIENT_MODEL_ERRORS, MyError)) or check an error with isinstance(error, TRANSIENT_MODEL_ERRORS).
  • Never retried:
    • an x-should-retry: false header (ModelHTTPError.provider_retry_hint is False). ModelFallback can still move on to another model.
    • UsageLimitExceeded.
    • non-default categories unless retry_on names them.
  • Waits use the error's retry_after. Without one, the wait is exponential backoff from initial_delay (doubling, capped at max_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.sleep on 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_delay or would end after the request deadline or the run deadline. That lets ModelFallback move on while there is still time.
  • Retry budget. max_attempts counts 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. RetryOnModelErrors is innermost and wrapped_by=(ModelFallback,), so it judges each failure first.
    • Two RetryOnModelErrors instances count the same attempts.
  • Attempt records. ModelRequestAttempt gets two new defaulted fields, kind: Literal['retry', 'fallback'] = 'fallback' and retry_after: float | None = None.
    • The core sets kind='retry' for any hook that raises RetryModelRequest() without a model.
    • Retries and fallbacks share one ordered failed_attempts list.
    • Attempts count towards token and cost limits, but not towards request_limit.
  • Streaming. A stream is retried only if it fails before its first event has reached the consumer.

Decisions for sign-off

  1. retry_on takes fallback_on's forms, including response handlers. A response handler rejects a non-streamed response and the same model is attempted again. When max_attempts is used up, the response is accepted, so an outer ModelFallback can judge it.

  2. 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: true does not override retry_on.
  3. Waiting. A retry_after longer than max_delay gives up rather than waiting, on the reasoning that a provider asking for minutes usually means a quota reset. The defaults are max_attempts=3, initial_delay=1, max_delay=30.

  4. Request deadline covers all retries of a model. On main, request_timeout is 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 ModelFallback moves 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 clock RequestDeadline uses, which Temporal replays. The module is added to the workflow-side determinism check, with a pragma on that call.

  5. The capability owns SDK retries. In prepare_model_request, for each attempt, it sets max_retries=0 unless:

    • the attempt's settings already set it, including the serving model's own settings, so a fallback model's own max_retries is kept; or
    • the serving model lists max_retries in its unsupported settings (Bedrock, xAI, Hugging Face, …), so those models don't warn.

    Setting it in get_model_settings instead would override fallback models' own settings, warn on those models, and break batching. Batching is fixed separately in #11931.

  6. 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.

  7. Refusals are left to ModelFallback by default. A response with finish_reason='content_filter' isn't retried with the default retry_on, since the same model usually refuses again, and ModelFallback falls back on refusals by default (#12039). Naming ContentFilterError in retry_on retries one, empty or with partial text, the same way naming it in fallback_on falls back from one; a streamed refusal is accepted without a warning, as ModelFallback does. The spec name list retry_on and fallback_on share now includes ContentFilterError.

  8. On Temporal, the agent has to be built with the capability. An agent built with RetryOnModelErrors makes every model error non-retryable in the model activity, whatever non_retryable_model_errors says, because that's set when the agent is bound. A RetryOnModelErrors that only a DynamicCapability returns for the run raises a UserError inside 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.

  9. 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.md now opens with a one-line RetryOnModelErrors() example (and the retrying transport for code outside an agent), and docs/production.md points at it for 429/5xx (#11923).
  • FallbackPredicates.parse takes param and default arguments, and should_fallback is renamed matches. The spec name list and parsing helpers move to _fallback.py (SpecModelError, spec_error_types). All of these are private, and ModelFallback'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 updated F multiplier;
    • cross-links from model-fallback.md, custom.md and the overview, plus agent-spec.md, navigation, and the skill.
  • Tests:
    • tests/test_capability_retry_on_model_errors.py: composition with ModelFallback in both orders, response handlers, streaming before vs after output, max_retries ownership (explicit values kept, unsupported models not warned), the request and run deadlines, BatchModelRequests retrying 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_TYPES addition 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