-
Notifications
You must be signed in to change notification settings - Fork 3.9k
Expand file tree
/
Copy pathtest_run_impl_resume_paths.py
More file actions
334 lines (293 loc) · 11.3 KB
/
test_run_impl_resume_paths.py
File metadata and controls
334 lines (293 loc) · 11.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
import json
from typing import cast
import pytest
from openai.types.responses import ResponseFunctionToolCall, ResponseOutputMessage
import agents.run as run_module
from agents import Agent, Runner, function_tool
from agents.agent import ToolsToFinalOutputResult
from agents.items import MessageOutputItem, ModelResponse, ToolCallItem, ToolCallOutputItem
from agents.lifecycle import RunHooks
from agents.run import RunConfig
from agents.run_context import RunContextWrapper
from agents.run_internal import run_loop, turn_resolution
from agents.run_internal.run_loop import (
NextStepFinalOutput,
NextStepInterruption,
NextStepRunAgain,
ProcessedResponse,
SingleStepResult,
)
from agents.run_state import RunState
from agents.usage import Usage
from tests.fake_model import FakeModel
from tests.test_responses import get_function_tool_call, get_text_message
from tests.utils.hitl import (
make_agent,
make_context_wrapper,
make_model_and_agent,
queue_function_call_and_text,
)
from tests.utils.simple_session import SimpleListSession
@pytest.mark.asyncio
async def test_resolve_interrupted_turn_final_output_short_circuit(monkeypatch) -> None:
agent: Agent[dict[str, str]] = make_agent(model=FakeModel())
context_wrapper = make_context_wrapper()
async def fake_execute_tool_plan(*_: object, **__: object):
return [], [], [], [], [], [], []
async def fake_check_for_final_output_from_tools(*_: object, **__: object):
return ToolsToFinalOutputResult(is_final_output=True, final_output="done")
async def fake_execute_final_output(
*,
original_input,
new_response,
pre_step_items,
new_step_items,
final_output,
tool_input_guardrail_results,
tool_output_guardrail_results,
**__: object,
) -> SingleStepResult:
return SingleStepResult(
original_input=original_input,
model_response=new_response,
pre_step_items=pre_step_items,
new_step_items=new_step_items,
next_step=NextStepFinalOutput(final_output),
tool_input_guardrail_results=tool_input_guardrail_results,
tool_output_guardrail_results=tool_output_guardrail_results,
)
monkeypatch.setattr(
turn_resolution, "check_for_final_output_from_tools", fake_check_for_final_output_from_tools
)
monkeypatch.setattr(turn_resolution, "execute_final_output", fake_execute_final_output)
monkeypatch.setattr(turn_resolution, "_execute_tool_plan", fake_execute_tool_plan)
processed_response = ProcessedResponse(
new_items=[],
handoffs=[],
functions=[],
computer_actions=[],
local_shell_calls=[],
shell_calls=[],
apply_patch_calls=[],
tools_used=[],
mcp_approval_requests=[],
interruptions=[],
)
result = await run_loop.resolve_interrupted_turn(
agent=agent,
original_input="input",
original_pre_step_items=[],
new_response=ModelResponse(output=[], usage=Usage(), response_id="resp"),
processed_response=processed_response,
hooks=RunHooks(),
context_wrapper=context_wrapper,
run_config=RunConfig(),
run_state=None,
)
assert isinstance(result, SingleStepResult)
assert isinstance(result.next_step, NextStepFinalOutput)
assert result.next_step.output == "done"
@pytest.mark.asyncio
async def test_resumed_session_persistence_uses_saved_count(monkeypatch) -> None:
agent = Agent(name="resume-agent")
context_wrapper: RunContextWrapper[dict[str, str]] = RunContextWrapper(context={})
state = RunState(
context=context_wrapper,
original_input="input",
starting_agent=agent,
max_turns=1,
)
session = SimpleListSession()
raw_output = {"type": "function_call_output", "call_id": "call-1", "output": "ok"}
item_1 = ToolCallOutputItem(agent=agent, raw_item=raw_output, output="ok")
item_2 = ToolCallOutputItem(agent=agent, raw_item=dict(raw_output), output="ok")
step = SingleStepResult(
original_input="input",
model_response=ModelResponse(output=[], usage=Usage(), response_id="resp"),
pre_step_items=[],
new_step_items=[item_1, item_2],
next_step=NextStepFinalOutput("done"),
tool_input_guardrail_results=[],
tool_output_guardrail_results=[],
)
async def fake_run_single_turn(**_kwargs):
return step
monkeypatch.setattr(run_module, "run_single_turn", fake_run_single_turn)
runner = run_module.AgentRunner()
await runner.run(agent, state, session=session, run_config=RunConfig())
assert state._current_turn_persisted_item_count == 1
assert len(session.saved_items) == 1
@pytest.mark.asyncio
async def test_resumed_run_again_resets_persisted_count(monkeypatch) -> None:
agent = Agent(name="resume-agent")
context_wrapper: RunContextWrapper[dict[str, str]] = RunContextWrapper(context={})
state = RunState(
context=context_wrapper,
original_input="input",
starting_agent=agent,
max_turns=2,
)
session = SimpleListSession()
state._current_step = NextStepInterruption(interruptions=[])
state._model_responses = [
ModelResponse(output=[], usage=Usage(), response_id="resp_1"),
]
state._last_processed_response = ProcessedResponse(
new_items=[],
handoffs=[],
functions=[],
computer_actions=[],
local_shell_calls=[],
shell_calls=[],
apply_patch_calls=[],
tools_used=[],
mcp_approval_requests=[],
interruptions=[],
)
state._current_turn_persisted_item_count = 1
async def fake_resolve_interrupted_turn(**_kwargs):
return SingleStepResult(
original_input="input",
model_response=ModelResponse(output=[], usage=Usage(), response_id="resp_resume"),
pre_step_items=[],
new_step_items=[],
next_step=NextStepRunAgain(),
tool_input_guardrail_results=[],
tool_output_guardrail_results=[],
)
async def fake_run_single_turn(**_kwargs):
tool_call = cast(
ResponseFunctionToolCall,
get_function_tool_call("test_tool", "{}", call_id="call-1"),
)
tool_call_item = ToolCallItem(agent=agent, raw_item=tool_call)
tool_output_item = ToolCallOutputItem(
agent=agent,
raw_item={
"type": "function_call_output",
"call_id": "call-1",
"output": "ok",
},
output="ok",
)
message_item = MessageOutputItem(
agent=agent,
raw_item=cast(ResponseOutputMessage, get_text_message("final")),
)
return SingleStepResult(
original_input="input",
model_response=ModelResponse(
output=[get_text_message("final")],
usage=Usage(),
response_id="resp_final",
),
pre_step_items=[],
new_step_items=[tool_call_item, tool_output_item, message_item],
next_step=NextStepFinalOutput("done"),
tool_input_guardrail_results=[],
tool_output_guardrail_results=[],
)
monkeypatch.setattr(run_module, "resolve_interrupted_turn", fake_resolve_interrupted_turn)
monkeypatch.setattr(run_module, "run_single_turn", fake_run_single_turn)
runner = run_module.AgentRunner()
result = await runner.run(agent, state, session=session, run_config=RunConfig())
assert result.final_output == "done"
saved_types = [
item.get("type") if isinstance(item, dict) else getattr(item, "type", None)
for item in session.saved_items
]
assert "function_call" in saved_types
@pytest.mark.parametrize(
("conversation_id", "previous_response_id", "auto_previous_response_id"),
[
("conv_1", None, False),
(None, "resp_prev", False),
(None, None, True),
],
)
@pytest.mark.asyncio
async def test_resumed_interruption_passes_server_managed_conversation_flag(
monkeypatch: pytest.MonkeyPatch,
conversation_id: str | None,
previous_response_id: str | None,
auto_previous_response_id: bool,
) -> None:
agent = Agent(name="resume-agent")
context_wrapper: RunContextWrapper[dict[str, str]] = RunContextWrapper(context={})
state = RunState(
context=context_wrapper,
original_input="input",
starting_agent=agent,
max_turns=1,
conversation_id=conversation_id,
previous_response_id=previous_response_id,
auto_previous_response_id=auto_previous_response_id,
)
state._current_step = NextStepInterruption(interruptions=[])
state._model_responses = [
ModelResponse(output=[], usage=Usage(), response_id="resp_1"),
]
state._last_processed_response = ProcessedResponse(
new_items=[],
handoffs=[],
functions=[],
computer_actions=[],
local_shell_calls=[],
shell_calls=[],
apply_patch_calls=[],
tools_used=[],
mcp_approval_requests=[],
interruptions=[],
)
server_managed_values: list[bool] = []
async def fake_resolve_interrupted_turn(**kwargs: object) -> SingleStepResult:
server_managed_values.append(cast(bool, kwargs["server_manages_conversation"]))
return SingleStepResult(
original_input="input",
model_response=ModelResponse(output=[], usage=Usage(), response_id="resp_resume"),
pre_step_items=[],
new_step_items=[],
next_step=NextStepFinalOutput("done"),
tool_input_guardrail_results=[],
tool_output_guardrail_results=[],
)
monkeypatch.setattr(run_module, "resolve_interrupted_turn", fake_resolve_interrupted_turn)
runner = run_module.AgentRunner()
result = await runner.run(agent, state, run_config=RunConfig())
assert result.final_output == "done"
assert server_managed_values == [True]
@pytest.mark.asyncio
async def test_resumed_approval_does_not_duplicate_session_items() -> None:
async def test_tool() -> str:
return "tool_result"
tool = function_tool(test_tool, name_override="test_tool", needs_approval=True)
model, agent = make_model_and_agent(name="test", tools=[tool])
session = SimpleListSession()
queue_function_call_and_text(
model,
get_function_tool_call("test_tool", json.dumps({}), call_id="call-resume"),
followup=[get_text_message("done")],
)
first = await Runner.run(agent, input="Use test_tool", session=session)
assert first.interruptions
state = first.to_state()
state.approve(first.interruptions[0])
resumed = await Runner.run(agent, state, session=session)
assert resumed.final_output == "done"
saved_items = await session.get_items()
call_count = sum(
1
for item in saved_items
if isinstance(item, dict)
and item.get("type") == "function_call"
and item.get("call_id") == "call-resume"
)
output_count = sum(
1
for item in saved_items
if isinstance(item, dict)
and item.get("type") == "function_call_output"
and item.get("call_id") == "call-resume"
)
assert call_count == 1
assert output_count == 1