Skip to content

Built-in Guardrails

Every guardrail is a capability class. Import it from pydantic_ai_guardrails and add it to Agent(capabilities=[...]). Guardrails run in list order within each stage.

Run in before_run, before the model is called. Fail with InputBlocked, or log with on_fail='warn'.

Guardrail Blocks when
DetectPII The prompt contains an email, phone, SSN, credit card or IP address
DetectPromptInjection The prompt matches injection or jailbreak patterns
DetectToxicity The prompt contains profanity, hate speech, threats or attacks
BlockKeywords The prompt contains a blocked keyword
LimitInputLength The prompt exceeds a character or token budget
RateLimit A key exceeds its request rate

Run in after_output_process, for text and structured output. Default on_fail='retry' raises ModelRetry; 'raise' raises OutputBlocked; 'warn' logs.

Guardrail Fails when
LimitOutputLength The output is outside character, word or sentence bounds
RedactSecrets Never fails: rewrites API keys and tokens to a placeholder
ValidateJson The output is not valid JSON or does not match a schema
FilterToxicity The output contains toxic language
DetectHallucination The output hedges or contains placeholder data
MatchRegex The output does not match the required patterns
BlockRefusals The output is a canned refusal
RequireToolUse The run did not call the required tools
LlmJudge A judge model scores the output below a threshold
RequireGrounding The answer’s claims aren’t supported by the run’s sources
Guardrail Effect
RestrictTools Allowlists, hides or approval-gates tools (glob patterns supported)
ValidateToolArgs Rejects tool arguments that fail a check, so the model retries
LimitCost Stops the run with BudgetExceeded once token usage or dollar cost crosses a budget

The detectors default to regex, which has no dependencies and adds almost no latency. Three can switch to an ML backend:

Guardrail Backend Extra
DetectPII backend='presidio' pii-detection
DetectToxicity, FilterToxicity backend='detoxify' toxicity-detection
DetectPromptInjection backend='transformers' prompt-injection

Unknown option names (a PII type, toxicity category or secret pattern that does not exist) raise ValueError at construction.

Need something else? Write your own with InputGuardrail, OutputGuardrail, AsyncGuardrail, or by subclassing InputGuardrailBase / OutputGuardrailBase.