Skip to main content
Output guardrails validate agent responses before they reach users or other agents. When a guardrail trips, the agent receives feedback and retries.

Function Signature

Each output guardrail receives three parameters:
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 when output_type is set.
Return:
  • GuardrailFunctionOutput with:
    • tripwire_triggered (bool): True if validation failed.
    • output_info (str): Feedback message sent to the agent when tripwire_triggered=True.

Basic Output Guardrail

Practical Example: Preventing Sensitive Information Leaks

See the full example at 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. The validation_attempts parameter controls this behavior.

How Retry Works

1

Agent generates response

The agent produces its initial response.
2

Output guardrail checks response

Each output guardrail validates the response.
3

If validation fails

The agent receives a system message containing the guardrail output_info.
4

Agent retries

The agent generates a new response, informed by that message.
5

Repeat until success or limit reached

This cycle continues up to validation_attempts times.
6

If all attempts fail

OutputGuardrailTripwireTriggered is raised.

Configure validation_attempts

SettingBehavior
validation_attempts=0Fail-fast (no retry, immediate exception)
validation_attempts=1Default (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 with message_origin="output_guardrail_error". For most use cases, role, content, and message_origin are enough. Extra metadata is mainly for debugging and run tracing.
OriginMeaning
output_guardrail_errorOutput guardrail failure (system message)

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.
In this example:
  • 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).