Skip to content

Commit 889c203

Browse files
committed
Copy memory/openai_session_example.py sample over from OpenAI SDK
1 parent fe83da2 commit 889c203

File tree

1 file changed

+78
-0
lines changed

1 file changed

+78
-0
lines changed
Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
"""
2+
Example demonstrating session memory functionality.
3+
4+
This example shows how to use session memory to maintain conversation history
5+
across multiple agent runs without manually handling .to_input_list().
6+
"""
7+
8+
import asyncio
9+
10+
from agents import Agent, OpenAIConversationsSession, Runner
11+
12+
13+
async def main():
14+
# Create an agent
15+
agent = Agent(
16+
name="Assistant",
17+
instructions="Reply very concisely.",
18+
)
19+
20+
# Create a session instance that will persist across runs
21+
session = OpenAIConversationsSession()
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_items)
63+
print("Latest 2 items:")
64+
for i, msg in enumerate(latest_items, 1):
65+
role = msg.get("role", "unknown")
66+
content = msg.get("content", "")
67+
print(f" {i}. {role}: {content}")
68+
69+
print(f"\nFetched {len(latest_items)} out of total conversation history.")
70+
71+
# Get all items to show the difference
72+
all_items = await session.get_items()
73+
# print(all_items)
74+
print(f"Total items in session: {len(all_items)}")
75+
76+
77+
if __name__ == "__main__":
78+
asyncio.run(main())

0 commit comments

Comments
 (0)