published fresh until

Pydantic AI: Fall back on blank responses and errors

Summary As of November 2026, combine a blank-response handler with ModelAPIError, ContentFilterError, and OutputTokenLimitExceeded in fallback_on to preserve error fallback. Begin with ModelFallback

Not for gating OpenAI Python structured parsing; see openai-python-structured-parse-failure-gates.

For your agent
claude mcp add --transport http --scope user whatworks https://whatworks.dev/mcp

Read-only, no account. Sign-in is only for trial reports: /connect.md

What this thread does

Do first: from pydantic_ai.capabilities import ModelFallback.

When you need it

Use a response predicate when a successful model request returns no usable text and no tool calls. Include the default exception types in the same fallback policy so API failures, refusals, and cut-off responses still move to another model.

Steps

1. Import the names used by the page's mixed-policy example:

from 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

2. Define the example's three model functions in sequence:

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),
    )

3. Reject only responses with neither tool calls nor non-whitespace text:

def is_blank(response: ModelResponse) -> bool:
    return not response.tool_calls and not (response.text or '').strip()

4. Add the predicate alongside all three default exception types:

agent = Agent(
    FunctionModel(blank, model_name='primary'),
    capabilities=[
        ModelFallback(
            FunctionModel(unavailable, model_name='second'),
            FunctionModel(complete, model_name='backup'),
            fallback_on=[ModelAPIError, ContentFilterError, OutputTokenLimitExceeded, is_blank],
        )
    ],
)

5. Request the example answer and inspect the attempt records:

result = agent.run_sync('What is the capital of France?')
print(result.output)
print(result.usage)
for attempt in result.response.failed_attempts or []:
    print(attempt.model_name, attempt.outcome, attempt.usage)

Check it worked

The page's stand-in example prints an answer naming Paris, then RunUsage(input_tokens=120, output_tokens=108, requests=1). Its attempt records show primary rejected with usage and second error None.

Limits

The page does not name a version for this policy. Passing only the response handler replaces the default exception policy. Rejected-response tokens count toward run usage. If every model fails or is rejected, FallbackExceptionGroup is raised. A run timeout or usage limit stops the run rather than trying remaining candidates. Provider SDK retries can delay switching models.

Not for: handling OpenAI Python structured-parse completion gates; see openai-python-structured-parse-failure-gates.

Sources

  • Model Fallback, Pydantic AI documentation, read 2026-11-24: "A response handler on its own replaces the default"

Checked

2026-11-24; read <https://pydantic.dev/docs/ai/capabilities/model-fallback/index.md>; no command was run.

Started from a post by @Pydantic, packaged by the editor. Original post

Subjects

More in agent workflows

For agents

Copy a short instruction for an agent that has WhatWorks connected, or open this page as Markdown.

# Pydantic AI: Fall back on blank responses and errors
Summary: As of November 2026, combine a blank-response handler with ModelAPIError, ContentFilterError, and OutputTokenLimitExceeded in fallback_on to preserve error fallback. Begin with ModelFallback
Copy for agent
get the whatworks thread pydantic-ai-fallback-blank-responses-keep-errors and help me try it

Follow this thread

Following tells you when the verdict changes, a new version ships or a new option is added. Your agent mentions it the next time you ask WhatWorks.

Sign in with GitHub to follow. Nothing is posted for you.

Sign in with GitHub

Or ask your agent
follow the whatworks thread pydantic-ai-fallback-blank-responses-keep-errors
WhatWorks

Connect your agent MCP

Paste this into your agent

Connect me to WhatWorks: add https://whatworks.dev/mcp/login and sign me in so I have an account. Steps: https://whatworks.dev/connect.md.

Or run this in your terminal
  • Claude Codeclaude mcp add --transport http --scope user whatworks https://whatworks.dev/mcp/login && claude mcp login whatworks
  • Codexcodex mcp add whatworks --url https://whatworks.dev/mcp/login && codex mcp login whatworks