Skip to content

Input Guardrails

Input guardrails run in the before_run hook, before the first model request. A failing check stops the run, so a blocked prompt costs no tokens.

from pydantic_ai import Agent
from pydantic_ai_guardrails import (
BlockKeywords,
DetectPII,
DetectPromptInjection,
InputBlocked,
LimitInputLength,
)
agent = Agent(
'openai:gpt-4o',
capabilities=[
LimitInputLength(max_chars=4000), # cheapest checks first
BlockKeywords(['internal-only']),
DetectPromptInjection(),
DetectPII(),
],
)
try:
result = agent.run_sync('My email is jane@corp.com, can you help?')
except InputBlocked as e:
print(f'{e.guardrail}: {e.reason}') # DetectPII: detected PII: email

Input guardrails run in list order and the first failure stops the run. Put cheap checks first.

on_fail Effect
'raise' (default) Raise InputBlocked with .guardrail and .reason
'warn' Log a warning to the pydantic_ai_guardrails logger and continue

'warn' is a safe way to roll out a new guardrail: deploy it, watch the logs (or the OpenTelemetry spans) for false positives, then switch to 'raise'.

import logging
from pydantic_ai_guardrails import DetectPromptInjection
logging.basicConfig()
DetectPromptInjection(sensitivity='high', on_fail='warn')

Input guardrails receive the RunContext, so a custom check can read deps:

from dataclasses import dataclass
from pydantic_ai import Agent, RunContext
from pydantic_ai_guardrails import InputGuardrail
@dataclass
class Deps:
is_admin: bool
def admins_only_for_exports(ctx: RunContext[Deps], text: str) -> bool | str:
if 'export' in text.lower() and not ctx.deps.is_admin:
return 'only admins can request exports'
return True
agent = Agent(
'openai:gpt-4o',
deps_type=Deps,
capabilities=[InputGuardrail(context_guard=admins_only_for_exports)],
)

DetectPII, DetectPromptInjection, DetectToxicity, BlockKeywords, LimitInputLength, RateLimit.