翻篇收录说明
翻篇网页快照

Model Fallback | Pydantic Docs

https://pydantic.dev/docs/ai/capabilities/model-fallback/

最近抓取:2026-12-03 23:23:58(北京时间)

最近内容变化:2026-12-03 23:23:58(北京时间)

这是最近一次有效抓取的文本快照,不含网页脚本、图片和动态交互内容。实际网页可能已更新。

访问原网页

页面简介

Fall back to other models when a Pydantic AI model request fails or its response is rejected, with the ModelFallback capability.

正文摘录

Model Fallback ModelFallback is a capability that attempts other models when the one serving a request fails, or returns a response you reject. It’s the way to fall back to other models in an agent; FallbackModel remains for direct model requests and standalone models (see Migrating from FallbackModel). The chain is the model selected for the step, followed by the capability’s models: model_fallback_capability.pyfrom pydantic_ai import Agent from pydantic_ai.capabilities import ModelFallback # Try the OpenAI model first, then the Anthropic one. agent = Agent('openai:gpt-6.1-sol', capabilities=[ModelFallback('anthropic:claude-sonnet-5-5')]) Because the chain starts from the model selected for the step, ModelFallback composes with the agent’s model, a model passed to agent.run(model=...), and SelectModel: whichever model they choose is attempted first. When the agent has no model and nothing else selects one, the first of ModelFallback’s models is used for the first attempt: model_fallback_without_agent_model.pyfrom pydantic_ai import Agent from pydantic_ai.capabilities import ModelFallback agent = Agent(capabilities=[ModelFallback('openai:gpt-6.1-sol', 'anthropic:claude-sonnet-5-5')]) A model that was already attempted in the step is skipped, whichever capability attempted it, so listing the agent’s own model among the candidates doesn’t cause a duplicate request. Falling back is not retrying: the next model usually can’t use the prompt cache that earlier requests built on the first one, and can answer differently and at a different price. Leave a transient failure, like a dropped connection, to a retry of the same model, with a budget small enough that it doesn’t hold up the fallback when the model stays down: add RetryOnModelErrors, and each model in the chain is retried before the request moves on to the next one (see Retry or fall back). See Recovery scopes compared and Choosing one retry owner. When to fall back By default, ModelFallback moves on when a request raises ModelAPIError, the error a model raises when the provider’s API fails, such as a 4xx or 5xx response, or sends a response the model can’t use, such as an empty stream (see Handling Model API Errors), when the model refuses, and when the output is cut off by the token limit: fallback_on defaults to (ModelAPIError, ContentFilterError, OutputTokenLimitExceeded). That includes a request the model can’t serve. When the model’s profile says it doesn’t support what the request asks for, like Native Output from a model without JSON schema output, Tool Output from one without tool calling, text or image output, or a tool_choice that forces tool use from one that can’t force it, Pydantic AI raises ModelFeatureUnsupportedError without sending the request, and ModelFallback moves on to the next model. The skipped model is recorded in the response’s failed_attempts like any other. When no model in the chain can serve the request, the run raises a FallbackExceptionGroup of these errors. Each is also a UserError, which is what a model without a fallback raises, as before. Under durable execution, AWS Lambda, Azure Durable Task and Render Workflows lose the error class, so ModelFallback doesn’t move on there (#13318); AWS Lambda also retries it first. The fallback_on parameter takes the same forms as FallbackModel’s, whose default is (ModelAPIError,): a tuple of exception types an exception handler, (Exception) -> bool a response handler, (ModelResponse) -> bool, which rejects a response that was returned successfully a sequence mixing any of the above Handlers may be sync or async. A handler whose first parameter is annotated as ModelResponse is a response handler; any other handler is an exception handler. See Response-Based Fallback for examples of handlers, which work the same for both. Here the first model’s answer is blank and rejected by a response handler, the second model fails, and the third answers. The answering response lists both attempts it moved on from, and the rejected response’s tokens count in the run’s usage: model_fallback_mixed_policy.pyfrom pydantic_ai import Agent, ModelAPIError, ModelMessage, ModelResponse, TextPart from pydantic_ai.capabilities import ModelFallback from pydantic_ai.exceptions import ContentFilterError, OutputTokenLimitExceeded from pydantic_ai.models.function import AgentInfo, FunctionModel from pydantic_ai.usage import RequestUsage def blank(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse: return ModelResponse( parts=[TextPart('\n\n')], usage=RequestUsage(input_tokens=60, output_tokens=100), ) def unavailable(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse: raise ModelAPIError('second', 'Service unavailable') def complete(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse: return ModelResponse( parts=[TextPart('The capital of France is Paris.')], usage=RequestUsage(input_tokens=60, output_tokens=8), ) def is_blank(response: ModelResponse) -> bool: return not response.tool_calls and not (response.text or '').strip() agent = Agent( # These deterministic models stand in for three providers. FunctionModel(blank, model_name='primary'), capabilities=[ ModelFallback( FunctionModel(unavailable, model_name='second'), FunctionModel(complete, model_name='backup'), fallback_on=[ModelAPIError, ContentFilterError, OutputTokenLimitExceeded, is_blank], ) ], ) result = agent.run_sync('What is the capital of France?') print(result.output) #> The capital of France is Paris. print(result.usage) #> RunUsage(input_tokens=120, output_tokens=108, requests=1) for attempt in result.response.failed_attempts or []: print(attempt.model_name, attempt.outcome, attempt.usage) #> primary rejected RequestUsage(input_tokens=60, output_tokens=100) #> second error None When every model has failed or been rejected, ModelFallback raises FallbackExceptionGroup with every exception, plus a ResponseRejected counting any rejected responses. A run that reaches its timeout= stops with RunTimedOut wherever it is, including in the middle of a candidate’s request: the remaining candidates aren’t attempted. Likewise, a request that exceeds the run’s usage limits raises UsageLimitExceeded whatever fallback_on says, as another model wouldn’t change that. Falling back when a model refuses A model sometimes refuses a request on safety grounds that another model would carry out, as a coding agent can find when a task touches on security. Pydantic AI reports a refusal as a successful response with a finish_reason of 'content_filter', and puts the provider’s explanation, where it gives one, in [provider_details['refusal']][pydantic_ai.messages.ModelResponse.provider_details]: Anthropic’s stop_reason: 'refusal' with its stop_details, the refusal that OpenAI sends in place of content, and Azure’s content filter. ModelFallback moves on from a refusal by default, to the next model, which applies its own provider’s safety policy. That’s the capability doing what you add it for; the agent on its own keeps its content-filter behavior, so without ModelFallback an empty refusal raises ContentFilterError and one with text is the run’s output. It does so whether the response is empty or has partial text: Anthropic recommends treating any partial output of a refused response as incomplete, and pointing the retry at a fallback model rather than the same one, which usually refuses again. Naming ContentFilterError in fallback_on, as the default does, is what turns this on: the agent raises that error only after it has accepted a response, too late to fall back from it, so in fallback_on it stands for the response it’s raised for. model_fallback_on_refusal.pyfrom pydantic_ai import Agent, ModelMessage, ModelResponse, TextPart from pydantic_ai.capabilities import ModelFallback from pydantic_ai.models.function import AgentInfo, FunctionModel def refuse(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse: return ModelResponse( parts=[], finish_reason='content_filter', provider_details={'finish_reason': 'refusal', 'refusal': "I can't help with that request."}, ) def answer(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse: return ModelResponse( parts=[TextPart("The input isn't escaped before it reaches the query; here's the fix.")] ) agent = Agent( # Deterministic stand-ins: an Anthropic model that refuses, and an OpenAI model that takes over. FunctionModel(refuse, model_name='anthropic-stand-in'), capabilities=[ModelFallback(FunctionModel(answer, model_name='openai-stand-in'))], ) result = agent.run_sync('Explain the vulnerability in this code and how to fix it.') print(result.output) #> The input isn't escaped before it reaches the query; here's the fix. for attempt in result.response.failed_attempts or []: print(attempt.model_name, attempt.outcome) #> anthropic-stand-in rejected A few things to know about falling back on refusals: To have a refusal end the run instead, opt out with fallback_on=(ModelAPIError, OutputTokenLimitExceeded). An empty refusal then raises ContentFilterError, and one with text is the run’s output, as without ModelFallback; add RaiseContentFilterError to raise on those too. A FallbackModel doesn’t fall back on refusals by default. Pass it fallback_on=(ModelAPIError, ContentFilterError). It happens per request. When a model refuses partway through a run, only that request moves to the next model, with the run’s message history so far. The responses the first model gave earlier in the run stay in the history. Anthropic recommends staying on the fallback model for the rest of the conversation, which sticky=True does. Without a fallback, an empty refusal raises ContentFilterError. It’s an UnexpectedModelBehavior, not a ModelAPIError, and so is a thinking-only refusal. Its message starts with Content filter triggered. and then names the reason: Refusal: '...' with the text from provider_details['refusal'] for an OpenAI refusal, or Finish reason: 'refusal' for an Anthropic one, whose refusal text