Function Signature
Each output guardrail receives three parameters:context: Run context wrapper with access to shared state.agent: The Agent instance generating the response.response_text: The agent response as a string, or a structured model whenoutput_typeis set.
GuardrailFunctionOutputwith:tripwire_triggered(bool):Trueif validation failed.output_info(str): Feedback message sent to the agent whentripwire_triggered=True.
Basic Output Guardrail
Practical Example: Preventing Sensitive Information Leaks
examples/guardrails_output.py.
Example: Simple Format Enforcement
Output Guardrail Retry Flow
When an output guardrail trips, the agent gets multiple chances to fix its response. Thevalidation_attempts parameter controls this behavior.
How Retry Works
Configure validation_attempts
| Setting | Behavior |
|---|---|
validation_attempts=0 | Fail-fast (no retry, immediate exception) |
validation_attempts=1 | Default (one retry after initial failure) |
validation_attempts=2+ | Multiple retries for more complex validations |
Each retry sends the guardrail
output_info message to the agent as a system message, giving the agent context to adjust its response.Handling Validation Failures
Message History
Output guardrail failures are stored as system messages withmessage_origin="output_guardrail_error".
For most use cases, role, content, and message_origin are enough. Extra metadata is mainly for debugging and run tracing.
| Origin | Meaning |
|---|---|
output_guardrail_error | Output guardrail failure (system message) |
Example history entry (with debug metadata)
Example history entry (with debug metadata)
Agent-to-Agent Validation
Use guardrails to control how agents communicate with each other. When adding communication flows between agents, the recipient agent’s guardrails define the message format.Example: Task/Response contract between agents
Example: Task/Response contract between agents
- If the CEO sends a message that does not start with
Task:, the worker input guardrail triggers. - The CEO receives an error and adjusts its message.
- The worker output guardrail enforces
Response:in returned messages.
Agent-to-agent messages are always single strings, so input guardrails for inter-agent communication receive a string (not a list).