apply_guardrail runs a single LLM-backed content check and, since it fails closed by default, blocks content whenever the check itself cannot complete.
on_error.
Quick Start
1
Use it as an agent guardrail
Wrap
apply_guardrail in a validator and pass it to guardrails=.2
Call it directly
Run a one-off check on any string.
3
Await the async twin
Use
aapply_guardrail inside an event loop.How It Works
The check runs an LLM against your rules and returns aGuardrailResult. Any failure inside the check is routed through on_error.
Choosing on_error
on_error decides what happens when the check itself cannot produce a valid decision.
Parameters
aapply_guardrail takes the same parameters and returns the same GuardrailResult.
GuardrailResult
Both functions return aGuardrailResult.
Common Patterns
Restore the old permissive behaviour
Handle the error yourself
Compose with an agent
Best Practices
Keep the fail-closed default in production
Keep the fail-closed default in production
The
"block" default protects you when the check LLM is rate-limited or returns malformed output. Only switch to "allow" when availability outranks safety for that specific check.Pass explicit rules
Pass explicit rules
Naming your rules (
rules=["no_pii", "no_profanity"]) gives the check LLM a clear contract. With no rules, the built-in PII / profanity / harm / misinformation set is used.Use the async twin inside event loops
Use the async twin inside event loops
Call
aapply_guardrail from async code so the check does not block the event loop. Use the sync apply_guardrail from plain scripts.Inspect violations on block
Inspect violations on block
When blocked, read
result.violations — a failed check surfaces {"reason": "guardrail_unavailable", "error": "..."} so you can tell a policy violation apart from an outage.Related
Guardrails
Agent-level output validation with automatic retry
Capabilities
Full inventory of capability helpers
Async Tool Safety
Non-blocking safety checks in async agents
Persistence Overview
Store architecture and backends

