Quick Start
This guide walks you through creating your first Pydantic AI agent with guardrails.
Your First Guarded Agent
Section titled “Your First Guarded Agent”-
Import the required modules
from pydantic_ai import Agentfrom pydantic_ai_guardrails import GuardedAgentfrom pydantic_ai_guardrails.guardrails.input import length_limit, pii_detectorfrom pydantic_ai_guardrails.guardrails.output import secret_redaction -
Create a Pydantic AI agent
agent = Agent('openai:gpt-4o') -
Wrap it with guardrails
guarded_agent = GuardedAgent(agent,input_guardrails=[length_limit(max_chars=1000),pii_detector(),],output_guardrails=[secret_redaction(),],) -
Run the agent
result = await guarded_agent.run('Hello, how are you?')print(result.output)
Complete Example
Section titled “Complete Example”Here’s a complete, runnable example:
import asynciofrom pydantic_ai import Agentfrom pydantic_ai_guardrails import GuardedAgentfrom pydantic_ai_guardrails.guardrails.input import length_limit, pii_detectorfrom pydantic_ai_guardrails.guardrails.output import secret_redaction
async def main(): # Create base agent agent = Agent('openai:gpt-4o')
# Add guardrails guarded_agent = GuardedAgent( agent, input_guardrails=[ length_limit(max_chars=1000), pii_detector(), ], output_guardrails=[ secret_redaction(), ], )
# Run with guardrail protection result = await guarded_agent.run('What is the capital of France?') print(result.output)
if __name__ == '__main__': asyncio.run(main())What Happened?
Section titled “What Happened?”When you called guarded_agent.run():
-
Input guardrails ran first
length_limitchecked that the prompt was under 1000 characterspii_detectorscanned for emails, phone numbers, and other PII
-
The agent generated a response
- Your prompt was sent to GPT-4o
- The model returned its response
-
Output guardrails validated the response
secret_redactionchecked for API keys, passwords, and other secrets
-
Result was returned
- All guardrails passed, so you got the response
Handling Violations
Section titled “Handling Violations”When a guardrail blocks a request, it raises an exception:
from pydantic_ai_guardrails import InputGuardrailViolation, OutputGuardrailViolation
try: # This prompt is too long result = await guarded_agent.run('a' * 2000)except InputGuardrailViolation as e: print(f"Blocked by: {e.guardrail_name}") print(f"Reason: {e.message}") print(f"Severity: {e.severity}")Output:
Blocked by: length_limitReason: Input exceeds maximum length of 1000 charactersSeverity: mediumAlternative: Log Instead of Raise
Section titled “Alternative: Log Instead of Raise”If you want to log violations instead of raising exceptions:
guarded_agent = GuardedAgent( agent, input_guardrails=[length_limit(max_chars=1000)], on_block='log', # Log warning instead of raising)
# This will log a warning but continueresult = await guarded_agent.run('a' * 2000)Synchronous Usage
Section titled “Synchronous Usage”For non-async contexts, use run_sync():
result = guarded_agent.run_sync('What is 2 + 2?')print(result.output)Using Built-in Guardrails
Section titled “Using Built-in Guardrails”The library includes 16 built-in guardrails. Here’s a quick overview:
Input Guardrails
Section titled “Input Guardrails”from pydantic_ai_guardrails.guardrails.input import ( length_limit, # Limit prompt length pii_detector, # Detect PII (emails, phones, SSNs) prompt_injection, # Detect prompt injection attacks toxicity_detector, # Detect toxic content blocked_keywords, # Block specific words/phrases rate_limiter, # Rate limit requests)Output Guardrails
Section titled “Output Guardrails”from pydantic_ai_guardrails.guardrails.output import ( secret_redaction, # Detect leaked secrets llm_judge, # LLM-as-a-judge evaluation json_validator, # Validate JSON output regex_match, # Match output against patterns no_refusals, # Detect when LLM refuses min_length, # Ensure minimum length require_tool_use, # Ensure tools were called tool_allowlist, # Restrict which tools can be called)See Built-in Guardrails for full documentation.
Next Steps
Section titled “Next Steps”Now that you’ve built your first guarded agent:
- Input Guardrails Guide - Deep dive into input validation
- Output Guardrails Guide - Protect your model’s responses
- Custom Guardrails - Write your own validation logic
- Auto-Retry - Let the LLM self-correct on violations