SQLite Memory Example
Description: Build an agent with persistent memory using SQLite sessions
Difficulty: intermediate
Category: memory
Python Code Example
"""
Example demonstrating session memory functionality.
This example shows how to use session memory to maintain conversation history
across multiple agent runs without manually handling .to_input_list().
"""
import asyncio
from agents import Agent, Runner, SQLiteSession
async def main():
# Create an agent
agent = Agent(
name="Assistant",
instructions="Reply very concisely.",
)
# Create a session instance that will persist across runs
session_id = "conversation_123"
session = SQLiteSession(session_id)
print("=== Session Example ===")
print("The agent will remember previous messages automatically.\n")
# First turn
print("First turn:")
print("User: What city is the Golden Gate Bridge in?")
result = await Runner.run(
agent,
"What city is the Golden Gate Bridge in?",
session=session,
)
print(f"Assistant: {result.final_output}")
print()
# Second turn - the agent will remember the previous conversation
print("Second turn:")
print("User: What state is it in?")
result = await Runner.run(agent, "What state is it in?", session=session)
print(f"Assistant: {result.final_output}")
print()
# Third turn - continuing the conversation
print("Third turn:")
print("User: What's the population of that state?")
result = await Runner.run(
agent,
"What's the population of that state?",
session=session,
)
print(f"Assistant: {result.final_output}")
print()
print("=== Conversation Complete ===")
print("Notice how the agent remembered the context from previous turns!")
print("Sessions automatically handles conversation history.")
# Demonstrate the limit parameter - get only the latest 2 items
print("\n=== Latest Items Demo ===")
latest_items = await session.get_items(limit=2)
print("Latest 2 items:")
for i, msg in enumerate(latest_items, 1):
role = msg.get("role", "unknown")
content = msg.get("content", "")
print(f" {i}. {role}: {content}")
print(f"\nFetched {len(latest_items)} out of total conversation history.")
# Get all items to show the difference
all_items = await session.get_items()
print(f"Total items in session: {len(all_items)}")
if __name__ == "__main__":
asyncio.run(main())
Expected Output: Multi-turn conversation with memory persistence
About This Example
This is an interactive Python tutorial for the OpenAI Agents SDK. The code runs directly in your browser using PyOdide (Python in WebAssembly).
Key Features:
- No installation required - runs entirely in your browser
- Interactive code editor with syntax highlighting
- Real-time execution using PyOdide
- Complete OpenAI Agents SDK functionality
- Connect with GitHub Models for AI capabilities
Related Examples:
← Back to all examples
JavaScript is required to run the interactive code editor. Please enable JavaScript in your browser for the full experience.