|
| 1 | +""" |
| 2 | +Example demonstrating SQLite in-memory session with human-in-the-loop (HITL) tool approval. |
| 3 | +
|
| 4 | +This example shows how to use SQLite in-memory session memory combined with |
| 5 | +human-in-the-loop tool approval. The session maintains conversation history while |
| 6 | +requiring approval for specific tool calls. |
| 7 | +""" |
| 8 | + |
| 9 | +import asyncio |
| 10 | + |
| 11 | +from agents import Agent, Runner, SQLiteSession, function_tool |
| 12 | + |
| 13 | + |
| 14 | +async def _needs_approval(_ctx, _params, _call_id) -> bool: |
| 15 | + """Always require approval for weather tool.""" |
| 16 | + return True |
| 17 | + |
| 18 | + |
| 19 | +@function_tool(needs_approval=_needs_approval) |
| 20 | +def get_weather(location: str) -> str: |
| 21 | + """Get weather for a location. |
| 22 | +
|
| 23 | + Args: |
| 24 | + location: The location to get weather for |
| 25 | +
|
| 26 | + Returns: |
| 27 | + Weather information as a string |
| 28 | + """ |
| 29 | + # Simulated weather data |
| 30 | + weather_data = { |
| 31 | + "san francisco": "Foggy, 58°F", |
| 32 | + "oakland": "Sunny, 72°F", |
| 33 | + "new york": "Rainy, 65°F", |
| 34 | + } |
| 35 | + # Check if any city name is in the provided location string |
| 36 | + location_lower = location.lower() |
| 37 | + for city, weather in weather_data.items(): |
| 38 | + if city in location_lower: |
| 39 | + return weather |
| 40 | + return f"Weather data not available for {location}" |
| 41 | + |
| 42 | + |
| 43 | +async def prompt_yes_no(question: str) -> bool: |
| 44 | + """Prompt user for yes/no answer. |
| 45 | +
|
| 46 | + Args: |
| 47 | + question: The question to ask |
| 48 | +
|
| 49 | + Returns: |
| 50 | + True if user answered yes, False otherwise |
| 51 | + """ |
| 52 | + print(f"\n{question} (y/n): ", end="", flush=True) |
| 53 | + loop = asyncio.get_event_loop() |
| 54 | + answer = await loop.run_in_executor(None, input) |
| 55 | + normalized = answer.strip().lower() |
| 56 | + return normalized in ("y", "yes") |
| 57 | + |
| 58 | + |
| 59 | +async def main(): |
| 60 | + # Create an agent with a tool that requires approval |
| 61 | + agent = Agent( |
| 62 | + name="HITL Assistant", |
| 63 | + instructions="You help users with information. Always use available tools when appropriate. Keep responses concise.", |
| 64 | + tools=[get_weather], |
| 65 | + ) |
| 66 | + |
| 67 | + # Create an in-memory SQLite session instance that will persist across runs |
| 68 | + session = SQLiteSession(":memory:") |
| 69 | + session_id = session.session_id |
| 70 | + |
| 71 | + print("=== Memory Session + HITL Example ===") |
| 72 | + print(f"Session id: {session_id}") |
| 73 | + print("Enter a message to chat with the agent. Submit an empty line to exit.") |
| 74 | + print("The agent will ask for approval before using tools.\n") |
| 75 | + |
| 76 | + while True: |
| 77 | + # Get user input |
| 78 | + print("You: ", end="", flush=True) |
| 79 | + loop = asyncio.get_event_loop() |
| 80 | + user_message = await loop.run_in_executor(None, input) |
| 81 | + |
| 82 | + if not user_message.strip(): |
| 83 | + break |
| 84 | + |
| 85 | + # Run the agent |
| 86 | + result = await Runner.run(agent, user_message, session=session) |
| 87 | + |
| 88 | + # Handle interruptions (tool approvals) |
| 89 | + while result.interruptions: |
| 90 | + # Get the run state |
| 91 | + state = result.to_state() |
| 92 | + |
| 93 | + for interruption in result.interruptions: |
| 94 | + tool_name = interruption.raw_item.name # type: ignore[union-attr] |
| 95 | + args = interruption.raw_item.arguments or "(no arguments)" # type: ignore[union-attr] |
| 96 | + |
| 97 | + approved = await prompt_yes_no( |
| 98 | + f"Agent {interruption.agent.name} wants to call '{tool_name}' with {args}. Approve?" |
| 99 | + ) |
| 100 | + |
| 101 | + if approved: |
| 102 | + state.approve(interruption) |
| 103 | + print("Approved tool call.") |
| 104 | + else: |
| 105 | + state.reject(interruption) |
| 106 | + print("Rejected tool call.") |
| 107 | + |
| 108 | + # Resume the run with the updated state |
| 109 | + result = await Runner.run(agent, state, session=session) |
| 110 | + |
| 111 | + # Display the response |
| 112 | + reply = result.final_output or "[No final output produced]" |
| 113 | + print(f"Assistant: {reply}\n") |
| 114 | + |
| 115 | + |
| 116 | +if __name__ == "__main__": |
| 117 | + asyncio.run(main()) |
0 commit comments