| 5 | |
| 6 | |
| 7 | async def main(): |
| 8 | # Create an agent |
| 9 | agent = Agent( |
| 10 | name="Assistant", |
| 11 | instructions="Reply very concisely.", |
| 12 | ) |
| 13 | |
| 14 | # Create a session instance with a session ID. |
| 15 | # This example uses an in-memory SQLite database. |
| 16 | # The `create_tables=True` flag is useful for development and testing. |
| 17 | session = SQLAlchemySession.from_url( |
| 18 | "conversation_123", |
| 19 | url="sqlite+aiosqlite:///:memory:", |
| 20 | create_tables=True, |
| 21 | ) |
| 22 | |
| 23 | print("=== Session Example ===") |
| 24 | print("The agent will remember previous messages automatically.\n") |
| 25 | |
| 26 | # First turn |
| 27 | print("First turn:") |
| 28 | print("User: What city is the Golden Gate Bridge in?") |
| 29 | result = await Runner.run( |
| 30 | agent, |
| 31 | "What city is the Golden Gate Bridge in?", |
| 32 | session=session, |
| 33 | ) |
| 34 | print(f"Assistant: {result.final_output}") |
| 35 | print() |
| 36 | |
| 37 | # Second turn - the agent will remember the previous conversation |
| 38 | print("Second turn:") |
| 39 | print("User: What state is it in?") |
| 40 | result = await Runner.run(agent, "What state is it in?", session=session) |
| 41 | print(f"Assistant: {result.final_output}") |
| 42 | print() |
| 43 | |
| 44 | # Third turn - continuing the conversation |
| 45 | print("Third turn:") |
| 46 | print("User: What's the population of that state?") |
| 47 | result = await Runner.run( |
| 48 | agent, |
| 49 | "What's the population of that state?", |
| 50 | session=session, |
| 51 | ) |
| 52 | print(f"Assistant: {result.final_output}") |
| 53 | print() |
| 54 | |
| 55 | print("=== Conversation Complete ===") |
| 56 | print("Notice how the agent remembered the context from previous turns!") |
| 57 | print("Sessions automatically handles conversation history.") |
| 58 | |
| 59 | # Demonstrate the limit parameter - get only the latest 2 items |
| 60 | print("\n=== Latest Items Demo ===") |
| 61 | latest_items = await session.get_items(limit=2) |
| 62 | print("Latest 2 items:") |
| 63 | for i, msg in enumerate(latest_items, 1): |
| 64 | role = msg.get("role", "unknown") |