forked from openai/openai-agents-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_run_step_processing.py
More file actions
596 lines (510 loc) · 18.5 KB
/
test_run_step_processing.py
File metadata and controls
596 lines (510 loc) · 18.5 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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
from __future__ import annotations
from typing import Any, cast
import pytest
from openai.types.responses import (
ResponseComputerToolCall,
ResponseFileSearchToolCall,
ResponseFunctionToolCall,
ResponseFunctionWebSearch,
)
from openai.types.responses.response_computer_tool_call import ActionClick
from openai.types.responses.response_function_web_search import ActionSearch
from openai.types.responses.response_reasoning_item import ResponseReasoningItem, Summary
from pydantic import BaseModel
from agents import (
Agent,
Computer,
ComputerTool,
Handoff,
HandoffInputData,
ModelBehaviorError,
ModelResponse,
ReasoningItem,
RunConfig,
RunContextWrapper,
RunHooks,
RunItem,
ToolCallItem,
ToolCallOutputItem,
Usage,
handoff,
)
from agents.run_internal import run_loop
from agents.run_internal.run_loop import ToolRunHandoff, get_handoffs, get_output_schema
from .test_responses import (
get_final_output_message,
get_function_tool,
get_function_tool_call,
get_handoff_tool_call,
get_text_input_item,
get_text_message,
)
def _dummy_ctx() -> RunContextWrapper[None]:
return RunContextWrapper(context=None)
async def process_response(
agent: Agent[Any],
response: ModelResponse,
*,
output_schema: Any = None,
handoffs: list[Handoff[Any, Agent[Any]]] | None = None,
) -> Any:
"""Process a model response using the agent's tools and optional handoffs."""
return run_loop.process_model_response(
agent=agent,
response=response,
output_schema=output_schema,
handoffs=handoffs or [],
all_tools=await agent.get_all_tools(_dummy_ctx()),
)
def test_empty_response():
agent = Agent(name="test")
response = ModelResponse(
output=[],
usage=Usage(),
response_id=None,
)
result = run_loop.process_model_response(
agent=agent,
response=response,
output_schema=None,
handoffs=[],
all_tools=[],
)
assert not result.handoffs
assert not result.functions
def test_no_tool_calls():
agent = Agent(name="test")
response = ModelResponse(
output=[get_text_message("Hello, world!")],
usage=Usage(),
response_id=None,
)
result = run_loop.process_model_response(
agent=agent, response=response, output_schema=None, handoffs=[], all_tools=[]
)
assert not result.handoffs
assert not result.functions
@pytest.mark.asyncio
async def test_single_tool_call():
agent = Agent(name="test", tools=[get_function_tool(name="test")])
response = ModelResponse(
output=[
get_text_message("Hello, world!"),
get_function_tool_call("test", ""),
],
usage=Usage(),
response_id=None,
)
result = await process_response(agent=agent, response=response)
assert not result.handoffs
assert result.functions and len(result.functions) == 1
func = result.functions[0]
assert func.tool_call.name == "test"
assert func.tool_call.arguments == ""
@pytest.mark.asyncio
async def test_missing_tool_call_raises_error():
agent = Agent(name="test", tools=[get_function_tool(name="test")])
response = ModelResponse(
output=[
get_text_message("Hello, world!"),
get_function_tool_call("missing", ""),
],
usage=Usage(),
response_id=None,
)
with pytest.raises(ModelBehaviorError):
await process_response(agent=agent, response=response)
@pytest.mark.asyncio
async def test_unknown_function_tool_respond_appends_recovery_output():
"""With unknown_tool_behavior='respond', an unknown function tool yields a tool output
describing the error and the run continues instead of raising."""
agent = Agent(
name="test",
tools=[get_function_tool(name="known_tool")],
unknown_tool_behavior="respond",
)
response = ModelResponse(
output=[get_function_tool_call("bogus_tool", "")],
usage=Usage(),
response_id=None,
)
result = await process_response(agent=agent, response=response)
# No real function run scheduled; the loop should continue and let the LLM retry.
assert not result.functions
assert not result.handoffs
# The unknown tool name is still recorded in tools_used (added before the lookup).
assert "bogus_tool" in result.tools_used
# The new items should contain a ToolCallItem for the unknown call followed by a
# ToolCallOutputItem containing the recovery message that names available tools.
tool_calls = [item for item in result.new_items if isinstance(item, ToolCallItem)]
tool_outputs = [item for item in result.new_items if isinstance(item, ToolCallOutputItem)]
assert len(tool_calls) == 1
assert len(tool_outputs) == 1
message = tool_outputs[0].output
assert "bogus_tool" in message
assert "known_tool" in message
@pytest.mark.asyncio
async def test_unknown_function_tool_default_still_raises():
"""The default Agent behavior must continue to raise so existing users aren't broken."""
agent = Agent(name="test", tools=[get_function_tool(name="known_tool")])
response = ModelResponse(
output=[get_function_tool_call("bogus_tool", "")],
usage=Usage(),
response_id=None,
)
with pytest.raises(ModelBehaviorError, match="bogus_tool"):
await process_response(agent=agent, response=response)
@pytest.mark.asyncio
async def test_multiple_tool_calls():
agent = Agent(
name="test",
tools=[
get_function_tool(name="test_1"),
get_function_tool(name="test_2"),
get_function_tool(name="test_3"),
],
)
response = ModelResponse(
output=[
get_text_message("Hello, world!"),
get_function_tool_call("test_1", "abc"),
get_function_tool_call("test_2", "xyz"),
],
usage=Usage(),
response_id=None,
)
result = await process_response(agent=agent, response=response)
assert not result.handoffs
assert result.functions and len(result.functions) == 2
func_1 = result.functions[0]
assert func_1.tool_call.name == "test_1"
assert func_1.tool_call.arguments == "abc"
func_2 = result.functions[1]
assert func_2.tool_call.name == "test_2"
assert func_2.tool_call.arguments == "xyz"
@pytest.mark.asyncio
async def test_handoffs_parsed_correctly():
agent_1 = Agent(name="test_1")
agent_2 = Agent(name="test_2")
agent_3 = Agent(name="test_3", handoffs=[agent_1, agent_2])
response = ModelResponse(
output=[get_text_message("Hello, world!")],
usage=Usage(),
response_id=None,
)
result = await process_response(agent=agent_3, response=response)
assert not result.handoffs, "Shouldn't have a handoff here"
response = ModelResponse(
output=[get_text_message("Hello, world!"), get_handoff_tool_call(agent_1)],
usage=Usage(),
response_id=None,
)
result = await process_response(
agent=agent_3,
response=response,
handoffs=await get_handoffs(agent_3, _dummy_ctx()),
)
assert len(result.handoffs) == 1, "Should have a handoff here"
handoff = result.handoffs[0]
assert handoff.handoff.tool_name == Handoff.default_tool_name(agent_1)
assert handoff.handoff.tool_description == Handoff.default_tool_description(agent_1)
assert handoff.handoff.agent_name == agent_1.name
handoff_agent = await handoff.handoff.on_invoke_handoff(
RunContextWrapper(None), handoff.tool_call.arguments
)
assert handoff_agent == agent_1
@pytest.mark.asyncio
async def test_handoff_can_disable_run_level_history_nesting(monkeypatch: pytest.MonkeyPatch):
source_agent = Agent(name="source")
target_agent = Agent(name="target")
override_handoff = handoff(target_agent, nest_handoff_history=False)
tool_call = cast(ResponseFunctionToolCall, get_handoff_tool_call(target_agent))
run_handoffs = [ToolRunHandoff(handoff=override_handoff, tool_call=tool_call)]
run_config = RunConfig(nest_handoff_history=True)
context_wrapper = RunContextWrapper(context=None)
hooks = RunHooks()
original_input = [get_text_input_item("hello")]
pre_step_items: list[RunItem] = []
new_step_items: list[RunItem] = []
new_response = ModelResponse(output=[tool_call], usage=Usage(), response_id=None)
calls: list[HandoffInputData] = []
def fake_nest(
handoff_input_data: HandoffInputData,
*,
history_mapper: Any,
) -> HandoffInputData:
_ = history_mapper
calls.append(handoff_input_data)
return handoff_input_data
monkeypatch.setattr("agents.run_internal.turn_resolution.nest_handoff_history", fake_nest)
result = await run_loop.execute_handoffs(
public_agent=source_agent,
original_input=list(original_input),
pre_step_items=pre_step_items,
new_step_items=new_step_items,
new_response=new_response,
run_handoffs=run_handoffs,
hooks=hooks,
context_wrapper=context_wrapper,
run_config=run_config,
)
assert calls == []
assert result.original_input == original_input
@pytest.mark.asyncio
async def test_handoff_can_enable_history_nesting(monkeypatch: pytest.MonkeyPatch):
source_agent = Agent(name="source")
target_agent = Agent(name="target")
override_handoff = handoff(target_agent, nest_handoff_history=True)
tool_call = cast(ResponseFunctionToolCall, get_handoff_tool_call(target_agent))
run_handoffs = [ToolRunHandoff(handoff=override_handoff, tool_call=tool_call)]
run_config = RunConfig(nest_handoff_history=False)
context_wrapper = RunContextWrapper(context=None)
hooks = RunHooks()
original_input = [get_text_input_item("hello")]
pre_step_items: list[RunItem] = []
new_step_items: list[RunItem] = []
new_response = ModelResponse(output=[tool_call], usage=Usage(), response_id=None)
def fake_nest(
handoff_input_data: HandoffInputData,
*,
history_mapper: Any,
) -> HandoffInputData:
_ = history_mapper
return handoff_input_data.clone(
input_history=(
{
"role": "assistant",
"content": "nested",
},
)
)
monkeypatch.setattr("agents.run_internal.turn_resolution.nest_handoff_history", fake_nest)
result = await run_loop.execute_handoffs(
public_agent=source_agent,
original_input=list(original_input),
pre_step_items=pre_step_items,
new_step_items=new_step_items,
new_response=new_response,
run_handoffs=run_handoffs,
hooks=hooks,
context_wrapper=context_wrapper,
run_config=run_config,
)
assert result.original_input == [
{
"role": "assistant",
"content": "nested",
}
]
@pytest.mark.asyncio
async def test_missing_handoff_fails():
agent_1 = Agent(name="test_1")
agent_2 = Agent(name="test_2")
agent_3 = Agent(name="test_3", handoffs=[agent_1])
response = ModelResponse(
output=[get_text_message("Hello, world!"), get_handoff_tool_call(agent_2)],
usage=Usage(),
response_id=None,
)
with pytest.raises(ModelBehaviorError):
await process_response(
agent=agent_3,
response=response,
handoffs=await get_handoffs(agent_3, _dummy_ctx()),
)
@pytest.mark.asyncio
async def test_multiple_handoffs_doesnt_error():
agent_1 = Agent(name="test_1")
agent_2 = Agent(name="test_2")
agent_3 = Agent(name="test_3", handoffs=[agent_1, agent_2])
response = ModelResponse(
output=[
get_text_message("Hello, world!"),
get_handoff_tool_call(agent_1),
get_handoff_tool_call(agent_2),
],
usage=Usage(),
response_id=None,
)
result = await process_response(
agent=agent_3,
response=response,
handoffs=await get_handoffs(agent_3, _dummy_ctx()),
)
assert len(result.handoffs) == 2, "Should have multiple handoffs here"
class Foo(BaseModel):
bar: str
@pytest.mark.asyncio
async def test_final_output_parsed_correctly():
agent = Agent(name="test", output_type=Foo)
response = ModelResponse(
output=[
get_text_message("Hello, world!"),
get_final_output_message(Foo(bar="123").model_dump_json()),
],
usage=Usage(),
response_id=None,
)
await process_response(
agent=agent,
response=response,
output_schema=get_output_schema(agent),
)
@pytest.mark.asyncio
async def test_file_search_tool_call_parsed_correctly():
# Ensure that a ResponseFileSearchToolCall output is parsed into a ToolCallItem and that no tool
# runs are scheduled.
agent = Agent(name="test")
file_search_call = ResponseFileSearchToolCall(
id="fs1",
queries=["query"],
status="completed",
type="file_search_call",
)
response = ModelResponse(
output=[get_text_message("hello"), file_search_call],
usage=Usage(),
response_id=None,
)
result = await process_response(agent=agent, response=response)
# The final item should be a ToolCallItem for the file search call
assert any(
isinstance(item, ToolCallItem) and item.raw_item is file_search_call
for item in result.new_items
)
assert not result.functions
assert not result.handoffs
@pytest.mark.asyncio
async def test_function_web_search_tool_call_parsed_correctly():
agent = Agent(name="test")
web_search_call = ResponseFunctionWebSearch(
id="w1",
action=ActionSearch(type="search", query="query"),
status="completed",
type="web_search_call",
)
response = ModelResponse(
output=[get_text_message("hello"), web_search_call],
usage=Usage(),
response_id=None,
)
result = await process_response(agent=agent, response=response)
assert any(
isinstance(item, ToolCallItem) and item.raw_item is web_search_call
for item in result.new_items
)
assert not result.functions
assert not result.handoffs
@pytest.mark.asyncio
async def test_reasoning_item_parsed_correctly():
# Verify that a Reasoning output item is converted into a ReasoningItem.
reasoning = ResponseReasoningItem(
id="r1", type="reasoning", summary=[Summary(text="why", type="summary_text")]
)
response = ModelResponse(
output=[reasoning],
usage=Usage(),
response_id=None,
)
agent = Agent(name="test")
result = await process_response(agent=agent, response=response)
assert any(
isinstance(item, ReasoningItem) and item.raw_item is reasoning for item in result.new_items
)
class DummyComputer(Computer):
"""Minimal computer implementation for testing."""
@property
def environment(self):
return "mac" # pragma: no cover
@property
def dimensions(self):
return (0, 0) # pragma: no cover
def screenshot(self) -> str:
return "" # pragma: no cover
def click(self, x: int, y: int, button: str) -> None:
return None # pragma: no cover
def double_click(self, x: int, y: int) -> None:
return None # pragma: no cover
def scroll(self, x: int, y: int, scroll_x: int, scroll_y: int) -> None:
return None # pragma: no cover
def type(self, text: str) -> None:
return None # pragma: no cover
def wait(self) -> None:
return None # pragma: no cover
def move(self, x: int, y: int) -> None:
return None # pragma: no cover
def keypress(self, keys: list[str]) -> None:
return None # pragma: no cover
def drag(self, path: list[tuple[int, int]]) -> None:
return None # pragma: no cover
@pytest.mark.asyncio
async def test_computer_tool_call_without_computer_tool_raises_error():
# If the agent has no ComputerTool in its tools, process_model_response should raise a
# ModelBehaviorError when encountering a ResponseComputerToolCall.
computer_call = ResponseComputerToolCall(
id="c1",
type="computer_call",
action=ActionClick(type="click", x=1, y=2, button="left"),
call_id="c1",
pending_safety_checks=[],
status="completed",
)
response = ModelResponse(
output=[computer_call],
usage=Usage(),
response_id=None,
)
with pytest.raises(ModelBehaviorError):
await process_response(agent=Agent(name="test"), response=response)
@pytest.mark.asyncio
async def test_computer_tool_call_with_computer_tool_parsed_correctly():
# If the agent contains a ComputerTool, ensure that a ResponseComputerToolCall is parsed into a
# ToolCallItem and scheduled to run in computer_actions.
dummy_computer = DummyComputer()
agent = Agent(name="test", tools=[ComputerTool(computer=dummy_computer)])
computer_call = ResponseComputerToolCall(
id="c1",
type="computer_call",
action=ActionClick(type="click", x=1, y=2, button="left"),
call_id="c1",
pending_safety_checks=[],
status="completed",
)
response = ModelResponse(
output=[computer_call],
usage=Usage(),
response_id=None,
)
result = await process_response(agent=agent, response=response)
assert any(
isinstance(item, ToolCallItem) and item.raw_item is computer_call
for item in result.new_items
)
assert result.computer_actions and result.computer_actions[0].tool_call == computer_call
@pytest.mark.asyncio
async def test_tool_and_handoff_parsed_correctly():
agent_1 = Agent(name="test_1")
agent_2 = Agent(name="test_2")
agent_3 = Agent(
name="test_3", tools=[get_function_tool(name="test")], handoffs=[agent_1, agent_2]
)
response = ModelResponse(
output=[
get_text_message("Hello, world!"),
get_function_tool_call("test", "abc"),
get_handoff_tool_call(agent_1),
],
usage=Usage(),
response_id=None,
)
result = await process_response(
agent=agent_3,
response=response,
handoffs=await get_handoffs(agent_3, _dummy_ctx()),
)
assert result.functions and len(result.functions) == 1
assert len(result.handoffs) == 1, "Should have a handoff here"
handoff = result.handoffs[0]
assert handoff.handoff.tool_name == Handoff.default_tool_name(agent_1)
assert handoff.handoff.tool_description == Handoff.default_tool_description(agent_1)
assert handoff.handoff.agent_name == agent_1.name