forked from openai/openai-agents-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_agent_runner.py
More file actions
4377 lines (3600 loc) · 140 KB
/
test_agent_runner.py
File metadata and controls
4377 lines (3600 loc) · 140 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
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import asyncio
import json
import tempfile
import warnings
from pathlib import Path
from typing import Any, Callable, cast
from unittest.mock import patch
import httpx
import pytest
from openai import APIConnectionError, BadRequestError
from openai.types.responses import ResponseFunctionToolCall
from openai.types.responses.response_output_text import AnnotationFileCitation, ResponseOutputText
from openai.types.responses.response_reasoning_item import ResponseReasoningItem, Summary
from typing_extensions import TypedDict
from agents import (
Agent,
GuardrailFunctionOutput,
Handoff,
HandoffInputData,
InputGuardrail,
InputGuardrailTripwireTriggered,
ModelBehaviorError,
ModelRetryAdvice,
ModelRetrySettings,
ModelSettings,
OpenAIConversationsSession,
OutputGuardrail,
OutputGuardrailTripwireTriggered,
RunConfig,
RunContextWrapper,
Runner,
SQLiteSession,
ToolTimeoutError,
UserError,
handoff,
retry_policies,
tool_namespace,
)
from agents.extensions.handoff_filters import remove_all_tools
from agents.agent import ToolsToFinalOutputResult
from agents.computer import Computer
from agents.items import (
HandoffOutputItem,
ModelResponse,
ReasoningItem,
RunItem,
ToolApprovalItem,
ToolCallOutputItem,
TResponseInputItem,
)
from agents.lifecycle import RunHooks
from agents.run import AgentRunner, get_default_agent_runner, set_default_agent_runner
from agents.run_config import _default_trace_include_sensitive_data
from agents.run_internal.items import (
drop_orphan_function_calls,
ensure_input_item_format,
fingerprint_input_item,
normalize_input_items_for_api,
normalize_resumed_input,
)
from agents.run_internal.oai_conversation import OpenAIServerConversationTracker
from agents.run_internal.run_loop import get_new_response
from agents.run_internal.run_steps import NextStepFinalOutput, SingleStepResult
from agents.run_internal.session_persistence import (
persist_session_items_for_guardrail_trip,
prepare_input_with_session,
rewind_session_items,
save_result_to_session,
wait_for_session_cleanup,
)
from agents.run_internal.tool_execution import execute_approved_tools
from agents.run_internal.tool_use_tracker import AgentToolUseTracker
from agents.run_state import RunState
from agents.tool import ComputerTool, FunctionToolResult, ShellTool, function_tool
from agents.tool_context import ToolContext
from agents.usage import Usage
from .fake_model import FakeModel
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,
)
from .utils.factories import make_run_state
from .utils.hitl import make_context_wrapper, make_model_and_agent, make_shell_call
from .utils.simple_session import CountingSession, IdStrippingSession, SimpleListSession
class _DummyRunItem:
def __init__(self, payload: dict[str, Any], item_type: str = "tool_call_output_item"):
self._payload = payload
self.type = item_type
def to_input_item(self) -> dict[str, Any]:
return self._payload
async def run_execute_approved_tools(
agent: Agent[Any],
approval_item: ToolApprovalItem,
*,
approve: bool | None,
run_config: RunConfig | None = None,
mutate_state: Callable[[RunState[Any, Agent[Any]], ToolApprovalItem], None] | None = None,
) -> list[RunItem]:
"""Execute approved tools with a consistent setup."""
context_wrapper: RunContextWrapper[Any] = make_context_wrapper()
state = make_run_state(
agent,
context=context_wrapper,
original_input="test",
max_turns=1,
)
if approve is True:
state.approve(approval_item)
elif approve is False:
state.reject(approval_item)
if mutate_state is not None:
mutate_state(state, approval_item)
generated_items: list[RunItem] = []
all_tools = await agent.get_all_tools(context_wrapper)
await execute_approved_tools(
agent=agent,
interruptions=[approval_item],
context_wrapper=context_wrapper,
generated_items=generated_items,
run_config=run_config or RunConfig(),
hooks=RunHooks(),
all_tools=all_tools,
)
return generated_items
def test_set_default_agent_runner_roundtrip():
runner = AgentRunner()
set_default_agent_runner(runner)
assert get_default_agent_runner() is runner
# Reset to ensure other tests are unaffected.
set_default_agent_runner(None)
assert isinstance(get_default_agent_runner(), AgentRunner)
def test_run_streamed_preserves_legacy_positional_previous_response_id():
captured: dict[str, Any] = {}
class DummyRunner:
def run_streamed(self, starting_agent: Any, input: Any, **kwargs: Any):
captured.update(kwargs)
return object()
original_runner = get_default_agent_runner()
set_default_agent_runner(cast(Any, DummyRunner()))
try:
Runner.run_streamed(
cast(Any, None),
"hello",
None,
10,
None,
None,
"resp-legacy",
)
finally:
set_default_agent_runner(original_runner)
assert captured["previous_response_id"] == "resp-legacy"
assert captured["error_handlers"] is None
def test_default_trace_include_sensitive_data_env(monkeypatch: pytest.MonkeyPatch):
monkeypatch.setenv("OPENAI_AGENTS_TRACE_INCLUDE_SENSITIVE_DATA", "false")
assert _default_trace_include_sensitive_data() is False
monkeypatch.setenv("OPENAI_AGENTS_TRACE_INCLUDE_SENSITIVE_DATA", "TRUE")
assert _default_trace_include_sensitive_data() is True
def test_run_config_defaults_nested_handoff_history_opt_in():
assert RunConfig().nest_handoff_history is False
def testdrop_orphan_function_calls_removes_orphans():
items: list[TResponseInputItem] = [
cast(
TResponseInputItem,
{
"type": "function_call",
"call_id": "call_orphan",
"name": "tool_one",
"arguments": "{}",
},
),
cast(TResponseInputItem, {"type": "message", "role": "user", "content": "hello"}),
cast(
TResponseInputItem,
{
"type": "function_call",
"call_id": "call_keep",
"name": "tool_keep",
"arguments": "{}",
},
),
cast(
TResponseInputItem,
{"type": "function_call_output", "call_id": "call_keep", "output": "done"},
),
cast(TResponseInputItem, {"type": "shell_call", "call_id": "shell_orphan"}),
cast(TResponseInputItem, {"type": "shell_call", "call_id": "shell_keep"}),
cast(
TResponseInputItem,
{"type": "shell_call_output", "call_id": "shell_keep", "output": []},
),
cast(TResponseInputItem, {"type": "apply_patch_call", "call_id": "patch_orphan"}),
cast(TResponseInputItem, {"type": "apply_patch_call", "call_id": "patch_keep"}),
cast(
TResponseInputItem,
{"type": "apply_patch_call_output", "call_id": "patch_keep", "output": "done"},
),
cast(TResponseInputItem, {"type": "computer_call", "call_id": "computer_orphan"}),
cast(TResponseInputItem, {"type": "computer_call", "call_id": "computer_keep"}),
cast(
TResponseInputItem,
{"type": "computer_call_output", "call_id": "computer_keep", "output": {}},
),
cast(TResponseInputItem, {"type": "local_shell_call", "call_id": "local_shell_orphan"}),
cast(TResponseInputItem, {"type": "local_shell_call", "call_id": "local_shell_keep"}),
cast(
TResponseInputItem,
{
"type": "local_shell_call_output",
"call_id": "local_shell_keep",
"output": {"stdout": "", "stderr": "", "outcome": {}},
},
),
]
filtered = drop_orphan_function_calls(items)
orphan_call_ids = {
"call_orphan",
"shell_orphan",
"patch_orphan",
"computer_orphan",
"local_shell_orphan",
}
for entry in filtered:
if isinstance(entry, dict):
assert entry.get("call_id") not in orphan_call_ids
def _has_call(call_type: str, call_id: str) -> bool:
return any(
isinstance(entry, dict)
and entry.get("type") == call_type
and entry.get("call_id") == call_id
for entry in filtered
)
assert _has_call("function_call", "call_keep")
assert _has_call("shell_call", "shell_keep")
assert _has_call("apply_patch_call", "patch_keep")
assert _has_call("computer_call", "computer_keep")
assert _has_call("local_shell_call", "local_shell_keep")
def test_normalize_resumed_input_drops_orphan_function_calls():
raw_input: list[TResponseInputItem] = [
cast(
TResponseInputItem,
{
"type": "function_call",
"call_id": "orphan_call",
"name": "tool_orphan",
"arguments": "{}",
},
),
cast(
TResponseInputItem,
{
"type": "function_call",
"call_id": "paired_call",
"name": "tool_paired",
"arguments": "{}",
},
),
cast(
TResponseInputItem,
{"type": "function_call_output", "call_id": "paired_call", "output": "ok"},
),
]
normalized = normalize_resumed_input(raw_input)
assert isinstance(normalized, list)
call_ids = [
cast(dict[str, Any], item).get("call_id")
for item in normalized
if isinstance(item, dict) and item.get("type") == "function_call"
]
assert "orphan_call" not in call_ids
assert "paired_call" in call_ids
def test_normalize_resumed_input_drops_orphan_tool_search_calls():
raw_input: list[TResponseInputItem] = [
cast(
TResponseInputItem,
{
"type": "tool_search_call",
"call_id": "orphan_search",
"arguments": {"query": "orphan"},
"execution": "server",
"status": "completed",
},
),
cast(
TResponseInputItem,
{
"type": "tool_search_call",
"call_id": "paired_search",
"arguments": {"query": "paired"},
"execution": "server",
"status": "completed",
},
),
cast(
TResponseInputItem,
{
"type": "tool_search_output",
"call_id": "paired_search",
"execution": "server",
"status": "completed",
"tools": [],
},
),
]
normalized = normalize_resumed_input(raw_input)
assert isinstance(normalized, list)
call_ids = [
cast(dict[str, Any], item).get("call_id")
for item in normalized
if isinstance(item, dict) and item.get("type") == "tool_search_call"
]
assert "orphan_search" not in call_ids
assert "paired_search" in call_ids
def test_normalize_resumed_input_preserves_hosted_tool_search_pair_without_call_ids():
raw_input: list[TResponseInputItem] = [
cast(
TResponseInputItem,
{
"type": "tool_search_call",
"call_id": None,
"arguments": {"query": "paired"},
"execution": "server",
"status": "completed",
},
),
cast(
TResponseInputItem,
{
"type": "tool_search_output",
"call_id": None,
"execution": "server",
"status": "completed",
"tools": [],
},
),
]
normalized = normalize_resumed_input(raw_input)
assert isinstance(normalized, list)
assert [cast(dict[str, Any], item)["type"] for item in normalized] == [
"tool_search_call",
"tool_search_output",
]
def test_normalize_resumed_input_matches_latest_anonymous_tool_search_call():
raw_input: list[TResponseInputItem] = [
cast(
TResponseInputItem,
{
"type": "tool_search_call",
"call_id": None,
"arguments": {"query": "orphan"},
"execution": "server",
"status": "completed",
},
),
cast(
TResponseInputItem,
{
"type": "tool_search_call",
"call_id": None,
"arguments": {"query": "paired"},
"execution": "server",
"status": "completed",
},
),
cast(
TResponseInputItem,
{
"type": "tool_search_output",
"call_id": None,
"execution": "server",
"status": "completed",
"tools": [],
},
),
]
normalized = normalize_resumed_input(raw_input)
assert isinstance(normalized, list)
assert [cast(dict[str, Any], item)["type"] for item in normalized] == [
"tool_search_call",
"tool_search_output",
]
assert cast(dict[str, Any], normalized[0])["arguments"] == {"query": "paired"}
def testnormalize_input_items_for_api_preserves_provider_data():
items: list[TResponseInputItem] = [
cast(
TResponseInputItem,
{
"type": "function_call_output",
"call_id": "call_norm",
"status": "completed",
"output": "out",
"provider_data": {"trace": "keep"},
},
),
cast(
TResponseInputItem,
{
"type": "message",
"role": "user",
"content": "hi",
"provider_data": {"trace": "remove"},
},
),
]
normalized = normalize_input_items_for_api(items)
first = cast(dict[str, Any], normalized[0])
second = cast(dict[str, Any], normalized[1])
assert first["type"] == "function_call_output"
assert first["call_id"] == "call_norm"
assert first["provider_data"] == {"trace": "keep"}
assert second["role"] == "user"
assert second["provider_data"] == {"trace": "remove"}
def test_fingerprint_input_item_returns_none_when_model_dump_fails():
class _BrokenModelDump:
def model_dump(self, *_args: Any, **_kwargs: Any) -> dict[str, Any]:
raise RuntimeError("model_dump failed")
assert fingerprint_input_item(_BrokenModelDump()) is None
def test_server_conversation_tracker_tracks_previous_response_id():
tracker = OpenAIServerConversationTracker(conversation_id=None, previous_response_id="resp_a")
response = ModelResponse(
output=[get_text_message("hello")],
usage=Usage(),
response_id="resp_b",
)
tracker.track_server_items(response)
assert tracker.previous_response_id == "resp_b"
assert len(tracker.server_items) == 1
def _as_message(item: Any) -> dict[str, Any]:
assert isinstance(item, dict)
role = item.get("role")
assert isinstance(role, str)
assert role in {"assistant", "user", "system", "developer"}
return cast(dict[str, Any], item)
def _find_reasoning_input_item(
items: str | list[TResponseInputItem] | Any,
) -> dict[str, Any] | None:
if not isinstance(items, list):
return None
for item in items:
if isinstance(item, dict) and item.get("type") == "reasoning":
return cast(dict[str, Any], item)
return None
@pytest.mark.asyncio
async def test_simple_first_run():
model = FakeModel()
agent = Agent(
name="test",
model=model,
)
model.set_next_output([get_text_message("first")])
result = await Runner.run(agent, input="test")
assert result.input == "test"
assert len(result.new_items) == 1, "exactly one item should be generated"
assert result.final_output == "first"
assert len(result.raw_responses) == 1, "exactly one model response should be generated"
assert result.raw_responses[0].output == [get_text_message("first")]
assert result.last_agent == agent
assert len(result.to_input_list()) == 2, "should have original input and generated item"
model.set_next_output([get_text_message("second")])
result = await Runner.run(
agent, input=[get_text_input_item("message"), get_text_input_item("another_message")]
)
assert len(result.new_items) == 1, "exactly one item should be generated"
assert result.final_output == "second"
assert len(result.raw_responses) == 1, "exactly one model response should be generated"
assert len(result.to_input_list()) == 3, "should have original input and generated item"
@pytest.mark.asyncio
async def test_subsequent_runs():
model = FakeModel()
agent = Agent(
name="test",
model=model,
)
model.set_next_output([get_text_message("third")])
result = await Runner.run(agent, input="test")
assert result.input == "test"
assert len(result.new_items) == 1, "exactly one item should be generated"
assert len(result.to_input_list()) == 2, "should have original input and generated item"
model.set_next_output([get_text_message("fourth")])
result = await Runner.run(agent, input=result.to_input_list())
assert len(result.input) == 2, f"should have previous input but got {result.input}"
assert len(result.new_items) == 1, "exactly one item should be generated"
assert result.final_output == "fourth"
assert len(result.raw_responses) == 1, "exactly one model response should be generated"
assert result.raw_responses[0].output == [get_text_message("fourth")]
assert result.last_agent == agent
assert len(result.to_input_list()) == 3, "should have original input and generated items"
@pytest.mark.asyncio
async def test_tool_call_runs():
model = FakeModel()
agent = Agent(
name="test",
model=model,
tools=[get_function_tool("foo", "tool_result")],
)
model.add_multiple_turn_outputs(
[
# First turn: a message and tool call
[get_text_message("a_message"), get_function_tool_call("foo", json.dumps({"a": "b"}))],
# Second turn: text message
[get_text_message("done")],
]
)
result = await Runner.run(agent, input="user_message")
assert result.final_output == "done"
assert len(result.raw_responses) == 2, (
"should have two responses: the first which produces a tool call, and the second which"
"handles the tool result"
)
assert len(result.to_input_list()) == 5, (
"should have five inputs: the original input, the message, the tool call, the tool result "
"and the done message"
)
@pytest.mark.asyncio
async def test_parallel_tool_call_with_cancelled_sibling_reaches_final_output() -> None:
async def _ok_tool() -> str:
return "ok"
async def _cancel_tool() -> str:
raise asyncio.CancelledError("tool-cancelled")
model = FakeModel()
agent = Agent(
name="test",
model=model,
tools=[
function_tool(_ok_tool, name_override="ok_tool"),
function_tool(_cancel_tool, name_override="cancel_tool"),
],
)
model.add_multiple_turn_outputs(
[
[
get_function_tool_call("ok_tool", "{}", call_id="call_ok"),
get_function_tool_call("cancel_tool", "{}", call_id="call_cancel"),
],
[get_text_message("final answer")],
]
)
result = await Runner.run(agent, input="user_message")
assert result.final_output == "final answer"
assert len(result.raw_responses) == 2
second_turn_input = cast(list[dict[str, Any]], model.last_turn_args["input"])
tool_outputs = [
item for item in second_turn_input if item.get("type") == "function_call_output"
]
assert tool_outputs == [
{"call_id": "call_ok", "output": "ok", "type": "function_call_output"},
{
"call_id": "call_cancel",
"output": (
"An error occurred while running the tool. Please try again. Error: tool-cancelled"
),
"type": "function_call_output",
},
]
@pytest.mark.asyncio
async def test_reasoning_item_id_policy_omits_follow_up_reasoning_ids() -> None:
model = FakeModel()
agent = Agent(
name="test",
model=model,
tools=[get_function_tool("foo", "tool_result")],
)
model.add_multiple_turn_outputs(
[
[
ResponseReasoningItem(
id="rs_first",
type="reasoning",
summary=[Summary(text="Thinking...", type="summary_text")],
),
get_function_tool_call("foo", json.dumps({"a": "b"}), call_id="call_first"),
],
[get_text_message("done")],
]
)
result = await Runner.run(
agent,
input="hello",
run_config=RunConfig(reasoning_item_id_policy="omit"),
)
assert result.final_output == "done"
second_request_reasoning = _find_reasoning_input_item(model.last_turn_args.get("input"))
assert second_request_reasoning is not None
assert "id" not in second_request_reasoning
history_reasoning = _find_reasoning_input_item(result.to_input_list())
assert history_reasoning is not None
assert "id" not in history_reasoning
@pytest.mark.asyncio
async def test_call_model_input_filter_can_reintroduce_reasoning_ids() -> None:
model = FakeModel()
agent = Agent(
name="test",
model=model,
tools=[get_function_tool("foo", "tool_result")],
)
model.add_multiple_turn_outputs(
[
[
ResponseReasoningItem(
id="rs_filter",
type="reasoning",
summary=[Summary(text="Thinking...", type="summary_text")],
),
get_function_tool_call("foo", json.dumps({"a": "b"}), call_id="call_filter"),
],
[get_text_message("done")],
]
)
def reintroduce_reasoning_id(data: Any) -> Any:
updated_input: list[TResponseInputItem] = []
for item in data.model_data.input:
if isinstance(item, dict) and item.get("type") == "reasoning" and "id" not in item:
updated_input.append(cast(TResponseInputItem, {**item, "id": "rs_reintroduced"}))
else:
updated_input.append(item)
data.model_data.input = updated_input
return data.model_data
result = await Runner.run(
agent,
input="hello",
run_config=RunConfig(
reasoning_item_id_policy="omit",
call_model_input_filter=reintroduce_reasoning_id,
),
)
assert result.final_output == "done"
second_request_reasoning = _find_reasoning_input_item(model.last_turn_args.get("input"))
assert second_request_reasoning is not None
assert second_request_reasoning.get("id") == "rs_reintroduced"
history_reasoning = _find_reasoning_input_item(result.to_input_list())
assert history_reasoning is not None
assert "id" not in history_reasoning
@pytest.mark.asyncio
async def test_resumed_run_uses_serialized_reasoning_item_id_policy() -> None:
model = FakeModel()
@function_tool(name_override="approval_tool", needs_approval=True)
def approval_tool() -> str:
return "ok"
agent = Agent(
name="test",
model=model,
tools=[approval_tool],
)
model.add_multiple_turn_outputs(
[
[
ResponseReasoningItem(
id="rs_resume",
type="reasoning",
summary=[Summary(text="Thinking...", type="summary_text")],
),
get_function_tool_call(
"approval_tool",
json.dumps({}),
call_id="call_resume",
),
],
[get_text_message("done")],
]
)
first_run = await Runner.run(
agent,
input="hello",
run_config=RunConfig(reasoning_item_id_policy="omit"),
)
assert len(first_run.interruptions) == 1
state = first_run.to_state()
state.approve(first_run.interruptions[0])
restored_state = await RunState.from_string(agent, state.to_string())
resumed = await Runner.run(agent, restored_state)
assert resumed.final_output == "done"
second_request_reasoning = _find_reasoning_input_item(model.last_turn_args.get("input"))
assert second_request_reasoning is not None
assert "id" not in second_request_reasoning
@pytest.mark.asyncio
async def test_tool_call_context_includes_current_agent() -> None:
model = FakeModel()
captured_contexts: list[ToolContext[Any]] = []
@function_tool(name_override="foo")
def foo(context: ToolContext[Any]) -> str:
captured_contexts.append(context)
return "tool_result"
agent = Agent(
name="test",
model=model,
tools=[foo],
)
model.add_multiple_turn_outputs(
[
[get_function_tool_call("foo", "{}")],
[get_text_message("done")],
]
)
result = await Runner.run(agent, input="user_message")
assert result.final_output == "done"
assert len(captured_contexts) == 1
assert captured_contexts[0].agent is agent
@pytest.mark.asyncio
async def test_handoffs():
model = FakeModel()
agent_1 = Agent(
name="test",
model=model,
)
agent_2 = Agent(
name="test",
model=model,
)
agent_3 = Agent(
name="test",
model=model,
handoffs=[agent_1, agent_2],
tools=[get_function_tool("some_function", "result")],
)
model.add_multiple_turn_outputs(
[
# First turn: a tool call
[get_function_tool_call("some_function", json.dumps({"a": "b"}))],
# Second turn: a message and a handoff
[get_text_message("a_message"), get_handoff_tool_call(agent_1)],
# Third turn: text message
[get_text_message("done")],
]
)
result = await Runner.run(agent_3, input="user_message")
assert result.final_output == "done"
assert len(result.raw_responses) == 3, "should have three model responses"
assert len(result.to_input_list()) == 7, (
"should have 7 inputs: summary message, tool call, tool result, message, handoff, "
"handoff result, and done message"
)
assert result.last_agent == agent_1, "should have handed off to agent_1"
@pytest.mark.asyncio
async def test_nested_handoff_filters_model_input_but_preserves_session_items():
model = FakeModel()
delegate = Agent(
name="delegate",
model=model,
)
triage = Agent(
name="triage",
model=model,
handoffs=[delegate],
tools=[get_function_tool("some_function", "result")],
)
model.add_multiple_turn_outputs(
[
# First turn: a tool call.
[get_function_tool_call("some_function", json.dumps({"a": "b"}))],
# Second turn: a message and a handoff.
[get_text_message("a_message"), get_handoff_tool_call(delegate)],
# Third turn: final message.
[get_text_message("done")],
]
)
model_input_types: list[list[str]] = []
def capture_model_input(data):
types: list[str] = []
for item in data.model_data.input:
if isinstance(item, dict):
item_type = item.get("type")
if isinstance(item_type, str):
types.append(item_type)
model_input_types.append(types)
return data.model_data
session = SimpleListSession()
result = await Runner.run(
triage,
input="user_message",
run_config=RunConfig(
nest_handoff_history=True,
call_model_input_filter=capture_model_input,
),
session=session,
)
assert result.final_output == "done"
assert len(model_input_types) >= 3
handoff_input_types = model_input_types[2]
assert "function_call" not in handoff_input_types
assert "function_call_output" not in handoff_input_types
assert any(isinstance(item, ToolCallOutputItem) for item in result.new_items)
assert any(isinstance(item, HandoffOutputItem) for item in result.new_items)
session_items = await session.get_items()
has_function_call_output = any(
isinstance(item, dict) and item.get("type") == "function_call_output"
for item in session_items
)
assert has_function_call_output
@pytest.mark.asyncio
async def test_nested_handoff_filters_reasoning_items_from_model_input():
model = FakeModel()
delegate = Agent(
name="delegate",
model=model,
)
triage = Agent(
name="triage",
model=model,
handoffs=[delegate],
)
model.add_multiple_turn_outputs(
[
[
ResponseReasoningItem(
id="reasoning_1",
type="reasoning",
summary=[Summary(text="Thinking about a handoff.", type="summary_text")],
),
get_handoff_tool_call(delegate),
],
[get_text_message("done")],
]
)
captured_inputs: list[list[dict[str, Any]]] = []
def capture_model_input(data):
if isinstance(data.model_data.input, list):
captured_inputs.append(
[item for item in data.model_data.input if isinstance(item, dict)]
)
return data.model_data
result = await Runner.run(
triage,
input="user_message",
run_config=RunConfig(
nest_handoff_history=True,
call_model_input_filter=capture_model_input,
),
)
assert result.final_output == "done"
assert len(captured_inputs) >= 2
handoff_input = captured_inputs[1]
handoff_input_types = [
item["type"] for item in handoff_input if isinstance(item.get("type"), str)
]
assert "reasoning" not in handoff_input_types
@pytest.mark.asyncio
async def test_resume_preserves_filtered_model_input_after_handoff():
model = FakeModel()
@function_tool(name_override="approval_tool", needs_approval=True)
def approval_tool() -> str:
return "ok"
delegate = Agent(
name="delegate",
model=model,
tools=[approval_tool],
)
triage = Agent(
name="triage",
model=model,
handoffs=[delegate],
tools=[get_function_tool("some_function", "result")],
)
model.add_multiple_turn_outputs(
[
[
get_function_tool_call(
"some_function", json.dumps({"a": "b"}), call_id="triage-call"