Guardrails
Validation and safety mechanisms for agent outputs. Supports function-based, LLM-based, and preset guardrails.Quick Start
Feature Usage Table
| Feature | Usage | Example |
|---|---|---|
| String preset | guardrails="strict" | Use predefined config |
| Array + overrides | guardrails=["strict", {"max_retries": 10}] | Preset with customization |
| LLM prompt | guardrails="Ensure response is safe..." | Natural language validation |
| Callable | guardrails=my_validator_fn | Function (output) -> (bool, result) |
| Config instance | guardrails=GuardrailConfig(...) | Full control |
| Policy strings | guardrails=["policy:strict", "pii:redact"] | Policy-based validation |
Presets & Options
| Preset | max_retries | on_fail | Description |
|---|---|---|---|
"strict" | 5 | raise | Fail hard on validation errors |
"permissive" | 1 | skip | Skip on failure, continue |
"safety" | 3 | retry | Retry on failure |
Precedence Ladder
Resolution Order: Instance > Config > Array > Dict > String > Bool > DefaultWhen you pass
guardrails=, the resolver checks in this order:- Callable - Function? Use as validator
- Config - GuardrailConfig instance? Use as-is
- Array -
["preset", {"override": value}]? Apply overrides - Dict -
{"key": value}? Convert to config - String - Preset name or LLM prompt? Look up or use as prompt
- Bool -
True? Use defaults.False? Disable
Usage Forms
String Preset
Array with Overrides
LLM Prompt (String)
Callable Function
Config Instance
Classes
GuardrailResult
Result of a guardrail validation.| Attribute | Type | Description |
|---|---|---|
success | bool | Whether check passed |
result | str | TaskOutput | Result or error message |
error | str | Error message if failed |
LLMGuardrail
LLM-powered guardrail using natural language.Common Recipes
Function-based Guardrail
LLM-based Guardrail
Multiple Guardrails
Best Practices
- Keep guardrails focused - Each guardrail should check one specific aspect
- Provide clear error messages - Help users understand why validation failed
- Use LLM guardrails for complex validation - When rules are hard to express programmatically
- Chain guardrails for multiple checks - Combine simple guardrails for comprehensive validation
- Handle errors gracefully - Guardrails should not crash the application

