Output Guardrails
Guardrails intercept AI responses before they are sent to text-to-speech. When a response matches a guardrail, it is replaced with a safe alternative. This prevents the agent from saying things it should not.Creating a Guardrail
Use theguardrail() static method:
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
name | str | required | Identifier used in log warnings when the guardrail fires. |
blocked_terms | list[str] | None | None | List of words or phrases. Any case-insensitive match blocks the response. |
check | Callable[[str], bool] | None | None | Custom function that receives the response text and returns True to block it. Evaluated after blocked_terms. |
replacement | str | "I'm sorry, I can't respond to that." | What the agent says instead when the response is blocked. |
How Guardrails Work
- The AI generates a response.
- Each guardrail is evaluated in order:
- blocked_terms: If any term appears in the response (case-insensitive substring match), the response is blocked.
- check: If the callable returns
True, the response is blocked.
- If blocked, the
replacementtext is sent to TTS instead. - A warning is logged with the guardrail
name.
Blocked Terms
The simplest way to filter responses. Terms are matched as case-insensitive substrings:Custom Check Function
For more complex logic, provide acheck callable:
check function receives the full response text and should return True to block.
Combining Terms and Checks
You can use bothblocked_terms and check on the same guardrail. The blocked terms are evaluated first; if they don’t match, the check function is called:
Multiple Guardrails
Pass a list of guardrails to the agent. They are evaluated in order — the first match wins:Complete Example
Guardrails are a defense-in-depth measure. Always include behavioral constraints in the
system_prompt as well. Guardrails catch cases where the AI ignores prompt instructions.
