Skip to content

Error Handling

Every guardrail error subclasses GuardrailError, which subclasses Pydantic AI’s AgentRunError. Guardrail errors propagate out of agent.run() like any other Pydantic AI error.

AgentRunError (pydantic_ai.exceptions)
└── GuardrailError
├── InputBlocked input guardrails .guardrail, .reason
├── OutputBlocked output guardrails, on_fail='raise' .guardrail, .reason
├── BudgetExceeded LimitCost
├── ToolDenied RestrictTools, approval needed but no callback .tool_name, .reason
└── GuardrailFailed AsyncGuardrail, LlmJudge judge errors .guardrail, .reason

Recoverable failures (an output guardrail with on_fail='retry', a hidden or unapproved tool, a bad tool argument) raise ModelRetry instead. The model handles those, and you only see UnexpectedModelBehavior if it runs out of retries.

from pydantic_ai import Agent
from pydantic_ai.exceptions import UnexpectedModelBehavior
from pydantic_ai_guardrails import (
BudgetExceeded,
DetectPII,
GuardrailError,
InputBlocked,
LimitCost,
LimitOutputLength,
OutputBlocked,
)
agent = Agent(
'openai:gpt-4o',
capabilities=[DetectPII(), LimitOutputLength(max_chars=500, on_fail='raise'), LimitCost(max_total_tokens=10_000)],
)
def answer(prompt: str) -> str:
try:
return agent.run_sync(prompt).output
except InputBlocked as e:
return f"I can't process that request ({e.reason})."
except OutputBlocked as e:
return 'Sorry, I could not produce a suitable answer.'
except BudgetExceeded:
return 'This request was too expensive to complete.'
except UnexpectedModelBehavior:
return 'The model could not meet the output requirements.'
except GuardrailError as e:
return f'Blocked: {e}'
from fastapi import FastAPI, HTTPException
from pydantic_ai import Agent
from pydantic_ai_guardrails import BudgetExceeded, DetectPromptInjection, InputBlocked, LimitCost, OutputBlocked
app = FastAPI()
agent = Agent('openai:gpt-4o', capabilities=[DetectPromptInjection(), LimitCost(max_total_tokens=20_000)])
@app.post('/chat')
async def chat(prompt: str) -> dict[str, str]:
try:
result = await agent.run(prompt)
except InputBlocked as e:
raise HTTPException(status_code=400, detail={'guardrail': e.guardrail, 'reason': e.reason})
except OutputBlocked as e:
raise HTTPException(status_code=422, detail={'guardrail': e.guardrail, 'reason': e.reason})
except BudgetExceeded as e:
raise HTTPException(status_code=429, detail=str(e))
return {'output': result.output}

Guardrails validate their configuration when you create them:

Cause Error
Unknown PII type, toxicity category or secret pattern ValueError
ML threshold / score_threshold outside [0, 1] or NaN ValueError
Missing required argument (e.g. LimitCost() with no budget) ValueError
ML backend requested but its package is not installed ImportError with the pip install command
ValidateJson(schema=...) using keywords beyond type without jsonschema ImportError
Unknown config key or bad config params ValueError naming the guardrail

Guardrails with on_fail='warn', AsyncGuardrail(mode='monitoring') and LlmJudge(on_error='allow') log to the pydantic_ai_guardrails logger:

import logging
logging.getLogger('pydantic_ai_guardrails').setLevel(logging.WARNING)

For structured traces, see OpenTelemetry.