|
1 | 1 | from __future__ import annotations |
2 | 2 |
|
3 | 3 | import asyncio |
4 | | - |
5 | 4 | from agents import Agent, Runner, function_tool |
6 | 5 | from agents.exceptions import UserError |
7 | 6 |
|
| 7 | + |
8 | 8 | """ |
9 | | -This example demonstrates an OpenAI Agents SDK agent that triggers a UserError due to incorrect SDK usage. |
| 9 | +This example demonstrates raising a `UserError` at runtime by violating a tool-specific logic rule |
| 10 | +(e.g., returning the wrong type despite declaring a valid return type). |
10 | 11 |
|
11 | | -The 'Assistant' agent is configured with an invalid `tool_use_behavior` (empty string) and an invalid tool (`invalid_tool`) that declares a `None` return type but returns a string. Either issue raises a `UserError` when the agent is executed, indicating improper SDK configuration by the user. The interactive loop processes user queries as direct string inputs, catching and displaying the `UserError` message. |
| 12 | +This passes `mypy` but fails at runtime due to logical misuse of the SDK. |
12 | 13 | """ |
13 | 14 |
|
14 | 15 |
|
15 | 16 | @function_tool |
16 | 17 | def invalid_tool() -> None: |
17 | | - return "I return a string" # Type mismatch triggers UserError |
| 18 | + # This tool *claims* to return None, but it returns a string instead. |
| 19 | + # This misuse is caught by the SDK during runtime and raises UserError. |
| 20 | + return "This return violates the declared return type." |
18 | 21 |
|
19 | 22 |
|
20 | 23 | async def main(): |
21 | 24 | agent = Agent( |
22 | 25 | name="Assistant", |
23 | | - instructions="Use the invalid_tool to process queries.", |
| 26 | + instructions="Use the tool to demonstrate misuse.", |
24 | 27 | tools=[invalid_tool], |
25 | | - tool_use_behavior="invalid_tool", |
| 28 | + tool_use_behavior="run_llm_again", # ✅ valid value — no mypy error |
26 | 29 | ) |
27 | | - user_input = "Do Something." |
| 30 | + |
| 31 | + user_input = "Please do something invalid" |
28 | 32 | try: |
29 | 33 | result = await Runner.run(agent, user_input) |
30 | 34 | print(result.final_output) |
31 | 35 | except UserError as e: |
32 | | - print(f"UserError: {e}") |
| 36 | + print(f"UserError caught as expected: {e}") |
33 | 37 |
|
34 | 38 |
|
35 | 39 | if __name__ == "__main__": |
|
0 commit comments