Skip to content

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.

guardrails.yaml
version: 1
guardrails:
- 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.

from pydantic_ai import Agent
from 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, .yaml or .yml. YAML needs PyYAML: pip install 'pydantic-ai-guardrails[yaml]'.
  • build_guardrails(config) accepts the loaded GuardrailConfig or a plain dict, and returns a list of capabilities.

Mix config-built and code-built guardrails freely:

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

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 version other than 1
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.