Pydantic AI native
Guardrails hook into the agent lifecycle (before_run, prepare_tools, after_output_process). Errors subclass Pydantic AI’s AgentRunError.
from pydantic_ai import Agentfrom pydantic_ai_guardrails import DetectPII, DetectPromptInjection, LimitCost, RedactSecrets
agent = Agent( 'openai:gpt-4o', capabilities=[ DetectPromptInjection(sensitivity='high'), DetectPII(), RedactSecrets(), LimitCost(max_total_tokens=100_000), ],)
result = agent.run_sync('Plan a trip to Lisbon')print(result.output)Every guardrail is a pydantic_ai.capabilities.AbstractCapability. You add it with Agent(capabilities=[...]), the same way you add Pydantic AI’s own capabilities. There is no wrapper class and no separate run method.
Pydantic AI native
Guardrails hook into the agent lifecycle (before_run, prepare_tools, after_output_process). Errors subclass Pydantic AI’s AgentRunError.
18 built-in guardrails
PII, prompt injection, toxicity, keywords, length, rate limits, secrets, JSON, regex, refusals, hallucination heuristics, LLM judge, tool restrictions and token budgets.
Self-correcting output
Output guardrails raise ModelRetry by default, so the model sees the reason and rewrites its answer.
Traced with OpenTelemetry
Each check emits a guardrail <Name> span. With Logfire or any OTel SDK, guardrail spans nest inside the agent trace.
Input guardrails
Stop a run before the model is called. Raise InputBlocked, or log with on_fail='warn'.
Tool and cost guardrails
Allow, hide or approval-gate tools with glob patterns. Stop the run once a token budget is crossed.
Optional ML backends
Regex detectors need no dependencies. Switch to Presidio, Detoxify or a transformers classifier with one argument.
Custom guardrails
Pass any sync or async function to InputGuardrail or OutputGuardrail, or subclass a base class.
Config files
Describe a guardrail set in JSON or YAML and build it with build_guardrails(load_config(path)).
Testing helpers
pydantic_ai_guardrails.testing provides async assertions built on Pydantic AI’s TestModel.
Installation
Install the package and any optional extras. Install now
Quick Start
Add your first guardrails to an agent. Start building
Built-in Guardrails
Browse all 18 built-in guardrails. View guardrails
Custom Guardrails
Write your own checks. Create custom