JSON & YAML Config
Describe a guardrail set in a file and build it at startup. This keeps policy (which guardrails, what limits) out of your code, so it can change per environment.
Format
Section titled “Format”version: 1guardrails: - type: DetectPromptInjection config: {sensitivity: high} - type: DetectPII config: {types: [ssn, credit_card]} - type: LimitOutputLength config: {min_chars: 10, on_fail: retry} - type: RestrictTools config: {allowed: ['github_*'], blocked: ['github_delete_*']} - type: LimitCost config: {max_total_tokens: 50000}{ "version": 1, "guardrails": [ {"type": "DetectPII", "config": {"types": ["ssn", "credit_card"]}}, {"type": "LimitCost", "config": {"max_total_tokens": 50000}} ]}Each entry has a type (a guardrail class name) and an optional config mapping of its constructor arguments. version must be 1.
Loading
Section titled “Loading”from pydantic_ai import Agentfrom pydantic_ai_guardrails import build_guardrails, load_config
agent = Agent('openai:gpt-4o', capabilities=build_guardrails(load_config('guardrails.yaml')))load_config(path)reads.json,.yamlor.yml. YAML needs PyYAML:pip install 'pydantic-ai-guardrails[yaml]'.build_guardrails(config)accepts the loadedGuardrailConfigor a plain dict, and returns a list of capabilities.
Mix config-built and code-built guardrails freely:
from pydantic_ai import Agentfrom pydantic_ai_guardrails import OutputGuardrail, build_guardrails, load_config
agent = Agent( 'openai:gpt-4o', capabilities=[ *build_guardrails(load_config('guardrails.yaml')), OutputGuardrail(guard=lambda out: 'TODO' not in out), ],)Supported types
Section titled “Supported types”| Kind | Types |
|---|---|
| Input | DetectPII, DetectPromptInjection, DetectToxicity, BlockKeywords, LimitInputLength, RateLimit |
| Output | LimitOutputLength, RedactSecrets, ValidateJson, FilterToxicity, DetectHallucination, MatchRegex, BlockRefusals, RequireToolUse, LlmJudge |
| Tool and cost | RestrictTools (without approval), LimitCost |
These take callables, so they are code-only: ValidateToolArgs, AsyncGuardrail, InputGuardrail, OutputGuardrail, and RestrictTools with an approval callback. The same goes for RateLimit(key=...): a config-built RateLimit uses one global bucket.
Validation
Section titled “Validation”build_guardrails validates the config and raises a ValueError that names the guardrail for:
- an unknown
type(the message lists the known types) - an unknown key in an entry, or an unknown parameter in
config - an invalid value, such as an unknown PII type or toxicity category
- a
versionother than1
from pydantic_ai_guardrails import build_guardrails
try: build_guardrails({'version': 1, 'guardrails': [{'type': 'DetectPII', 'config': {'types': ['passport']}}]})except ValueError as e: print(e)Build the guardrails at startup so a bad config fails the deploy, not the first request.