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_execution.py
More file actions
3317 lines (2779 loc) · 107 KB
/
test_run_step_execution.py
File metadata and controls
3317 lines (2779 loc) · 107 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 copy
import dataclasses
import gc
import json
from collections.abc import Callable
from contextvars import ContextVar
from dataclasses import dataclass
from typing import Any, cast
import pytest
from openai.types.responses import ResponseFunctionToolCall
from openai.types.responses.response_output_item import McpApprovalRequest
from openai.types.responses.response_output_message import ResponseOutputMessage
from openai.types.responses.response_output_refusal import ResponseOutputRefusal
from pydantic import BaseModel
from agents import (
Agent,
ApplyPatchTool,
FunctionTool,
HostedMCPTool,
MCPApprovalRequestItem,
MCPApprovalResponseItem,
MessageOutputItem,
ModelBehaviorError,
ModelRefusalError,
ModelResponse,
RunConfig,
RunContextWrapper,
RunHooks,
RunItem,
ShellTool,
ToolApprovalItem,
ToolCallItem,
ToolCallOutputItem,
ToolGuardrailFunctionOutput,
ToolInputGuardrail,
ToolOutputGuardrailData,
ToolOutputGuardrailTripwireTriggered,
ToolTimeoutError,
TResponseInputItem,
Usage,
UserError,
tool_namespace,
tool_output_guardrail,
trace,
)
from agents._public_agent import set_public_agent
from agents.run_internal import run_loop, turn_resolution
from agents.run_internal.agent_bindings import bind_execution_agent, bind_public_agent
from agents.run_internal.run_loop import (
NextStepFinalOutput,
NextStepHandoff,
NextStepInterruption,
NextStepRunAgain,
ProcessedResponse,
SingleStepResult,
ToolRunApplyPatchCall,
ToolRunComputerAction,
ToolRunFunction,
ToolRunHandoff,
ToolRunLocalShellCall,
ToolRunMCPApprovalRequest,
ToolRunShellCall,
get_handoffs,
get_output_schema,
)
from agents.run_internal.tool_execution import execute_function_tool_calls
from agents.tool import function_tool
from agents.tool_context import ToolContext
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 .testing_processor import SPAN_PROCESSOR_TESTING
from .utils.hitl import (
RecordingEditor,
assert_single_approval_interruption,
make_agent,
make_apply_patch_dict,
make_context_wrapper,
make_function_tool_call,
make_shell_call,
reject_tool_call,
)
def _function_spans() -> list[dict[str, Any]]:
function_spans: list[dict[str, Any]] = []
for span in SPAN_PROCESSOR_TESTING.get_ordered_spans(including_empty=True):
exported = span.export()
if not exported:
continue
span_data = exported.get("span_data")
if not isinstance(span_data, dict):
continue
if span_data.get("type") != "function":
continue
function_spans.append(exported)
return function_spans
def _function_span_names() -> list[str]:
names: list[str] = []
for exported in _function_spans():
span_data = exported.get("span_data")
if not isinstance(span_data, dict):
continue
name = span_data.get("name")
if isinstance(name, str):
names.append(name)
return names
def _bind_agent(agent: Agent[Any]):
public_agent = getattr(agent, "_agents_public_agent", None)
if isinstance(public_agent, Agent):
return bind_execution_agent(public_agent=public_agent, execution_agent=agent)
return bind_public_agent(agent)
@pytest.mark.asyncio
async def test_empty_response_is_final_output():
agent = Agent[None](name="test")
response = ModelResponse(
output=[],
usage=Usage(),
response_id=None,
)
result = await get_execute_result(agent, response)
assert result.original_input == "hello"
assert result.generated_items == []
assert isinstance(result.next_step, NextStepFinalOutput)
assert result.next_step.output == ""
@pytest.mark.asyncio
async def test_plaintext_agent_no_tool_calls_is_final_output():
agent = Agent(name="test")
response = ModelResponse(
output=[get_text_message("hello_world")],
usage=Usage(),
response_id=None,
)
result = await get_execute_result(agent, response)
assert result.original_input == "hello"
assert len(result.generated_items) == 1
assert_item_is_message(result.generated_items[0], "hello_world")
assert isinstance(result.next_step, NextStepFinalOutput)
assert result.next_step.output == "hello_world"
@pytest.mark.asyncio
async def test_plaintext_agent_no_tool_calls_multiple_messages_is_final_output():
agent = Agent(name="test")
response = ModelResponse(
output=[
get_text_message("hello_world"),
get_text_message("bye"),
],
usage=Usage(),
response_id=None,
)
result = await get_execute_result(
agent,
response,
original_input=[
get_text_input_item("test"),
get_text_input_item("test2"),
],
)
assert len(result.original_input) == 2
assert len(result.generated_items) == 2
assert_item_is_message(result.generated_items[0], "hello_world")
assert_item_is_message(result.generated_items[1], "bye")
assert isinstance(result.next_step, NextStepFinalOutput)
assert result.next_step.output == "bye"
@pytest.mark.asyncio
async def test_execute_tools_allows_unhashable_tool_call_arguments():
agent = make_agent()
response = ModelResponse(output=[], usage=Usage(), response_id="resp")
raw_tool_call = {
"type": "function_call",
"call_id": "call-1",
"name": "tool",
"arguments": {"key": "value"},
}
pre_step_items: list[RunItem] = [ToolCallItem(agent=agent, raw_item=raw_tool_call)]
result = await get_execute_result(agent, response, generated_items=pre_step_items)
assert len(result.generated_items) == 1
assert isinstance(result.next_step, NextStepFinalOutput)
@pytest.mark.asyncio
async def test_plaintext_agent_with_tool_call_is_run_again():
agent = Agent(name="test", tools=[get_function_tool(name="test", return_value="123")])
response = ModelResponse(
output=[get_text_message("hello_world"), get_function_tool_call("test", "")],
usage=Usage(),
response_id=None,
)
result = await get_execute_result(agent, response)
assert result.original_input == "hello"
# 3 items: new message, tool call, tool result
assert len(result.generated_items) == 3
assert isinstance(result.next_step, NextStepRunAgain)
items = result.generated_items
assert_item_is_message(items[0], "hello_world")
assert_item_is_function_tool_call(items[1], "test", None)
assert_item_is_function_tool_call_output(items[2], "123")
assert isinstance(result.next_step, NextStepRunAgain)
@pytest.mark.asyncio
async def test_plaintext_agent_hosted_shell_items_without_message_runs_again():
shell_tool = ShellTool(environment={"type": "container_auto"})
agent = Agent(name="test", tools=[shell_tool])
response = ModelResponse(
output=[
make_shell_call(
"call_shell_hosted", id_value="shell_call_hosted", commands=["echo hi"]
),
cast(
Any,
{
"type": "shell_call_output",
"id": "sh_out_hosted",
"call_id": "call_shell_hosted",
"status": "completed",
"output": [
{
"stdout": "hi\n",
"stderr": "",
"outcome": {"type": "exit", "exit_code": 0},
}
],
},
),
],
usage=Usage(),
response_id=None,
)
result = await get_execute_result(agent, response)
assert len(result.generated_items) == 2
assert isinstance(result.generated_items[0], ToolCallItem)
assert isinstance(result.generated_items[1], ToolCallOutputItem)
assert isinstance(result.next_step, NextStepRunAgain)
@pytest.mark.asyncio
async def test_plaintext_agent_shell_output_only_without_message_runs_again():
agent = Agent(name="test")
response = ModelResponse(
output=[
cast(
Any,
{
"type": "shell_call_output",
"id": "sh_out_only",
"call_id": "call_shell_only",
"status": "completed",
"output": [
{
"stdout": "hi\n",
"stderr": "",
"outcome": {"type": "exit", "exit_code": 0},
}
],
},
),
],
usage=Usage(),
response_id=None,
)
result = await get_execute_result(agent, response)
assert len(result.generated_items) == 1
assert isinstance(result.generated_items[0], ToolCallOutputItem)
assert isinstance(result.next_step, NextStepRunAgain)
@pytest.mark.asyncio
async def test_plaintext_agent_tool_search_only_without_message_runs_again():
agent = Agent(name="test")
response = ModelResponse(output=[], usage=Usage(), response_id=None)
response.output = cast(
Any,
[
{
"type": "tool_search_call",
"id": "tsc_step",
"arguments": {"paths": ["crm"], "query": "profile"},
"execution": "server",
"status": "completed",
},
{
"type": "tool_search_output",
"id": "tso_step",
"execution": "server",
"status": "completed",
"tools": [
{
"type": "function",
"name": "lookup_account",
"description": "Look up a CRM account.",
"parameters": {
"type": "object",
"properties": {
"account_id": {
"type": "string",
}
},
"required": ["account_id"],
},
"defer_loading": True,
}
],
},
],
)
result = await get_execute_result(agent, response)
assert len(result.generated_items) == 2
assert getattr(result.generated_items[0].raw_item, "type", None) == "tool_search_call"
raw_output = result.generated_items[1].raw_item
assert getattr(raw_output, "type", None) == "tool_search_output"
assert isinstance(result.next_step, NextStepRunAgain)
@pytest.mark.asyncio
async def test_plaintext_agent_client_tool_search_requires_manual_handling() -> None:
agent = Agent(name="test")
response = ModelResponse(output=[], usage=Usage(), response_id=None)
response.output = cast(
Any,
[
{
"type": "tool_search_call",
"id": "tsc_client_step",
"call_id": "call_tool_search_client",
"arguments": {"paths": ["crm"], "query": "profile"},
"execution": "client",
"status": "completed",
}
],
)
with pytest.raises(ModelBehaviorError, match="Client-executed tool_search calls"):
await get_execute_result(agent, response)
@pytest.mark.asyncio
async def test_plaintext_agent_hosted_shell_with_refusal_message_raises_refusal_error():
shell_tool = ShellTool(environment={"type": "container_auto"})
agent = Agent(name="test", tools=[shell_tool])
refusal_message = ResponseOutputMessage(
id="msg_refusal",
type="message",
role="assistant",
content=[ResponseOutputRefusal(type="refusal", refusal="I cannot help with that.")],
status="completed",
)
response = ModelResponse(
output=[
make_shell_call(
"call_shell_hosted_refusal",
id_value="shell_call_hosted_refusal",
commands=["echo hi"],
),
cast(
Any,
{
"type": "shell_call_output",
"id": "sh_out_hosted_refusal",
"call_id": "call_shell_hosted_refusal",
"status": "completed",
"output": [
{
"stdout": "hi\n",
"stderr": "",
"outcome": {"type": "exit", "exit_code": 0},
}
],
},
),
refusal_message,
],
usage=Usage(),
response_id=None,
)
with pytest.raises(ModelRefusalError) as exc_info:
await get_execute_result(agent, response)
assert exc_info.value.refusal == "I cannot help with that."
@pytest.mark.asyncio
async def test_multiple_tool_calls():
agent = Agent(
name="test",
tools=[
get_function_tool(name="test_1", return_value="123"),
get_function_tool(name="test_2", return_value="456"),
get_function_tool(name="test_3", return_value="789"),
],
)
response = ModelResponse(
output=[
get_text_message("Hello, world!"),
get_function_tool_call("test_1"),
get_function_tool_call("test_2"),
],
usage=Usage(),
response_id=None,
)
result = await get_execute_result(agent, response)
assert result.original_input == "hello"
# 5 items: new message, 2 tool calls, 2 tool call outputs
assert len(result.generated_items) == 5
assert isinstance(result.next_step, NextStepRunAgain)
items = result.generated_items
assert_item_is_message(items[0], "Hello, world!")
assert_item_is_function_tool_call(items[1], "test_1", None)
assert_item_is_function_tool_call(items[2], "test_2", None)
assert isinstance(result.next_step, NextStepRunAgain)
@pytest.mark.asyncio
async def test_multiple_tool_calls_with_tool_context():
async def _fake_tool(context: ToolContext[str], value: str) -> str:
return f"{value}-{context.tool_call_id}"
tool = function_tool(_fake_tool, name_override="fake_tool", failure_error_function=None)
agent = Agent(
name="test",
tools=[tool],
)
response = ModelResponse(
output=[
get_function_tool_call("fake_tool", json.dumps({"value": "123"}), call_id="1"),
get_function_tool_call("fake_tool", json.dumps({"value": "456"}), call_id="2"),
],
usage=Usage(),
response_id=None,
)
result = await get_execute_result(agent, response)
assert result.original_input == "hello"
# 4 items: new message, 2 tool calls, 2 tool call outputs
assert len(result.generated_items) == 4
assert isinstance(result.next_step, NextStepRunAgain)
items = result.generated_items
assert_item_is_function_tool_call(items[0], "fake_tool", json.dumps({"value": "123"}))
assert_item_is_function_tool_call(items[1], "fake_tool", json.dumps({"value": "456"}))
assert_item_is_function_tool_call_output(items[2], "123-1")
assert_item_is_function_tool_call_output(items[3], "456-2")
assert isinstance(result.next_step, NextStepRunAgain)
@pytest.mark.asyncio
async def test_multiple_tool_calls_still_raise_when_sibling_failure_error_function_none():
async def _ok_tool() -> str:
return "ok"
async def _error_tool() -> str:
raise ValueError("boom")
ok_tool = function_tool(_ok_tool, name_override="ok_tool", failure_error_function=None)
error_tool = function_tool(
_error_tool,
name_override="error_tool",
failure_error_function=None,
)
agent = Agent(name="test", tools=[ok_tool, error_tool])
response = ModelResponse(
output=[
get_function_tool_call("ok_tool", "{}", call_id="1"),
get_function_tool_call("error_tool", "{}", call_id="2"),
],
usage=Usage(),
response_id=None,
)
with pytest.raises(UserError, match="Error running tool error_tool: boom"):
await get_execute_result(agent, response)
@pytest.mark.asyncio
async def test_function_tool_error_trace_respects_sensitive_data_setting():
async def _error_tool() -> str:
raise ValueError("secret-token-123")
error_tool = function_tool(
_error_tool,
name_override="error_tool",
failure_error_function=None,
)
agent = Agent(name="test", tools=[error_tool])
response = ModelResponse(
output=[get_function_tool_call("error_tool", "{}", call_id="1")],
usage=Usage(),
response_id=None,
)
with trace("test"):
with pytest.raises(UserError, match="Error running tool error_tool: secret-token-123"):
await get_execute_result(
agent,
response,
run_config=RunConfig(trace_include_sensitive_data=False),
)
function_spans = _function_spans()
assert len(function_spans) == 1
error = function_spans[0]["error"]
assert error["message"] == "Error running tool"
assert error["data"]["tool_name"] == "error_tool"
assert error["data"]["error"] == "Tool execution failed. Error details are redacted."
assert "secret-token-123" not in str(error)
@pytest.mark.asyncio
async def test_default_function_tool_error_trace_respects_sensitive_data_setting():
async def _error_tool() -> str:
raise ValueError("secret-token-123")
error_tool = function_tool(_error_tool, name_override="error_tool")
agent = Agent(name="test", tools=[error_tool])
response = ModelResponse(
output=[get_function_tool_call("error_tool", "{}", call_id="1")],
usage=Usage(),
response_id=None,
)
with trace("test"):
result = await get_execute_result(
agent,
response,
run_config=RunConfig(trace_include_sensitive_data=False),
)
assert len(result.generated_items) == 2
assert isinstance(result.next_step, NextStepRunAgain)
assert_item_is_function_tool_call_output(
result.generated_items[1],
"An error occurred while running the tool. Please try again. Error: secret-token-123",
)
function_spans = _function_spans()
assert len(function_spans) == 1
error = function_spans[0]["error"]
assert error["message"] == "Error running tool (non-fatal)"
assert error["data"]["tool_name"] == "error_tool"
assert error["data"]["error"] == "Tool execution failed. Error details are redacted."
assert "secret-token-123" not in str(error)
@pytest.mark.asyncio
async def test_multiple_tool_calls_still_raise_when_sibling_cancelled():
async def _ok_tool() -> str:
return "ok"
async def _cancel_tool() -> str:
raise asyncio.CancelledError("tool-cancelled")
ok_tool = function_tool(_ok_tool, name_override="ok_tool", failure_error_function=None)
cancel_tool = function_tool(
_cancel_tool,
name_override="cancel_tool",
failure_error_function=None,
)
agent = Agent(name="test", tools=[ok_tool, cancel_tool])
response = ModelResponse(
output=[
get_function_tool_call("ok_tool", "{}", call_id="1"),
get_function_tool_call("cancel_tool", "{}", call_id="2"),
],
usage=Usage(),
response_id=None,
)
with pytest.raises(asyncio.CancelledError):
await get_execute_result(agent, response)
@pytest.mark.asyncio
async def test_multiple_tool_calls_cancel_sibling_when_tool_raises_cancelled_error():
started = asyncio.Event()
cancellation_started = asyncio.Event()
cancellation_finished = asyncio.Event()
allow_cancellation_exit = asyncio.Event()
async def _waiting_tool() -> str:
started.set()
try:
await asyncio.Future()
return "unreachable"
except asyncio.CancelledError:
cancellation_started.set()
await allow_cancellation_exit.wait()
cancellation_finished.set()
raise
async def _cancel_tool() -> str:
await started.wait()
raise asyncio.CancelledError("tool-cancelled")
waiting_tool = function_tool(
_waiting_tool,
name_override="waiting_tool",
failure_error_function=None,
)
cancel_tool = function_tool(
_cancel_tool,
name_override="cancel_tool",
failure_error_function=None,
)
agent = Agent(name="test", tools=[waiting_tool, cancel_tool])
response = ModelResponse(
output=[
get_function_tool_call("waiting_tool", "{}", call_id="1"),
get_function_tool_call("cancel_tool", "{}", call_id="2"),
],
usage=Usage(),
response_id=None,
)
execution_task = asyncio.create_task(get_execute_result(agent, response))
await asyncio.wait_for(started.wait(), timeout=0.2)
await asyncio.wait_for(cancellation_started.wait(), timeout=0.2)
with pytest.raises(asyncio.CancelledError):
await asyncio.wait_for(execution_task, timeout=0.2)
assert not cancellation_finished.is_set()
allow_cancellation_exit.set()
await asyncio.wait_for(cancellation_finished.wait(), timeout=0.2)
assert cancellation_finished.is_set()
@pytest.mark.asyncio
async def test_multiple_tool_calls_use_custom_failure_error_function_for_cancelled_tool():
async def _ok_tool() -> str:
return "ok"
async def _cancel_tool() -> str:
raise asyncio.CancelledError("tool-cancelled")
seen_error: Exception | None = None
def _custom_failure_error(_context: RunContextWrapper[Any], _error: Exception) -> str:
nonlocal seen_error
assert isinstance(_error, Exception)
assert not isinstance(_error, asyncio.CancelledError)
seen_error = _error
return "custom-cancel-msg"
ok_tool = function_tool(_ok_tool, name_override="ok_tool", failure_error_function=None)
cancel_tool = function_tool(
_cancel_tool,
name_override="cancel_tool",
failure_error_function=_custom_failure_error,
)
agent = Agent(name="test", tools=[ok_tool, cancel_tool])
response = ModelResponse(
output=[
get_function_tool_call("ok_tool", "{}", call_id="1"),
get_function_tool_call("cancel_tool", "{}", call_id="2"),
],
usage=Usage(),
response_id=None,
)
result = await get_execute_result(agent, response)
assert len(result.generated_items) == 4
assert isinstance(result.next_step, NextStepRunAgain)
assert_item_is_function_tool_call_output(result.generated_items[2], "ok")
assert_item_is_function_tool_call_output(result.generated_items[3], "custom-cancel-msg")
assert seen_error is not None
assert str(seen_error) == "tool-cancelled"
@pytest.mark.asyncio
async def test_multiple_tool_calls_use_custom_failure_error_function_for_replaced_cancelled_tool():
async def _ok_tool() -> str:
return "ok"
async def _cancel_tool() -> str:
raise asyncio.CancelledError("tool-cancelled")
def _custom_failure_error(_context: RunContextWrapper[Any], _error: Exception) -> str:
return "custom-cancel-msg"
ok_tool = function_tool(_ok_tool, name_override="ok_tool", failure_error_function=None)
cancel_tool = dataclasses.replace(
function_tool(
_cancel_tool,
name_override="cancel_tool",
failure_error_function=_custom_failure_error,
),
name="cancel_tool",
)
agent = Agent(name="test", tools=[ok_tool, cancel_tool])
response = ModelResponse(
output=[
get_function_tool_call("ok_tool", "{}", call_id="1"),
get_function_tool_call("cancel_tool", "{}", call_id="2"),
],
usage=Usage(),
response_id=None,
)
result = await get_execute_result(agent, response)
assert len(result.generated_items) == 4
assert isinstance(result.next_step, NextStepRunAgain)
assert_item_is_function_tool_call_output(result.generated_items[2], "ok")
assert_item_is_function_tool_call_output(result.generated_items[3], "custom-cancel-msg")
@pytest.mark.asyncio
async def test_multiple_tool_calls_use_default_failure_error_function_for_copied_cancelled_tool():
async def _ok_tool() -> str:
return "ok"
async def _cancel_tool() -> str:
raise asyncio.CancelledError("tool-cancelled")
ok_tool = function_tool(_ok_tool, name_override="ok_tool", failure_error_function=None)
cancel_tool = copy.deepcopy(function_tool(_cancel_tool, name_override="cancel_tool"))
agent = Agent(name="test", tools=[ok_tool, cancel_tool])
response = ModelResponse(
output=[
get_function_tool_call("ok_tool", "{}", call_id="1"),
get_function_tool_call("cancel_tool", "{}", call_id="2"),
],
usage=Usage(),
response_id=None,
)
result = await get_execute_result(agent, response)
assert len(result.generated_items) == 4
assert isinstance(result.next_step, NextStepRunAgain)
assert_item_is_function_tool_call_output(result.generated_items[2], "ok")
assert_item_is_function_tool_call_output(
result.generated_items[3],
"An error occurred while running the tool. Please try again. Error: tool-cancelled",
)
@pytest.mark.asyncio
async def test_multiple_tool_calls_use_default_failure_error_function_for_manual_cancelled_tool():
async def _ok_tool() -> str:
return "ok"
async def _manual_on_invoke_tool(_ctx: ToolContext[Any], _args: str) -> str:
raise asyncio.CancelledError("manual-tool-cancelled")
ok_tool = function_tool(_ok_tool, name_override="ok_tool", failure_error_function=None)
manual_tool = FunctionTool(
name="manual_cancel_tool",
description="manual cancel",
params_json_schema={},
on_invoke_tool=_manual_on_invoke_tool,
)
agent = Agent(name="test", tools=[ok_tool, manual_tool])
response = ModelResponse(
output=[
get_function_tool_call("ok_tool", "{}", call_id="1"),
get_function_tool_call("manual_cancel_tool", "{}", call_id="2"),
],
usage=Usage(),
response_id=None,
)
result = await get_execute_result(agent, response)
assert len(result.generated_items) == 4
assert isinstance(result.next_step, NextStepRunAgain)
assert_item_is_function_tool_call_output(result.generated_items[2], "ok")
assert_item_is_function_tool_call_output(
result.generated_items[3],
"An error occurred while running the tool. Please try again. Error: manual-tool-cancelled",
)
@pytest.mark.asyncio
async def test_single_tool_call_uses_default_failure_error_function_for_cancelled_tool():
async def _cancel_tool() -> str:
raise asyncio.CancelledError("tool-cancelled")
cancel_tool = function_tool(_cancel_tool, name_override="cancel_tool")
agent = Agent(name="test", tools=[cancel_tool])
response = ModelResponse(
output=[get_function_tool_call("cancel_tool", "{}", call_id="1")],
usage=Usage(),
response_id=None,
)
result = await get_execute_result(agent, response)
assert len(result.generated_items) == 2
assert isinstance(result.next_step, NextStepRunAgain)
assert_item_is_function_tool_call_output(
result.generated_items[1],
"An error occurred while running the tool. Please try again. Error: tool-cancelled",
)
@pytest.mark.asyncio
async def test_cancelled_function_tool_error_trace_respects_sensitive_data_setting():
async def _cancel_tool() -> str:
raise asyncio.CancelledError("secret-token-123")
cancel_tool = function_tool(_cancel_tool, name_override="cancel_tool")
agent = Agent(name="test", tools=[cancel_tool])
response = ModelResponse(
output=[get_function_tool_call("cancel_tool", "{}", call_id="1")],
usage=Usage(),
response_id=None,
)
with trace("test"):
result = await get_execute_result(
agent,
response,
run_config=RunConfig(trace_include_sensitive_data=False),
)
assert len(result.generated_items) == 2
assert isinstance(result.next_step, NextStepRunAgain)
assert_item_is_function_tool_call_output(
result.generated_items[1],
"An error occurred while running the tool. Please try again. Error: secret-token-123",
)
function_spans = _function_spans()
assert len(function_spans) == 1
error = function_spans[0]["error"]
assert error["message"] == "Tool execution cancelled"
assert error["data"]["tool_name"] == "cancel_tool"
assert error["data"]["error"] == "Tool execution failed. Error details are redacted."
assert "secret-token-123" not in str(error)
@pytest.mark.asyncio
async def test_multiple_tool_calls_surface_hook_failure_over_sibling_cancellation():
hook_started = asyncio.Event()
class FailingHooks(RunHooks[Any]):
async def on_tool_end(
self,
context: RunContextWrapper[Any],
agent: Agent[Any],
tool,
result: str,
) -> None:
if tool.name != "ok_tool":
return
hook_started.set()
raise ValueError("hook boom")
async def _ok_tool() -> str:
return "ok"
async def _cancel_tool() -> str:
await hook_started.wait()
raise asyncio.CancelledError("tool-cancelled")
hooks = FailingHooks()
ok_tool = function_tool(_ok_tool, name_override="ok_tool", failure_error_function=None)
cancel_tool = function_tool(
_cancel_tool,
name_override="cancel_tool",
failure_error_function=None,
)
agent = Agent(name="test", tools=[ok_tool, cancel_tool])
response = ModelResponse(
output=[
get_function_tool_call("ok_tool", "{}", call_id="1"),
get_function_tool_call("cancel_tool", "{}", call_id="2"),
],
usage=Usage(),
response_id=None,
)
with pytest.raises(UserError, match="Error running tool ok_tool: hook boom"):
await get_execute_result(agent, response, hooks=hooks)
@pytest.mark.asyncio
async def test_multiple_tool_calls_surface_output_guardrail_failure_over_sibling_cancellation():
guardrail_started = asyncio.Event()
@tool_output_guardrail
async def tripwire_guardrail(
data: ToolOutputGuardrailData,
) -> ToolGuardrailFunctionOutput:
guardrail_started.set()
return ToolGuardrailFunctionOutput.raise_exception(
output_info={"tool": data.context.tool_name}
)
async def _ok_tool() -> str:
return "ok"
async def _cancel_tool() -> str:
await guardrail_started.wait()
raise asyncio.CancelledError("tool-cancelled")
ok_tool = function_tool(
_ok_tool,
name_override="ok_tool",
failure_error_function=None,
tool_output_guardrails=[tripwire_guardrail],
)
cancel_tool = function_tool(
_cancel_tool,
name_override="cancel_tool",
failure_error_function=None,
)
agent = Agent(name="test", tools=[ok_tool, cancel_tool])
response = ModelResponse(
output=[
get_function_tool_call("ok_tool", "{}", call_id="1"),
get_function_tool_call("cancel_tool", "{}", call_id="2"),
],
usage=Usage(),
response_id=None,
)
with pytest.raises(ToolOutputGuardrailTripwireTriggered):
await get_execute_result(agent, response)
@pytest.mark.asyncio
async def test_function_tool_preserves_contextvar_from_tool_body_to_post_invoke_hooks():
tool_state: ContextVar[str] = ContextVar("tool_state", default="unset")
seen_values: list[tuple[str, str]] = []
@tool_output_guardrail
async def record_guardrail(_data: ToolOutputGuardrailData) -> ToolGuardrailFunctionOutput:
seen_values.append(("guardrail", tool_state.get()))
return ToolGuardrailFunctionOutput.allow(output_info="checked")
class RecordingHooks(RunHooks[Any]):
async def on_tool_end(
self,
context: RunContextWrapper[Any],
agent: Agent[Any],
tool,