Skip to content

Exceptions

All guardrail exceptions subclass GuardrailError, which subclasses pydantic_ai.exceptions.AgentRunError. Import them from pydantic_ai_guardrails.

Exception Raised by Attributes
GuardrailError Base class; catch it to handle every guardrail failure
InputBlocked Input guardrails with on_fail='raise' .guardrail, .reason
OutputBlocked Output guardrails with on_fail='raise' .guardrail, .reason
BudgetExceeded LimitCost message only
ToolDenied RestrictTools when a tool needs approval but no approval callback is set .tool_name, .reason
GuardrailFailed AsyncGuardrail; LlmJudge when the judge fails and on_error='raise' .guardrail, .reason
Exception When
pydantic_ai.ModelRetry Output guardrails with on_fail='retry' (default), denied or hidden tools, failing tool-argument checks. Pydantic AI catches it and asks the model to try again
pydantic_ai.exceptions.UnexpectedModelBehavior The model ran out of retries
ValueError Bad constructor arguments or config, such as unknown option names or an ML threshold outside [0, 1], raised at construction
ImportError An optional backend or jsonschema is not installed, raised at construction

.guardrail is the guardrail’s class name, or its label for InputGuardrail / OutputGuardrail.

Read the reason from .reason. For InputBlocked, OutputBlocked and GuardrailFailed, the exception message leaves the reason out (DetectPII: input blocked (reason on .reason)) unless PYDANTIC_AI_GUARDRAILS_TRACE_REASONS=1, because exception messages end up in traces and logs and a reason can quote user content.

import logging
from pydantic_ai import Agent
from pydantic_ai_guardrails import DetectPII, GuardrailError, InputBlocked, OutputBlocked
log = logging.getLogger(__name__)
agent = Agent('openai:gpt-4o', capabilities=[DetectPII()])
try:
result = agent.run_sync('my SSN is 123-45-6789')
except (InputBlocked, OutputBlocked) as e:
log.warning('guardrail %s blocked: %s', e.guardrail, e.reason)
except GuardrailError as e:
log.error('guardrail error: %s', e)

See Error Handling for patterns.