Skip to content

Custom Guardrails

There are three ways to add your own check, from least to most code.

InputGuardrail and OutputGuardrail wrap a function you supply.

from pydantic_ai import Agent
from 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.

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.

context_guard receives the RunContext, giving you deps, usage, messages and prompt:

from dataclasses import dataclass
from pydantic_ai import Agent, RunContext
from pydantic_ai_guardrails import OutputGuardrail
@dataclass
class 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']))

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 dataclass
from typing import Any
from pydantic_ai import Agent, RunContext
from pydantic_ai_guardrails import InputGuardrailBase, OnInputFail, OnOutputFail, OutputGuardrailBase
@dataclass
class 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
@dataclass
class 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 optionally async def transform(self, ctx, output, text) -> Any. When transform returns a different object, that becomes the output and check is skipped.

Any library that can score text can become a guardrail. See llm-guard, autoevals and pydantic-evals.

See Testing for assert_input_blocked and friends.