-
Notifications
You must be signed in to change notification settings - Fork 4.2k
Expand file tree
/
Copy pathtest_agent_as_tool.py
More file actions
2749 lines (2300 loc) · 78.8 KB
/
Copy pathtest_agent_as_tool.py
File metadata and controls
2749 lines (2300 loc) · 78.8 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 contextlib
import dataclasses
import json
from typing import Any, cast
import pytest
from mcp.shared.exceptions import McpError
from mcp.types import ErrorData
from openai.types.responses import ResponseOutputMessage, ResponseOutputText
from openai.types.responses.response_function_tool_call import ResponseFunctionToolCall
from pydantic import BaseModel, Field
from agents import (
Agent,
AgentBase,
AgentToolStreamEvent,
FunctionTool,
MessageOutputItem,
ModelBehaviorError,
ModelResponse,
RunConfig,
RunContextWrapper,
RunHooks,
Runner,
RunResult,
RunResultStreaming,
Session,
SessionSettings,
ToolApprovalItem,
ToolCallOutputItem,
TResponseInputItem,
Usage,
tool_namespace,
)
from agents.agent_tool_input import StructuredToolInputBuilderOptions
from agents.agent_tool_state import (
get_agent_tool_state_scope,
record_agent_tool_run_result,
set_agent_tool_state_scope,
)
from agents.run_context import _ApprovalRecord
from agents.run_state import _build_agent_map
from agents.stream_events import AgentUpdatedStreamEvent, RawResponsesStreamEvent
from agents.tool_context import ToolContext
from tests.fake_model import FakeModel
from tests.mcp.helpers import FakeMCPServer
from tests.test_responses import get_function_tool_call, get_text_message
from tests.utils.hitl import make_function_tool_call
class BoolCtx(BaseModel):
enable_tools: bool
@pytest.mark.asyncio
async def test_agent_as_tool_is_enabled_bool():
"""Test that agent.as_tool() respects static boolean is_enabled parameter."""
# Create a simple agent
agent = Agent(
name="test_agent",
instructions="You are a test agent that says hello.",
)
# Create tool with is_enabled=False
disabled_tool = agent.as_tool(
tool_name="disabled_agent_tool",
tool_description="A disabled agent tool",
is_enabled=False,
)
# Create tool with is_enabled=True (default)
enabled_tool = agent.as_tool(
tool_name="enabled_agent_tool",
tool_description="An enabled agent tool",
is_enabled=True,
)
# Create another tool with default is_enabled (should be True)
default_tool = agent.as_tool(
tool_name="default_agent_tool",
tool_description="A default agent tool",
)
# Create test agent that uses these tools
orchestrator = Agent(
name="orchestrator",
instructions="You orchestrate other agents.",
tools=[disabled_tool, enabled_tool, default_tool],
)
# Test with any context
context = RunContextWrapper(BoolCtx(enable_tools=True))
# Get all tools - should filter out the disabled one
tools = await orchestrator.get_all_tools(context)
tool_names = [tool.name for tool in tools]
assert "enabled_agent_tool" in tool_names
assert "default_agent_tool" in tool_names
assert "disabled_agent_tool" not in tool_names
@pytest.mark.asyncio
async def test_agent_as_tool_is_enabled_callable():
"""Test that agent.as_tool() respects callable is_enabled parameter."""
# Create a simple agent
agent = Agent(
name="test_agent",
instructions="You are a test agent that says hello.",
)
# Create tool with callable is_enabled
async def cond_enabled(ctx: RunContextWrapper[BoolCtx], agent: AgentBase) -> bool:
return ctx.context.enable_tools
conditional_tool = agent.as_tool(
tool_name="conditional_agent_tool",
tool_description="A conditionally enabled agent tool",
is_enabled=cond_enabled,
)
# Create tool with lambda is_enabled
lambda_tool = agent.as_tool(
tool_name="lambda_agent_tool",
tool_description="A lambda enabled agent tool",
is_enabled=lambda ctx, agent: ctx.context.enable_tools,
)
# Create test agent that uses these tools
orchestrator = Agent(
name="orchestrator",
instructions="You orchestrate other agents.",
tools=[conditional_tool, lambda_tool],
)
# Test with enable_tools=False
context_disabled = RunContextWrapper(BoolCtx(enable_tools=False))
tools_disabled = await orchestrator.get_all_tools(context_disabled)
assert len(tools_disabled) == 0
# Test with enable_tools=True
context_enabled = RunContextWrapper(BoolCtx(enable_tools=True))
tools_enabled = await orchestrator.get_all_tools(context_enabled)
tool_names = [tool.name for tool in tools_enabled]
assert len(tools_enabled) == 2
assert "conditional_agent_tool" in tool_names
assert "lambda_agent_tool" in tool_names
@pytest.mark.asyncio
async def test_agent_as_tool_is_enabled_mixed():
"""Test agent.as_tool() with mixed enabled/disabled tools."""
# Create a simple agent
agent = Agent(
name="test_agent",
instructions="You are a test agent that says hello.",
)
# Create various tools with different is_enabled configurations
always_enabled = agent.as_tool(
tool_name="always_enabled",
tool_description="Always enabled tool",
is_enabled=True,
)
always_disabled = agent.as_tool(
tool_name="always_disabled",
tool_description="Always disabled tool",
is_enabled=False,
)
conditionally_enabled = agent.as_tool(
tool_name="conditionally_enabled",
tool_description="Conditionally enabled tool",
is_enabled=lambda ctx, agent: ctx.context.enable_tools,
)
default_enabled = agent.as_tool(
tool_name="default_enabled",
tool_description="Default enabled tool",
)
# Create test agent that uses these tools
orchestrator = Agent(
name="orchestrator",
instructions="You orchestrate other agents.",
tools=[always_enabled, always_disabled, conditionally_enabled, default_enabled],
)
# Test with enable_tools=False
context_disabled = RunContextWrapper(BoolCtx(enable_tools=False))
tools_disabled = await orchestrator.get_all_tools(context_disabled)
tool_names_disabled = [tool.name for tool in tools_disabled]
assert len(tools_disabled) == 2
assert "always_enabled" in tool_names_disabled
assert "default_enabled" in tool_names_disabled
assert "always_disabled" not in tool_names_disabled
assert "conditionally_enabled" not in tool_names_disabled
# Test with enable_tools=True
context_enabled = RunContextWrapper(BoolCtx(enable_tools=True))
tools_enabled = await orchestrator.get_all_tools(context_enabled)
tool_names_enabled = [tool.name for tool in tools_enabled]
assert len(tools_enabled) == 3
assert "always_enabled" in tool_names_enabled
assert "default_enabled" in tool_names_enabled
assert "conditionally_enabled" in tool_names_enabled
assert "always_disabled" not in tool_names_enabled
@pytest.mark.asyncio
async def test_agent_as_tool_is_enabled_preserves_other_params():
"""Test that is_enabled parameter doesn't interfere with other agent.as_tool() parameters."""
# Create a simple agent
agent = Agent(
name="test_agent",
instructions="You are a test agent that returns a greeting.",
)
# Custom output extractor
async def custom_extractor(result):
return f"CUSTOM: {result.new_items[-1].text if result.new_items else 'No output'}"
# Create tool with all parameters including is_enabled
tool = agent.as_tool(
tool_name="custom_tool_name",
tool_description="A custom tool with all parameters",
custom_output_extractor=custom_extractor,
is_enabled=True,
)
# Verify the tool was created with correct properties
assert tool.name == "custom_tool_name"
assert isinstance(tool, FunctionTool)
assert tool.description == "A custom tool with all parameters"
assert tool.is_enabled is True
# Verify tool is included when enabled
orchestrator = Agent(
name="orchestrator",
instructions="You orchestrate other agents.",
tools=[tool],
)
context = RunContextWrapper(BoolCtx(enable_tools=True))
tools = await orchestrator.get_all_tools(context)
assert len(tools) == 1
assert tools[0].name == "custom_tool_name"
@pytest.mark.asyncio
async def test_agent_as_tool_returns_final_output(monkeypatch: pytest.MonkeyPatch) -> None:
"""Agent tool should return final_output when no custom extractor is provided."""
agent = Agent(name="storyteller")
result = type(
"DummyResult",
(),
{"final_output": "Hello world"},
)()
async def fake_run(
cls,
starting_agent,
input,
*,
context,
max_turns,
hooks,
run_config,
previous_response_id,
conversation_id,
session,
):
assert starting_agent is agent
assert input == "hello"
return result
monkeypatch.setattr(Runner, "run", classmethod(fake_run))
tool = agent.as_tool(
tool_name="story_tool",
tool_description="Tell a short story",
is_enabled=True,
)
assert isinstance(tool, FunctionTool)
tool_context = ToolContext(
context=None,
tool_name="story_tool",
tool_call_id="call_1",
tool_arguments='{"input": "hello"}',
)
output = await tool.on_invoke_tool(tool_context, '{"input": "hello"}')
assert output == "Hello world"
@pytest.mark.asyncio
async def test_agent_as_tool_custom_output_extractor(monkeypatch: pytest.MonkeyPatch) -> None:
"""Custom output extractors should receive the RunResult from Runner.run."""
agent = Agent(name="summarizer")
message = ResponseOutputMessage(
id="msg_2",
role="assistant",
status="completed",
type="message",
content=[
ResponseOutputText(
annotations=[],
text="Original text",
type="output_text",
logprobs=[],
)
],
)
class DummySession(Session):
session_id = "sess_123"
session_settings = SessionSettings()
async def get_items(self, limit: int | None = None) -> list[TResponseInputItem]:
return []
async def add_items(self, items: list[TResponseInputItem]) -> None:
return None
async def pop_item(self) -> TResponseInputItem | None:
return None
async def clear_session(self) -> None:
return None
dummy_session = DummySession()
class DummyResult:
def __init__(self, items: list[MessageOutputItem]) -> None:
self.new_items = items
run_result = DummyResult([MessageOutputItem(agent=agent, raw_item=message)])
async def fake_run(
cls,
starting_agent,
input,
*,
context,
max_turns,
hooks,
run_config,
previous_response_id,
conversation_id,
session,
):
assert starting_agent is agent
assert input == "summarize this"
assert isinstance(context, ToolContext)
assert context.tool_call_id == "call_2"
assert context.tool_name == "summary_tool"
assert max_turns == 7
assert hooks is hooks_obj
assert run_config is run_config_obj
assert previous_response_id == "resp_1"
assert conversation_id == "conv_1"
assert session is dummy_session
return run_result
monkeypatch.setattr(Runner, "run", classmethod(fake_run))
async def extractor(result) -> str:
assert result is run_result
return "custom output"
hooks_obj = RunHooks[Any]()
run_config_obj = RunConfig(model="gpt-4.1-mini")
tool = agent.as_tool(
tool_name="summary_tool",
tool_description="Summarize input",
custom_output_extractor=extractor,
is_enabled=True,
run_config=run_config_obj,
max_turns=7,
hooks=hooks_obj,
previous_response_id="resp_1",
conversation_id="conv_1",
session=dummy_session,
)
assert isinstance(tool, FunctionTool)
tool_context = ToolContext(
context=None,
tool_name="summary_tool",
tool_call_id="call_2",
tool_arguments='{"input": "summarize this"}',
)
output = await tool.on_invoke_tool(tool_context, '{"input": "summarize this"}')
assert output == "custom output"
@pytest.mark.asyncio
async def test_agent_as_tool_fallback_uses_current_run_items_only(
monkeypatch: pytest.MonkeyPatch,
) -> None:
agent = Agent(name="summarizer")
message = ResponseOutputMessage(
id="msg_current",
role="assistant",
status="completed",
type="message",
content=[
ResponseOutputText(
annotations=[],
text="Current run summary",
type="output_text",
logprobs=[],
)
],
)
class DummyResult:
def __init__(self) -> None:
self.final_output = ""
self.new_items = [
ToolCallOutputItem(
agent=agent,
raw_item={
"call_id": "call_current",
"output": "Current tool output",
"type": "function_call_output",
},
output="Current tool output",
),
MessageOutputItem(agent=agent, raw_item=message),
]
def to_input_list(self) -> list[dict[str, Any]]:
return [
{
"call_id": "call_old",
"output": "Old output from prior history",
"type": "function_call_output",
}
]
run_result = DummyResult()
async def fake_run(
cls,
starting_agent,
input,
*,
context,
max_turns,
hooks,
run_config,
previous_response_id,
conversation_id,
session,
):
del (
cls,
starting_agent,
input,
context,
max_turns,
hooks,
run_config,
previous_response_id,
conversation_id,
session,
)
return run_result
monkeypatch.setattr(Runner, "run", classmethod(fake_run))
tool = agent.as_tool(
tool_name="summary_tool",
tool_description="Summarize current run output",
)
tool_context = ToolContext(
context=None,
tool_name="summary_tool",
tool_call_id="call_1",
tool_arguments='{"input": "hello"}',
)
output = await tool.on_invoke_tool(tool_context, '{"input": "hello"}')
assert output == "Current run summary"
@pytest.mark.asyncio
async def test_agent_as_tool_fallback_returns_most_recent_current_run_output(
monkeypatch: pytest.MonkeyPatch,
) -> None:
agent = Agent(name="summarizer")
older_message = ResponseOutputMessage(
id="msg_older",
role="assistant",
status="completed",
type="message",
content=[
ResponseOutputText(
annotations=[],
text="Older message output",
type="output_text",
logprobs=[],
)
],
)
class DummyResult:
def __init__(self) -> None:
self.final_output = ""
self.new_items = [
MessageOutputItem(agent=agent, raw_item=older_message),
ToolCallOutputItem(
agent=agent,
raw_item={
"call_id": "call_current",
"output": "Newest tool output",
"type": "function_call_output",
},
output="Newest tool output",
),
]
run_result = DummyResult()
async def fake_run(
cls,
starting_agent,
input,
*,
context,
max_turns,
hooks,
run_config,
previous_response_id,
conversation_id,
session,
):
del (
cls,
starting_agent,
input,
context,
max_turns,
hooks,
run_config,
previous_response_id,
conversation_id,
session,
)
return run_result
monkeypatch.setattr(Runner, "run", classmethod(fake_run))
tool = agent.as_tool(
tool_name="summary_tool",
tool_description="Summarize current run output",
)
tool_context = ToolContext(
context=None,
tool_name="summary_tool",
tool_call_id="call_1",
tool_arguments='{"input": "hello"}',
)
output = await tool.on_invoke_tool(tool_context, '{"input": "hello"}')
assert output == "Newest tool output"
@pytest.mark.asyncio
async def test_agent_as_tool_extractor_can_access_agent_tool_invocation(
monkeypatch: pytest.MonkeyPatch,
) -> None:
agent = Agent(name="nested_agent")
run_result = RunResult(
input="hello",
new_items=[],
raw_responses=[],
final_output="done",
input_guardrail_results=[],
output_guardrail_results=[],
tool_input_guardrail_results=[],
tool_output_guardrail_results=[],
context_wrapper=ToolContext(
context=None,
tool_name="nested_tool",
tool_call_id="call_abc_123",
tool_arguments='{"input": "hello"}',
),
_last_agent=agent,
)
async def fake_run(
cls,
starting_agent,
input,
*,
context,
max_turns,
hooks,
run_config,
previous_response_id,
conversation_id,
session,
):
del cls, starting_agent, input, context, max_turns, hooks, run_config
del previous_response_id, conversation_id, session
return run_result
monkeypatch.setattr(Runner, "run", classmethod(fake_run))
received_tool_call_id: str | None = None
async def extractor(result: RunResult | RunResultStreaming) -> str:
nonlocal received_tool_call_id
invocation = result.agent_tool_invocation
assert invocation is not None
received_tool_call_id = invocation.tool_call_id
assert invocation.tool_name == "nested_tool"
assert invocation.tool_arguments == '{"input": "hello"}'
return "extracted"
tool = agent.as_tool(
tool_name="nested_tool",
tool_description="A nested agent tool",
custom_output_extractor=extractor,
)
parent_tool_context = ToolContext(
context=None,
tool_name="nested_tool",
tool_call_id="call_abc_123",
tool_arguments='{"input": "hello"}',
)
output = await tool.on_invoke_tool(parent_tool_context, '{"input": "hello"}')
assert output == "extracted"
assert received_tool_call_id == "call_abc_123"
@pytest.mark.asyncio
async def test_agent_as_tool_inherits_parent_run_config_when_not_set(
monkeypatch: pytest.MonkeyPatch,
) -> None:
agent = Agent(name="inherits_config_agent")
parent_run_config = RunConfig(model="gpt-4.1-mini")
class DummyResult:
def __init__(self) -> None:
self.final_output = "ok"
async def fake_run(
cls,
starting_agent,
input,
*,
context,
max_turns,
hooks,
run_config,
previous_response_id,
conversation_id,
session,
):
assert starting_agent is agent
assert input == "hello"
assert isinstance(context, ToolContext)
assert run_config is parent_run_config
assert context.run_config is parent_run_config
return DummyResult()
monkeypatch.setattr(Runner, "run", classmethod(fake_run))
tool = agent.as_tool(
tool_name="inherits_config_tool",
tool_description="inherit config",
)
tool_context = ToolContext(
context=None,
tool_name="inherits_config_tool",
tool_call_id="call_inherit",
tool_arguments='{"input":"hello"}',
run_config=parent_run_config,
)
output = await tool.on_invoke_tool(tool_context, '{"input":"hello"}')
assert output == "ok"
@pytest.mark.asyncio
async def test_agent_as_tool_explicit_run_config_overrides_parent_context(
monkeypatch: pytest.MonkeyPatch,
) -> None:
agent = Agent(name="override_config_agent")
parent_run_config = RunConfig(model="gpt-4.1-mini")
explicit_run_config = RunConfig(model="gpt-4.1")
class DummyResult:
def __init__(self) -> None:
self.final_output = "ok"
async def fake_run(
cls,
starting_agent,
input,
*,
context,
max_turns,
hooks,
run_config,
previous_response_id,
conversation_id,
session,
):
assert starting_agent is agent
assert input == "hello"
assert isinstance(context, ToolContext)
assert run_config is explicit_run_config
assert context.run_config is explicit_run_config
return DummyResult()
monkeypatch.setattr(Runner, "run", classmethod(fake_run))
tool = agent.as_tool(
tool_name="override_config_tool",
tool_description="override config",
run_config=explicit_run_config,
)
tool_context = ToolContext(
context=None,
tool_name="override_config_tool",
tool_call_id="call_override",
tool_arguments='{"input":"hello"}',
run_config=parent_run_config,
)
output = await tool.on_invoke_tool(tool_context, '{"input":"hello"}')
assert output == "ok"
@pytest.mark.asyncio
async def test_agent_as_tool_inherits_trace_include_sensitive_data_setting(
monkeypatch: pytest.MonkeyPatch,
) -> None:
agent = Agent(name="trace_config_agent")
parent_run_config = RunConfig(trace_include_sensitive_data=False)
class DummyResult:
def __init__(self) -> None:
self.final_output = "ok"
async def fake_run(
cls,
starting_agent,
input,
*,
context,
max_turns,
hooks,
run_config,
previous_response_id,
conversation_id,
session,
):
assert starting_agent is agent
assert input == "hello"
assert isinstance(context, ToolContext)
assert run_config is parent_run_config
assert run_config.trace_include_sensitive_data is False
return DummyResult()
monkeypatch.setattr(Runner, "run", classmethod(fake_run))
tool = agent.as_tool(
tool_name="trace_config_tool",
tool_description="inherits trace config",
)
tool_context = ToolContext(
context=None,
tool_name="trace_config_tool",
tool_call_id="call_trace",
tool_arguments='{"input":"hello"}',
run_config=parent_run_config,
)
output = await tool.on_invoke_tool(tool_context, '{"input":"hello"}')
assert output == "ok"
@pytest.mark.asyncio
async def test_agent_as_tool_structured_input_sets_tool_input(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Structured agent tools should capture input data and pass JSON to the nested run."""
class TranslationInput(BaseModel):
text: str
source: str
target: str
agent = Agent(name="translator")
tool = agent.as_tool(
tool_name="translate",
tool_description="Translate text",
parameters=TranslationInput,
)
captured: dict[str, Any] = {}
class DummyResult:
def __init__(self) -> None:
self.final_output = "ok"
async def fake_run(
cls,
starting_agent,
input,
*,
context,
max_turns,
hooks,
run_config,
previous_response_id,
conversation_id,
session,
):
captured["input"] = input
captured["context"] = context
return DummyResult()
monkeypatch.setattr(Runner, "run", classmethod(fake_run))
run_context = RunContextWrapper({"locale": "en-US"})
args = {"text": "hola", "source": "es", "target": "en"}
tool_context = ToolContext(
context=run_context.context,
usage=run_context.usage,
tool_name="translate",
tool_call_id="call_structured",
tool_arguments=json.dumps(args),
)
await tool.on_invoke_tool(tool_context, json.dumps(args))
called_input = captured["input"]
assert isinstance(called_input, str)
assert json.loads(called_input) == args
nested_context = captured["context"]
assert isinstance(nested_context, ToolContext)
assert nested_context.context is run_context.context
assert nested_context.usage is run_context.usage
assert nested_context.tool_input == args
assert run_context.tool_input is None
@pytest.mark.asyncio
async def test_agent_as_tool_clears_stale_tool_input_for_plain_tools(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Non-structured agent tools should not inherit stale tool input."""
agent = Agent(name="plain_agent")
tool = agent.as_tool(
tool_name="plain_tool",
tool_description="Plain tool",
)
run_context = RunContextWrapper({"locale": "en-US"})
run_context.tool_input = {"text": "bonjour"}
tool_context = ToolContext(
context=run_context.context,
usage=run_context.usage,
tool_name="plain_tool",
tool_call_id="call_plain",
tool_arguments='{"input": "hello"}',
)
tool_context.tool_input = run_context.tool_input
class DummyResult:
def __init__(self) -> None:
self.final_output = "ok"
async def fake_run(
cls,
starting_agent,
input,
*,
context,
max_turns,
hooks,
run_config,
previous_response_id,
conversation_id,
session,
):
assert isinstance(context, ToolContext)
assert context.tool_input is None
return DummyResult()
monkeypatch.setattr(Runner, "run", classmethod(fake_run))
await tool.on_invoke_tool(tool_context, '{"input": "hello"}')
assert run_context.tool_input == {"text": "bonjour"}
@pytest.mark.asyncio
async def test_agent_as_tool_includes_schema_summary_with_descriptions(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Schema descriptions should be summarized for structured inputs."""
class TranslationInput(BaseModel):
text: str = Field(description="Text to translate")
target: str = Field(description="Target language")
agent = Agent(name="summary_agent")
tool = agent.as_tool(
tool_name="summarize_schema",
tool_description="Summary tool",
parameters=TranslationInput,
)
captured: dict[str, Any] = {}
class DummyResult:
def __init__(self) -> None:
self.final_output = "ok"
async def fake_run(
cls,
starting_agent,
input,
*,
context,
max_turns,
hooks,
run_config,
previous_response_id,
conversation_id,
session,
):
captured["input"] = input
return DummyResult()
monkeypatch.setattr(Runner, "run", classmethod(fake_run))
args = {"text": "hola", "target": "en"}
tool_context = ToolContext(
context=None,
tool_name="summarize_schema",
tool_call_id="call_summary",
tool_arguments=json.dumps(args),
)
await tool.on_invoke_tool(tool_context, json.dumps(args))
called_input = captured["input"]
assert isinstance(called_input, str)
assert "Input Schema Summary:" in called_input
assert "text (string, required)" in called_input
assert "Text to translate" in called_input
assert "target (string, required)" in called_input
assert "Target language" in called_input
assert '"text": "hola"' in called_input
assert '"target": "en"' in called_input
@pytest.mark.asyncio
async def test_agent_as_tool_supports_custom_input_builder(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Custom input builders should supply nested input items."""
class TranslationInput(BaseModel):
text: str