Add provider-neutral model error categories like `ModelRateLimitError`, `ModelUnavailableError`, `ModelServerError` and `ModelContextWindowExceededError`, and `ModelHTTPError.for_category`
Handling a failed model request used to mean reading each provider's exception chain. Overload, rate limiting, transport failures and context overflow arrived as a ModelHTTPError with some status and a provider-specific body, or as a bare ModelAPIError whose details were only on __cause__. This PR adds the error categories decided in #9339.
[!WARNING]
Compatibility impact: Existing code that matches model errors by exact type or class name, or that relies on an in-stream error not being a ModelHTTPError, may behave differently:
- Errors that were a plain
ModelHTTPError or ModelAPIError may now be an instance of a subclass, so exact-type checks like type(e) is ModelHTTPError no longer match them.
- An HTTP error with a category reads as its category (e.g.
ModelRateLimitError: status_code: 429, ...) instead of ModelHTTPError in tracebacks, repr(), OTel exception.type and ModelRequestAttempt.error strings in failed_attempts.
- Bedrock
ConverseStream exception events, error objects inside OpenAI-compatible and OpenAI Responses streams, Hugging Face TGI's in-stream OverloadedError, and xAI INVALID_ARGUMENT are now a ModelHTTPError with the status the provider uses for the same error, instead of a plain ModelAPIError. So except ModelHTTPError now catches them, under Temporal a retry policy with non_retryable_error_types=['ModelHTTPError'] now stops retrying them, and their str(e) and message take ModelHTTPError's form (status_code: 429, model_name: ..., body: {...}) instead of the provider's message text, which is still in body.
Why this can ship in a minor release: Every error is still a ModelHTTPError or ModelAPIError (now possibly a subclass of it), so except and isinstance checks that matched before still match; errors that already had a status keep their status code, body, headers and message. OTel attributes and repr() may change in a minor release, and the class name in an error string is not a documented format. An in-stream error not being a ModelHTTPError depended on whether the request happened to be streamed, which wasn't documented and is what this PR fixes.
Migration: Match errors with except or isinstance (e.g. except ModelRateLimitError) rather than exact-type checks or class-name strings in logs, alerts or failed_attempts. Code that reads the provider's text from str(e) or e.message of those in-stream errors should read e.body instead. To keep Temporal retrying these in-stream errors, don't list 'ModelHTTPError' in non_retryable_error_types; a retry policy only sees ModelHTTPError or ModelAPIError, never a category name.
New public surface (all exported from pydantic_ai):
- The categories, each a subclass of
ModelAPIError:ModelRateLimitError,ModelQuotaExceededError,ModelUnavailableErrorwith itsModelOverloadedErrorsubclass,ModelServerError,ModelConnectionErrorwith itsModelTimeoutErrorsubclass, andModelContextWindowExceededError. ModelHTTPError.for_category(category, *, status_code, model_name, body=None, headers=None, ...), which builds the combined HTTP + category error the adapters raise, for custom models and tests.- On
ModelAPIError: the new optional keyword fieldsprovider_error_code,provider_error_typeandin_stream, plusbodyandretry_after(now a stored field, also read fromretry-after-ms), which move up fromModelHTTPError. ModelConnectionError.phase('pool','connect','write','read') andModelHTTPError.provider_retry_hint(fromx-should-retry).
Behavior
- An error that came with an HTTP status is raised as a private combined class from
ModelHTTPError.for_category, e.g.ModelHTTPError+ModelRateLimitError. The private class takes its category's name, so tracebacks,repr(), OTelexception.typeandModelRequestAttempt.errorshowModelRateLimitError, not a private name; it pickles and crosses the Temporal activity boundary as itself. Soexcept ModelHTTPError,status_code,bodyandheaderswork as before, andexcept ModelRateLimitErrorcatches it too. Under Temporal, a retry policy still sees an error with a category asModelHTTPError(with an HTTP status) orModelAPIError(without), sonon_retryable_error_typesmatches what it did before; workflow code gets the category class. - An error inside an already open stream gets the status the same error has before a stream opens, with
in_stream=True, becauserun()can stream without the user asking (event stream handlers, #9298). That covers Anthropicerrorevents (#9298's mapping), OpenAI-compatible error objects and Responses events bycode/type(e.g.rate_limit_exceeded→ 429,server_error→ 500), Bedrock exception events (e.g.throttlingException→ 429) and TGIOverloadedError(429). One with no clear equivalent stays a plainModelAPIErrorwithin_stream=True. - Classification uses the provider's code or type first:
- status: 402 → quota; 429 → rate limit; 503 → unavailable (overloaded if the message says "overloaded" or "over capacity"); 529 → overloaded; other 5xx → server error
- codes:
context_length_exceeded; OpenAIinsufficient_quota/billing_hard_limit_reached→ quota; anoverloadedcode or type → overloaded; Anthropicrate_limit_error/billing_error(quota) /overloaded_error; BedrockThrottlingException,ServiceQuotaExceededException(quota),ServiceUnavailableException/ModelNotReadyException(unavailable, or overloaded if the message says so); Google and xAIRESOURCE_EXHAUSTED(rate limit),UNAVAILABLE(unavailable, or overloaded if the message says so),INTERNAL(server error); Mistral3051 - message text only for context overflow (Anthropic, Bedrock, Google, Groq without a code, Cohere, xAI, OpenAI-compatible APIs without a code), Anthropic's "credit balance is too low" 400 (quota), and an explicit overload in an unavailable error
- Gemini's
RESOURCE_EXHAUSTEDis always a rate limit: it's the same status and message for a per-minute limit and exhausted quota. xAIDEADLINE_EXCEEDEDstays unclassified, because it can mean either side's deadline. - The derived statuses (xAI gRPC, now including
INVALID_ARGUMENT→ 400; OpenRoutercode; Google in-stream) are kept as the provider's own equivalents, and now carry a category,provider_error_codeand, in a stream,in_stream. FallbackModel's defaultfallback_on=(ModelAPIError,)is unchanged, so it falls back on every category, includingModelContextWindowExceededError(#7139). The docs show how to exclude it and catch it withexcept*, and how to fall back only on some categories.
The overflow detection builds on @dsfaccini's #4221: the same signals, and its recorded wire bodies. Its default_fallback_on change is intentionally not included; see the thread there.
What changes for existing users: errors that were a plain ModelHTTPError or ModelAPIError may now be a subclass of it. Errors that already had a status keep their status code, body, headers and message. Exact-type checks like type(e) is ModelHTTPError would notice, and so would anything that reads the class name: an HTTP error with a category shows as its category (e.g. ModelRateLimitError: status_code: 429, ...) in tracebacks, repr(), OTel exception.type and ModelRequestAttempt.error, where it showed ModelHTTPError before. Errors that came without an HTTP status but now get the status the provider uses for the same error are now a ModelHTTPError instead of a plain ModelAPIError, so except ModelHTTPError newly catches them, a Temporal retry policy now sees them as ModelHTTPError, and their str(e)/message is ModelHTTPError's status_code: ..., model_name: ..., body: ... form rather than the provider's message (which stays in body): Bedrock ConverseStream exception events (e.g. throttling as 429), error objects inside OpenAI-compatible and OpenAI Responses streams, Hugging Face TGI's in-stream OverloadedError, and xAI INVALID_ARGUMENT (as 400).
Verification
tests/models/test_error_categories.py: 41 cases across OpenAI, OpenRouter, Anthropic (including streamerrorevents), Groq, Google, Mistral, Cohere, Bedrock (including stream exceptions and timeouts), xAI and Hugging Face. They run wire-shaped errors through each SDK and assert the exact set of classes and fields. 40 of them fail with the adapters reverted; the 41st pins an error that stays unclassified.tests/test_exceptions.py: pickling and hashing for the new classes and the combined classes.check_api_compatibility.py --against v2.51.0passes.
Dependencies on open fix PRs
#9321, #9307, #9308, #9314 and #9336 edit the same _map_api_errors functions, so whichever lands second needs a small rebase. Each edit here is kept local to the raise statements to make that easy. #9313 and #9312 are merged in, and their in-stream errors are classified here. #9336 is merged in too: every transport error it maps (Google, Mistral, Cohere, Hugging Face, Anthropic, Groq and Bedrock, including the Google and Cohere embedding models) raises ModelConnectionError/ModelTimeoutError with phase where the transport error says. The DecisionModel adapters (TypeSafeModel, SystemOneModel, OpenAIDecisionsModel) classify their HTTP and transport errors the same way. Other errors from embedding, image and realtime models are not classified yet.
Checklist
- 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.
- PR title is fit for the release changelog.