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 Agentfrom 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: emailInput guardrails run in list order and the first failure stops the run. Put cheap checks first.
Failure modes
Section titled “Failure modes”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')Using run context
Section titled “Using run context”Input guardrails receive the RunContext, so a custom check can read deps:
from dataclasses import dataclass
from pydantic_ai import Agent, RunContextfrom pydantic_ai_guardrails import InputGuardrail
@dataclassclass 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)],)Built-in input guardrails
Section titled “Built-in input guardrails”DetectPII, DetectPromptInjection, DetectToxicity, BlockKeywords, LimitInputLength, RateLimit.