Custom Guardrails
There are three ways to add your own check, from least to most code.
1. Pass a function
Section titled “1. Pass a function”InputGuardrail and OutputGuardrail wrap a function you supply.
from pydantic_ai import Agentfrom pydantic_ai_guardrails import InputGuardrail, OutputGuardrail
def no_sql(text: str) -> bool: return 'drop table' not in text.lower()
async def polite(output: str) -> bool | str: return True if 'please' in output.lower() else 'Ask politely; include the word "please".'
agent = Agent( 'openai:gpt-4o', capabilities=[ InputGuardrail(guard=no_sql, label='NoSQL'), OutputGuardrail(guard=polite, on_fail='retry'), ],)| Parameter | InputGuardrail |
OutputGuardrail |
|---|---|---|
guard |
fn(prompt_text) |
fn(output) |
context_guard |
fn(ctx, prompt_text) |
fn(ctx, output) |
on_fail |
'raise' (default) or 'warn' |
'retry' (default), 'raise' or 'warn' |
label |
Name used in logs, errors and spans (defaults to the class name) | same |
Pass exactly one of guard or context_guard. Either can be sync or async.
What a check returns
Section titled “What a check returns”| Return | Meaning |
|---|---|
True or None |
Pass |
False |
Fail with a generic reason |
'some reason' |
Fail with that reason |
(passed, reason) |
Explicit result |
For output guardrails, output is the agent’s output value: a str for text agents, or your model instance when you set output_type.
2. Use the run context
Section titled “2. Use the run context”context_guard receives the RunContext, giving you deps, usage, messages and prompt:
from dataclasses import dataclass
from pydantic_ai import Agent, RunContextfrom pydantic_ai_guardrails import OutputGuardrail
@dataclassclass Deps: banned_terms: list[str]
def no_banned_terms(ctx: RunContext[Deps], output: str) -> bool | str: found = [t for t in ctx.deps.banned_terms if t in output.lower()] return f'remove these terms: {found}' if found else True
agent = Agent('openai:gpt-4o', deps_type=Deps, capabilities=[OutputGuardrail(context_guard=no_banned_terms)])result = agent.run_sync('Describe our product', deps=Deps(banned_terms=['guarantee']))3. Subclass a base class
Section titled “3. Subclass a base class”For a reusable guardrail with its own fields, subclass InputGuardrailBase or OutputGuardrailBase as a dataclass and implement check. Return a reason string to fail, or None to pass.
from dataclasses import dataclassfrom typing import Any
from pydantic_ai import Agent, RunContextfrom pydantic_ai_guardrails import InputGuardrailBase, OnInputFail, OnOutputFail, OutputGuardrailBase
@dataclassclass MaxQuestionMarks(InputGuardrailBase): limit: int = 3 on_fail: OnInputFail = 'raise'
async def check(self, ctx: RunContext[Any], text: str) -> str | None: count = text.count('?') return f'{count} questions, ask at most {self.limit}' if count > self.limit else None
@dataclassclass Shout(OutputGuardrailBase): """Rewrite the output instead of blocking it."""
on_fail: OnOutputFail = 'retry'
async def transform(self, ctx: RunContext[Any], output: Any, text: str) -> Any: return output.upper() if isinstance(output, str) else output
agent = Agent('openai:gpt-4o', capabilities=[MaxQuestionMarks(limit=2), Shout()])The base classes handle on_fail, logging, exceptions and the OpenTelemetry span for you.
- Input:
async def check(self, ctx, text) -> str | None - Output:
async def check(self, ctx, output, text) -> str | None, and optionallyasync def transform(self, ctx, output, text) -> Any. Whentransformreturns a different object, that becomes the output andcheckis skipped.
Wrapping a third-party scanner
Section titled “Wrapping a third-party scanner”Any library that can score text can become a guardrail. See llm-guard, autoevals and pydantic-evals.
Testing
Section titled “Testing”See Testing for assert_input_blocked and friends.