Input Guardrails Example
Description: Learn how to use guardrails to check inputs and prevent unwanted behavior like doing math homework
Difficulty: advanced
Category: guardrails
Python Code Example
from __future__ import annotations
import asyncio
from pydantic import BaseModel
from agents import (
Agent,
GuardrailFunctionOutput,
InputGuardrailTripwireTriggered,
RunContextWrapper,
Runner,
TResponseInputItem,
input_guardrail,
)
"""
This example shows how to use guardrails.
Guardrails are checks that run in parallel to the agent's execution.
They can be used to do things like:
- Check if input messages are off-topic
- Check that input messages don't violate any policies
- Take over control of the agent's execution if an unexpected input is detected
In this example, we'll setup an input guardrail that trips if the user is asking to do math homework.
If the guardrail trips, we'll respond with a refusal message.
"""
### 1. An agent-based guardrail that is triggered if the user is asking to do math homework
class MathHomeworkOutput(BaseModel):
reasoning: str
is_math_homework: bool
guardrail_agent = Agent(
name="Guardrail check",
instructions="Check if the user is asking you to do their math homework.",
output_type=MathHomeworkOutput,
)
@input_guardrail
async def math_guardrail(
context: RunContextWrapper[None], agent: Agent, input: str | list[TResponseInputItem]
) -> GuardrailFunctionOutput:
"""This is an input guardrail function, which happens to call an agent to check if the input
is a math homework question.
"""
result = await Runner.run(guardrail_agent, input, context=context.context)
final_output = result.final_output_as(MathHomeworkOutput)
return GuardrailFunctionOutput(
output_info=final_output,
tripwire_triggered=final_output.is_math_homework,
)
### 2. The run loop
async def main():
agent = Agent(
name="Customer support agent",
instructions="You are a customer support agent. You help customers with their questions.",
input_guardrails=[math_guardrail],
)
# For demo purposes, we'll simulate a conversation
print("=== Guardrails Demo ===")
print("This agent will refuse to help with math homework.\n")
# Test 1: Normal question
print("Test 1: Normal question")
print("User: What's the capital of California?")
try:
result = await Runner.run(agent, "What's the capital of California?")
print(f"Assistant: {result.final_output}")
except InputGuardrailTripwireTriggered:
print("Assistant: Sorry, I can't help you with your math homework.")
print()
# Test 2: Math homework question
print("Test 2: Math homework question")
print("User: Can you help me solve for x: 2x + 5 = 11")
try:
result = await Runner.run(agent, "Can you help me solve for x: 2x + 5 = 11")
print(f"Assistant: {result.final_output}")
except InputGuardrailTripwireTriggered:
print("Assistant: Sorry, I can't help you with your math homework.")
print()
print("=== Guardrails Demo Complete ===")
if __name__ == "__main__":
asyncio.run(main())
Expected Output: Guardrail triggers for math homework, allows normal questions
About This Example
This is an interactive Python tutorial for the OpenAI Agents SDK. The code runs directly in your browser using PyOdide (Python in WebAssembly).
Key Features:
- No installation required - runs entirely in your browser
- Interactive code editor with syntax highlighting
- Real-time execution using PyOdide
- Complete OpenAI Agents SDK functionality
- Connect with GitHub Models for AI capabilities
Related Examples:
← Back to all examples
JavaScript is required to run the interactive code editor. Please enable JavaScript in your browser for the full experience.