You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: docs/models.md
+112Lines changed: 112 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -653,3 +653,115 @@ For streaming, you'll also need to implement the following abstract base class:
653
653
The best place to start is to review the source code for existing implementations, e.g. [`OpenAIModel`](https://github.com/pydantic/pydantic-ai/blob/main/pydantic_ai_slim/pydantic_ai/models/openai.py).
654
654
655
655
For details on when we'll accept contributions adding new models to PydanticAI, see the [contributing guidelines](contributing.md#new-model-rules).
656
+
657
+
658
+
## Fallback
659
+
660
+
You can use [`FallbackModel`][pydantic_ai.models.fallback.FallbackModel] to attempt multiple models
661
+
in sequence until one returns a successful result. Under the hood, PydanticAI automatically switches
662
+
from one model to the next if the current model returns a 4xx or 5xx status code.
663
+
664
+
In the following example, the agent first makes a request to the OpenAI model (which fails due to an invalid API key),
665
+
and then falls back to the Anthropic model.
666
+
667
+
```python {title="fallback_model.py"}
668
+
from pydantic_ai import Agent
669
+
from pydantic_ai.models.anthropic import AnthropicModel
670
+
from pydantic_ai.models.fallback import FallbackModel
The `ModelResponse` message above indicates in the `model_name` field that the result was returned by the Anthropic model, which is the second model specified in the `FallbackModel`.
706
+
707
+
!!! note
708
+
Each model's options should be configured individually. For example, `base_url`, `api_key`, and custom clients should be set on each model itself, not on the `FallbackModel`.
709
+
710
+
In this next example, we demonstrate the exception-handling capabilities of `FallbackModel`.
711
+
If all models fail, a [`FallbackExceptionGroup`][pydantic_ai.exceptions.FallbackExceptionGroup] is raised, which
712
+
contains all the exceptions encountered during the `run` execution.
0 commit comments