Skip to content

Commit e0f2b46

Browse files
committed
Examples and tests for previous_response_id
1 parent d622605 commit e0f2b46

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed
+66
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
import asyncio
2+
3+
from agents import Agent, Runner
4+
5+
"""This demonstrates usage of the `previous_response_id` parameter to continue a conversation.
6+
The second run passes the previous response ID to the model, which allows it to continue the
7+
conversation without re-sending the previous messages.
8+
9+
Notes:
10+
1. This only applies to the OpenAI Responses API. Other models will ignore this parameter.
11+
2. Responses are only stored for 30 days as of this writing, so in production you should
12+
store the response ID along with an expiration date; if the response is no longer valid,
13+
you'll need to re-send the previous conversation history.
14+
"""
15+
16+
17+
async def main():
18+
agent = Agent(
19+
name="Assistant",
20+
instructions="You are a helpful assistant. be VERY concise.",
21+
)
22+
23+
result = await Runner.run(agent, "What is the largest country in South America?")
24+
print(result.final_output)
25+
# Brazil
26+
27+
result = await Runner.run(
28+
agent,
29+
"What is the capital of that country?",
30+
previous_response_id=result.last_response_id,
31+
)
32+
print(result.final_output)
33+
# Brasilia
34+
35+
36+
async def main_stream():
37+
agent = Agent(
38+
name="Assistant",
39+
instructions="You are a helpful assistant. be VERY concise.",
40+
)
41+
42+
result = Runner.run_streamed(agent, "What is the largest country in South America?")
43+
44+
async for event in result.stream_events():
45+
if event.type == "raw_response_event" and event.data.type == "response.output_text.delta":
46+
print(event.data.delta, end="", flush=True)
47+
48+
print()
49+
50+
result = Runner.run_streamed(
51+
agent,
52+
"What is the capital of that country?",
53+
previous_response_id=result.last_response_id,
54+
)
55+
56+
async for event in result.stream_events():
57+
if event.type == "raw_response_event" and event.data.type == "response.output_text.delta":
58+
print(event.data.delta, end="", flush=True)
59+
60+
61+
if __name__ == "__main__":
62+
is_stream = input("Run in stream mode? (y/n): ")
63+
if is_stream == "y":
64+
asyncio.run(main_stream())
65+
else:
66+
asyncio.run(main())

0 commit comments

Comments
 (0)