|
| 1 | +"""Human-in-the-loop example with tool approval. |
| 2 | +
|
| 3 | +This example demonstrates how to: |
| 4 | +1. Define tools that require approval before execution |
| 5 | +2. Handle interruptions when tool approval is needed |
| 6 | +3. Serialize/deserialize run state to continue execution later |
| 7 | +4. Approve or reject tool calls based on user input |
| 8 | +""" |
| 9 | + |
| 10 | +import asyncio |
| 11 | +import json |
| 12 | + |
| 13 | +from agents import Agent, Runner, RunState, function_tool |
| 14 | + |
| 15 | + |
| 16 | +@function_tool |
| 17 | +async def get_weather(city: str) -> str: |
| 18 | + """Get the weather for a given city. |
| 19 | +
|
| 20 | + Args: |
| 21 | + city: The city to get weather for. |
| 22 | +
|
| 23 | + Returns: |
| 24 | + Weather information for the city. |
| 25 | + """ |
| 26 | + return f"The weather in {city} is sunny" |
| 27 | + |
| 28 | + |
| 29 | +async def _needs_temperature_approval(_ctx, params, _call_id) -> bool: |
| 30 | + """Check if temperature tool needs approval.""" |
| 31 | + return "Oakland" in params.get("city", "") |
| 32 | + |
| 33 | + |
| 34 | +@function_tool( |
| 35 | + # Dynamic approval: only require approval for Oakland |
| 36 | + needs_approval=_needs_temperature_approval |
| 37 | +) |
| 38 | +async def get_temperature(city: str) -> str: |
| 39 | + """Get the temperature for a given city. |
| 40 | +
|
| 41 | + Args: |
| 42 | + city: The city to get temperature for. |
| 43 | +
|
| 44 | + Returns: |
| 45 | + Temperature information for the city. |
| 46 | + """ |
| 47 | + return f"The temperature in {city} is 20° Celsius" |
| 48 | + |
| 49 | + |
| 50 | +# Main agent with tool that requires approval |
| 51 | +agent = Agent( |
| 52 | + name="Weather Assistant", |
| 53 | + instructions=( |
| 54 | + "You are a helpful weather assistant. " |
| 55 | + "Answer questions about weather and temperature using the available tools." |
| 56 | + ), |
| 57 | + tools=[get_weather, get_temperature], |
| 58 | +) |
| 59 | + |
| 60 | + |
| 61 | +async def confirm(question: str) -> bool: |
| 62 | + """Prompt user for yes/no confirmation. |
| 63 | +
|
| 64 | + Args: |
| 65 | + question: The question to ask. |
| 66 | +
|
| 67 | + Returns: |
| 68 | + True if user confirms, False otherwise. |
| 69 | + """ |
| 70 | + # Note: In a real application, you would use proper async input |
| 71 | + # For now, using synchronous input with run_in_executor |
| 72 | + loop = asyncio.get_event_loop() |
| 73 | + answer = await loop.run_in_executor(None, input, f"{question} (y/n): ") |
| 74 | + normalized = answer.strip().lower() |
| 75 | + return normalized in ("y", "yes") |
| 76 | + |
| 77 | + |
| 78 | +async def main(): |
| 79 | + """Run the human-in-the-loop example.""" |
| 80 | + result = await Runner.run( |
| 81 | + agent, |
| 82 | + "What is the weather and temperature in Oakland?", |
| 83 | + ) |
| 84 | + |
| 85 | + has_interruptions = len(result.interruptions) > 0 |
| 86 | + |
| 87 | + while has_interruptions: |
| 88 | + print("\n" + "=" * 80) |
| 89 | + print("Run interrupted - tool approval required") |
| 90 | + print("=" * 80) |
| 91 | + |
| 92 | + # Storing state to file (demonstrating serialization) |
| 93 | + state = result.to_state() |
| 94 | + state_json = state.to_json() |
| 95 | + with open("result.json", "w") as f: |
| 96 | + json.dump(state_json, f, indent=2) |
| 97 | + |
| 98 | + print("State saved to result.json") |
| 99 | + |
| 100 | + # From here on you could run things on a different thread/process |
| 101 | + |
| 102 | + # Reading state from file (demonstrating deserialization) |
| 103 | + print("Loading state from result.json") |
| 104 | + with open("result.json", "r") as f: |
| 105 | + stored_state_json = json.load(f) |
| 106 | + |
| 107 | + state = RunState.from_json(agent, stored_state_json) |
| 108 | + |
| 109 | + # Process each interruption |
| 110 | + for interruption in result.interruptions: |
| 111 | + print(f"\nTool call details:") |
| 112 | + print(f" Agent: {interruption.agent.name}") |
| 113 | + print(f" Tool: {interruption.raw_item.name}") # type: ignore |
| 114 | + print(f" Arguments: {interruption.raw_item.arguments}") # type: ignore |
| 115 | + |
| 116 | + confirmed = await confirm("\nDo you approve this tool call?") |
| 117 | + |
| 118 | + if confirmed: |
| 119 | + print(f"✓ Approved: {interruption.raw_item.name}") |
| 120 | + state.approve(interruption) |
| 121 | + else: |
| 122 | + print(f"✗ Rejected: {interruption.raw_item.name}") |
| 123 | + state.reject(interruption) |
| 124 | + |
| 125 | + # Resume execution with the updated state |
| 126 | + print("\nResuming agent execution...") |
| 127 | + result = await Runner.run(agent, state) |
| 128 | + has_interruptions = len(result.interruptions) > 0 |
| 129 | + |
| 130 | + print("\n" + "=" * 80) |
| 131 | + print("Final Output:") |
| 132 | + print("=" * 80) |
| 133 | + print(result.final_output) |
| 134 | + |
| 135 | + |
| 136 | +if __name__ == "__main__": |
| 137 | + asyncio.run(main()) |
0 commit comments