BaseGuardrail
TheBaseGuardrail class is the abstract base for all guardrail implementations.
Implementation
check()
Synchronous guardrail check.async_check()
Asynchronous guardrail check.Usage with Agents
Guardrails can be added as pre_hooks or post_hooks:Example Guardrails
RunInput Structure
TheRunInput object passed to guardrails contains:
message: The input messageuser_id: User ID (if provided)session_id: Session ID (if provided)run_response: The response (for post_hooks)- Other run parameters
Best Practices
- Fast checks: Keep guardrail checks fast to avoid latency
- Clear errors: Provide clear error messages when blocking
- Logging: Log blocked requests for monitoring
- Async: Implement async_check for I/O operations
- Order matters: Cheaper checks first (length before API calls)
- Testing: Thoroughly test guardrails with edge cases
- Monitoring: Track how often guardrails trigger
Use Cases
- Content moderation
- PII detection and blocking
- Rate limiting
- Input validation
- Output sanitization
- Compliance enforcement
- Cost control (token limits)
- Policy enforcement