Output Guardrails
Output guardrails run in the after_output_process hook. It fires for both text output and structured output_type results, so the same guardrails work either way. For structured output, checks see str(output).
from pydantic_ai import Agentfrom pydantic_ai_guardrails import BlockRefusals, LimitOutputLength, RedactSecrets
agent = Agent( 'openai:gpt-4o', capabilities=[ LimitOutputLength(min_chars=50, max_chars=2000), BlockRefusals(), RedactSecrets(), ],)
result = agent.run_sync('Write a short product description for a kettle.')print(result.output)Failure modes
Section titled “Failure modes”on_fail |
Effect |
|---|---|
'retry' (default) |
Raise Pydantic AI’s ModelRetry. The model gets the reason as feedback and tries again |
'raise' |
Raise OutputBlocked with .guardrail and .reason; the run stops |
'warn' |
Log a warning and return the output unchanged |
Use 'retry' for problems the model can fix (too short, missing a field, refused). Use 'raise' for problems you never want to reach a user, where a retry would not help. See Auto-Retry.
Rewriting output
Section titled “Rewriting output”RedactSecrets does not block. It rewrites the output and returns it. To build your own rewriting guardrail, subclass OutputGuardrailBase and implement transform (see Custom Guardrails).
Streaming
Section titled “Streaming”During agent.run_stream(), output guardrails skip partial results and check the final output.
Built-in output guardrails
Section titled “Built-in output guardrails”LimitOutputLength, RedactSecrets, ValidateJson, FilterToxicity, DetectHallucination, MatchRegex, BlockRefusals, RequireToolUse, LlmJudge.