Skip to content

Auto-Retry

Output guardrails default to on_fail='retry'. A failure raises Pydantic AI’s ModelRetry, the same exception your own tools and output validators raise. Pydantic AI sends the message back to the model as a retry prompt and the model tries again. There is no separate retry loop in this library.

prompt → model → output guardrail fails → ModelRetry("LimitOutputLength: only 12 chars (minimum 100)")
→ model (sees the reason) → output guardrail passes → result

The number of attempts comes from the agent’s output retry budget:

from pydantic_ai import Agent
from pydantic_ai_guardrails import LimitOutputLength, MatchRegex
agent = Agent(
'openai:gpt-4o',
retries={'output': 3},
capabilities=[
LimitOutputLength(min_words=40),
MatchRegex(r'TICKET-\d+', on_fail='retry'),
],
)

When the budget runs out, Pydantic AI raises UnexpectedModelBehavior:

from pydantic_ai import Agent
from pydantic_ai.exceptions import UnexpectedModelBehavior
from pydantic_ai_guardrails import LimitOutputLength
agent = Agent('openai:gpt-4o', retries={'output': 3}, capabilities=[LimitOutputLength(min_words=40)])
try:
result = agent.run_sync('Summarise ticket TICKET-42')
except UnexpectedModelBehavior as e:
print(f'Model could not satisfy the guardrails: {e}')
Problem Use
Too short or too long, missing a pattern, bad JSON, canned refusal, missing tool call 'retry': the model can fix it
Content you never want shown, even once 'raise': stop with OutputBlocked
Not sure yet 'warn': log it and measure

Each retry is another model request, so it costs tokens. Combine with LimitCost to cap the total.

For a custom guardrail, the reason string is the feedback the model sees. Say what to change, not just what failed:

from pydantic_ai_guardrails import OutputGuardrail
def cites_source(output: str) -> bool | str:
if 'Source:' not in output:
return 'End the answer with a line "Source: <url>" naming where the information came from.'
return True
OutputGuardrail(guard=cites_source)