|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import asyncio |
| 4 | +import json |
| 5 | + |
| 6 | +from pydantic import BaseModel, Field |
| 7 | + |
| 8 | +from agents import ( |
| 9 | + Agent, |
| 10 | + GuardrailFunctionOutput, |
| 11 | + OutputGuardrailTripwireTriggered, |
| 12 | + RunContextWrapper, |
| 13 | + Runner, |
| 14 | + output_guardrail, |
| 15 | +) |
| 16 | + |
| 17 | +""" |
| 18 | +This example shows how to use output guardrails. |
| 19 | +
|
| 20 | +Output guardrails are checks that run on the final output of an agent. |
| 21 | +They can be used to do things like: |
| 22 | +- Check if the output contains sensitive data |
| 23 | +- Check if the output is a valid response to the user's message |
| 24 | +
|
| 25 | +In this example, we'll use a (contrived) example where we check if the agent's response contains |
| 26 | +a phone number. |
| 27 | +""" |
| 28 | + |
| 29 | + |
| 30 | +# The agent's output type |
| 31 | +class MessageOutput(BaseModel): |
| 32 | + reasoning: str = Field(description="Thoughts on how to respond to the user's message") |
| 33 | + response: str = Field(description="The response to the user's message") |
| 34 | + user_name: str | None = Field(description="The name of the user who sent the message, if known") |
| 35 | + |
| 36 | + |
| 37 | +@output_guardrail |
| 38 | +async def sensitive_data_check( |
| 39 | + context: RunContextWrapper, agent: Agent, output: MessageOutput |
| 40 | +) -> GuardrailFunctionOutput: |
| 41 | + phone_number_in_response = "650" in output.response |
| 42 | + phone_number_in_reasoning = "650" in output.reasoning |
| 43 | + |
| 44 | + return GuardrailFunctionOutput( |
| 45 | + output_info={ |
| 46 | + "phone_number_in_response": phone_number_in_response, |
| 47 | + "phone_number_in_reasoning": phone_number_in_reasoning, |
| 48 | + }, |
| 49 | + tripwire_triggered=phone_number_in_response or phone_number_in_reasoning, |
| 50 | + ) |
| 51 | + |
| 52 | + |
| 53 | +agent = Agent( |
| 54 | + name="Assistant", |
| 55 | + instructions="You are a helpful assistant.", |
| 56 | + output_type=MessageOutput, |
| 57 | + output_guardrails=[sensitive_data_check], |
| 58 | +) |
| 59 | + |
| 60 | + |
| 61 | +async def output_guardrails_agent(): |
| 62 | + # This should be ok |
| 63 | + await Runner.run(agent, "What's the capital of California?") |
| 64 | + print("First message passed") |
| 65 | + |
| 66 | + # This should trip the guardrail |
| 67 | + try: |
| 68 | + result = await Runner.run( |
| 69 | + agent, "My phone number is 650-123-4567. Where do you think I live?" |
| 70 | + ) |
| 71 | + print( |
| 72 | + f"Guardrail didn't trip - this is unexpected. Output: {json.dumps(result.final_output.model_dump(), indent=2)}" |
| 73 | + ) |
| 74 | + |
| 75 | + except OutputGuardrailTripwireTriggered as e: |
| 76 | + print(f"Guardrail tripped. Info: {e.guardrail_result.output.output_info}") |
| 77 | + |
0 commit comments