-
Notifications
You must be signed in to change notification settings - Fork 3.9k
Expand file tree
/
Copy pathtest_function_tool.py
More file actions
641 lines (494 loc) · 21.7 KB
/
Copy pathtest_function_tool.py
File metadata and controls
641 lines (494 loc) · 21.7 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
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from unittest.mock import MagicMock
from google.adk.agents.context import Context
from google.adk.agents.invocation_context import InvocationContext
from google.adk.sessions.session import Session
from google.adk.tools.function_tool import FunctionTool
from google.adk.tools.tool_confirmation import ToolConfirmation
from google.adk.tools.tool_context import ToolContext
import pytest
@pytest.fixture
def mock_tool_context() -> ToolContext:
"""Fixture that provides a mock ToolContext for testing."""
mock_invocation_context = MagicMock(spec=InvocationContext)
mock_invocation_context._state_schema = None
mock_invocation_context.session = MagicMock(spec=Session)
mock_invocation_context.session.state = MagicMock()
return ToolContext(invocation_context=mock_invocation_context)
def function_for_testing_with_no_args():
"""Function for testing with no args."""
pass
async def async_function_for_testing_with_1_arg_and_tool_context(
arg1, tool_context
):
"""Async function for testing with 1 arg and tool context."""
assert arg1
assert tool_context
return arg1
async def async_function_for_testing_with_2_arg_and_no_tool_context(arg1, arg2):
"""Async function for testing with 2 args and no tool context."""
assert arg1
assert arg2
return arg1
class AsyncCallableWith2ArgsAndNoToolContext:
def __init__(self):
self.__name__ = "Async callable name"
self.__doc__ = "Async callable doc"
async def __call__(self, arg1, arg2):
assert arg1
assert arg2
return arg1
def function_for_testing_with_1_arg_and_tool_context(arg1, tool_context):
"""Function for testing with 1 arg and tool context."""
assert arg1
assert tool_context
return arg1
class AsyncCallableWith1ArgAndToolContext:
async def __call__(self, arg1, tool_context):
"""Async call doc"""
assert arg1
assert tool_context
return arg1
def function_for_testing_with_2_arg_and_no_tool_context(arg1, arg2):
"""Function for testing with 2 args and no tool context."""
assert arg1
assert arg2
return arg1
async def async_function_for_testing_with_4_arg_and_no_tool_context(
arg1, arg2, arg3, arg4
):
"""Async function for testing with 4 args."""
pass
def function_for_testing_with_4_arg_and_no_tool_context(arg1, arg2, arg3, arg4):
"""Function for testing with 4 args."""
pass
def function_returning_none() -> None:
"""Function for testing with no return value."""
return None
def function_returning_empty_dict() -> dict[str, str]:
"""Function for testing with empty dict return value."""
return {}
def test_init():
"""Test that the FunctionTool is initialized correctly."""
tool = FunctionTool(function_for_testing_with_no_args)
assert tool.name == "function_for_testing_with_no_args"
assert tool.description == "Function for testing with no args."
assert tool.func == function_for_testing_with_no_args
@pytest.mark.asyncio
async def test_function_returning_none():
"""Test that the function returns with None actually returning None."""
tool = FunctionTool(function_returning_none)
result = await tool.run_async(args={}, tool_context=MagicMock())
assert result is None
@pytest.mark.asyncio
async def test_function_returning_empty_dict():
"""Test that the function returns with empty dict actually returning empty dict."""
tool = FunctionTool(function_returning_empty_dict)
result = await tool.run_async(args={}, tool_context=MagicMock())
assert isinstance(result, dict)
@pytest.mark.asyncio
async def test_run_async_with_tool_context_async_func():
"""Test that run_async calls the function with tool_context when tool_context is in signature (async function)."""
tool = FunctionTool(async_function_for_testing_with_1_arg_and_tool_context)
args = {"arg1": "test_value_1"}
result = await tool.run_async(args=args, tool_context=MagicMock())
assert result == "test_value_1"
@pytest.mark.asyncio
async def test_run_async_with_tool_context_async_callable():
"""Test that run_async calls the callable with tool_context when tool_context is in signature (async callable)."""
tool = FunctionTool(AsyncCallableWith1ArgAndToolContext())
args = {"arg1": "test_value_1"}
result = await tool.run_async(args=args, tool_context=MagicMock())
assert result == "test_value_1"
assert tool.name == "AsyncCallableWith1ArgAndToolContext"
assert tool.description == "Async call doc"
@pytest.mark.asyncio
async def test_run_async_without_tool_context_async_func():
"""Test that run_async calls the function without tool_context when tool_context is not in signature (async function)."""
tool = FunctionTool(async_function_for_testing_with_2_arg_and_no_tool_context)
args = {"arg1": "test_value_1", "arg2": "test_value_2"}
result = await tool.run_async(args=args, tool_context=MagicMock())
assert result == "test_value_1"
@pytest.mark.asyncio
async def test_run_async_without_tool_context_async_callable():
"""Test that run_async calls the callable without tool_context when tool_context is not in signature (async callable)."""
tool = FunctionTool(AsyncCallableWith2ArgsAndNoToolContext())
args = {"arg1": "test_value_1", "arg2": "test_value_2"}
result = await tool.run_async(args=args, tool_context=MagicMock())
assert result == "test_value_1"
assert tool.name == "Async callable name"
assert tool.description == "Async callable doc"
@pytest.mark.asyncio
async def test_run_async_with_tool_context_sync_func():
"""Test that run_async calls the function with tool_context when tool_context is in signature (synchronous function)."""
tool = FunctionTool(function_for_testing_with_1_arg_and_tool_context)
args = {"arg1": "test_value_1"}
result = await tool.run_async(args=args, tool_context=MagicMock())
assert result == "test_value_1"
@pytest.mark.asyncio
async def test_run_async_without_tool_context_sync_func():
"""Test that run_async calls the function without tool_context when tool_context is not in signature (synchronous function)."""
tool = FunctionTool(function_for_testing_with_2_arg_and_no_tool_context)
args = {"arg1": "test_value_1", "arg2": "test_value_2"}
result = await tool.run_async(args=args, tool_context=MagicMock())
assert result == "test_value_1"
@pytest.mark.asyncio
async def test_run_async_1_missing_arg_sync_func():
"""Test that run_async calls the function with 1 missing arg in signature (synchronous function)."""
tool = FunctionTool(function_for_testing_with_2_arg_and_no_tool_context)
args = {"arg1": "test_value_1"}
result = await tool.run_async(args=args, tool_context=MagicMock())
assert result == {
"error": (
"""Invoking `function_for_testing_with_2_arg_and_no_tool_context()` failed as the following mandatory input parameters are not present:
arg2
You could retry calling this tool, but it is IMPORTANT for you to provide all the mandatory parameters."""
)
}
@pytest.mark.asyncio
async def test_run_async_1_missing_arg_async_func():
"""Test that run_async calls the function with 1 missing arg in signature (async function)."""
tool = FunctionTool(async_function_for_testing_with_2_arg_and_no_tool_context)
args = {"arg2": "test_value_1"}
result = await tool.run_async(args=args, tool_context=MagicMock())
assert result == {
"error": (
"""Invoking `async_function_for_testing_with_2_arg_and_no_tool_context()` failed as the following mandatory input parameters are not present:
arg1
You could retry calling this tool, but it is IMPORTANT for you to provide all the mandatory parameters."""
)
}
@pytest.mark.asyncio
async def test_run_async_3_missing_arg_sync_func():
"""Test that run_async calls the function with 3 missing args in signature (synchronous function)."""
tool = FunctionTool(function_for_testing_with_4_arg_and_no_tool_context)
args = {"arg2": "test_value_1"}
result = await tool.run_async(args=args, tool_context=MagicMock())
assert result == {
"error": (
"""Invoking `function_for_testing_with_4_arg_and_no_tool_context()` failed as the following mandatory input parameters are not present:
arg1
arg3
arg4
You could retry calling this tool, but it is IMPORTANT for you to provide all the mandatory parameters."""
)
}
@pytest.mark.asyncio
async def test_run_async_3_missing_arg_async_func():
"""Test that run_async calls the function with 3 missing args in signature (async function)."""
tool = FunctionTool(async_function_for_testing_with_4_arg_and_no_tool_context)
args = {"arg3": "test_value_1"}
result = await tool.run_async(args=args, tool_context=MagicMock())
assert result == {
"error": (
"""Invoking `async_function_for_testing_with_4_arg_and_no_tool_context()` failed as the following mandatory input parameters are not present:
arg1
arg2
arg4
You could retry calling this tool, but it is IMPORTANT for you to provide all the mandatory parameters."""
)
}
@pytest.mark.asyncio
async def test_run_async_missing_all_arg_sync_func():
"""Test that run_async calls the function with all missing args in signature (synchronous function)."""
tool = FunctionTool(function_for_testing_with_4_arg_and_no_tool_context)
args = {}
result = await tool.run_async(args=args, tool_context=MagicMock())
assert result == {
"error": (
"""Invoking `function_for_testing_with_4_arg_and_no_tool_context()` failed as the following mandatory input parameters are not present:
arg1
arg2
arg3
arg4
You could retry calling this tool, but it is IMPORTANT for you to provide all the mandatory parameters."""
)
}
@pytest.mark.asyncio
async def test_run_async_missing_all_arg_async_func():
"""Test that run_async calls the function with all missing args in signature (async function)."""
tool = FunctionTool(async_function_for_testing_with_4_arg_and_no_tool_context)
args = {}
result = await tool.run_async(args=args, tool_context=MagicMock())
assert result == {
"error": (
"""Invoking `async_function_for_testing_with_4_arg_and_no_tool_context()` failed as the following mandatory input parameters are not present:
arg1
arg2
arg3
arg4
You could retry calling this tool, but it is IMPORTANT for you to provide all the mandatory parameters."""
)
}
@pytest.mark.asyncio
async def test_run_async_with_optional_args_not_set_sync_func():
"""Test that run_async calls the function for sync function with optional args not set."""
def func_with_optional_args(arg1, arg2=None, *, arg3, arg4=None, **kwargs):
return f"{arg1},{arg3}"
tool = FunctionTool(func_with_optional_args)
args = {"arg1": "test_value_1", "arg3": "test_value_3"}
result = await tool.run_async(args=args, tool_context=MagicMock())
assert result == "test_value_1,test_value_3"
@pytest.mark.asyncio
async def test_run_async_with_optional_args_not_set_async_func():
"""Test that run_async calls the function for async function with optional args not set."""
async def async_func_with_optional_args(
arg1, arg2=None, *, arg3, arg4=None, **kwargs
):
return f"{arg1},{arg3}"
tool = FunctionTool(async_func_with_optional_args)
args = {"arg1": "test_value_1", "arg3": "test_value_3"}
result = await tool.run_async(args=args, tool_context=MagicMock())
assert result == "test_value_1,test_value_3"
@pytest.mark.asyncio
async def test_run_async_with_unexpected_argument():
"""Test that run_async filters out unexpected arguments."""
def sample_func(expected_arg: str):
return {"received_arg": expected_arg}
tool = FunctionTool(sample_func)
mock_invocation_context = MagicMock(spec=InvocationContext)
mock_invocation_context._state_schema = None
mock_invocation_context.session = MagicMock(spec=Session)
# Add the missing state attribute to the session mock
mock_invocation_context.session.state = MagicMock()
tool_context_mock = ToolContext(invocation_context=mock_invocation_context)
result = await tool.run_async(
args={"expected_arg": "hello", "parameters": "should_be_filtered"},
tool_context=tool_context_mock,
)
assert result == {"received_arg": "hello"}
@pytest.mark.asyncio
async def test_run_async_with_tool_context_and_unexpected_argument():
"""Test that run_async handles tool_context and filters out unexpected arguments."""
def sample_func_with_context(expected_arg: str, tool_context: ToolContext):
return {"received_arg": expected_arg, "context_present": bool(tool_context)}
tool = FunctionTool(sample_func_with_context)
mock_invocation_context = MagicMock(spec=InvocationContext)
mock_invocation_context._state_schema = None
mock_invocation_context.session = MagicMock(spec=Session)
# Add the missing state attribute to the session mock
mock_invocation_context.session.state = MagicMock()
mock_tool_context = ToolContext(invocation_context=mock_invocation_context)
result = await tool.run_async(
args={
"expected_arg": "world",
"parameters": "should_also_be_filtered",
},
tool_context=mock_tool_context,
)
assert result == {
"received_arg": "world",
"context_present": True,
}
@pytest.mark.asyncio
async def test_run_async_with_require_confirmation():
"""Test that run_async handles require_confirmation flag."""
def sample_func(arg1: str):
return {"received_arg": arg1}
tool = FunctionTool(sample_func, require_confirmation=True)
mock_invocation_context = MagicMock(spec=InvocationContext)
mock_invocation_context._state_schema = None
mock_invocation_context.session = MagicMock(spec=Session)
mock_invocation_context.session.state = MagicMock()
mock_invocation_context.agent = MagicMock()
mock_invocation_context.agent.name = "test_agent"
tool_context_mock = ToolContext(invocation_context=mock_invocation_context)
tool_context_mock.function_call_id = "test_function_call_id"
# First call, should request confirmation
result = await tool.run_async(
args={"arg1": "hello"},
tool_context=tool_context_mock,
)
assert result == {
"error": "This tool call requires confirmation, please approve or reject."
}
assert tool_context_mock._event_actions.requested_tool_confirmations[
"test_function_call_id"
].hint == (
"Please approve or reject the tool call sample_func() by responding with"
" a FunctionResponse with an expected ToolConfirmation payload."
)
# Second call, user rejects
tool_context_mock.tool_confirmation = ToolConfirmation(confirmed=False)
result = await tool.run_async(
args={"arg1": "hello"},
tool_context=tool_context_mock,
)
assert result == {"error": "This tool call is rejected."}
# Third call, user approves
tool_context_mock.tool_confirmation = ToolConfirmation(confirmed=True)
result = await tool.run_async(
args={"arg1": "hello"},
tool_context=tool_context_mock,
)
assert result == {"received_arg": "hello"}
@pytest.mark.asyncio
async def test_run_async_parameter_filtering(mock_tool_context):
"""Test that parameter filtering works correctly for functions with explicit parameters."""
def explicit_params_func(arg1: str, arg2: int):
"""Function with explicit parameters (no **kwargs)."""
return {"arg1": arg1, "arg2": arg2}
tool = FunctionTool(explicit_params_func)
# Test that unexpected parameters are still filtered out for non-kwargs functions
result = await tool.run_async(
args={
"arg1": "test",
"arg2": 42,
"unexpected_param": "should_be_filtered",
},
tool_context=mock_tool_context,
)
assert result == {"arg1": "test", "arg2": 42}
# Explicitly verify that unexpected_param was filtered out and not passed to the function
assert "unexpected_param" not in result
def test_context_param_detection_with_context_type():
"""Test that FunctionTool detects context parameter by Context type annotation."""
def my_tool(query: str, ctx: Context) -> str:
return query
tool = FunctionTool(my_tool)
assert tool._context_param_name == "ctx"
assert tool._ignore_params == ["ctx", "input_stream", "progress_callback"]
def test_context_param_detection_with_tool_context_type():
"""Test that FunctionTool detects context parameter by ToolContext type annotation."""
def my_tool(query: str, tool_context: ToolContext) -> str:
return query
tool = FunctionTool(my_tool)
assert tool._context_param_name == "tool_context"
assert tool._ignore_params == [
"tool_context",
"input_stream",
"progress_callback",
]
def test_context_param_detection_with_custom_name():
"""Test that FunctionTool detects context parameter with any name if type is Context."""
def my_tool(query: str, my_custom_context: Context) -> str:
return query
tool = FunctionTool(my_tool)
assert tool._context_param_name == "my_custom_context"
assert tool._ignore_params == [
"my_custom_context",
"input_stream",
"progress_callback",
]
def test_context_param_detection_fallback_to_name():
"""Test that FunctionTool falls back to 'tool_context' name when no type annotation."""
def my_tool(query: str, tool_context) -> str:
return query
tool = FunctionTool(my_tool)
assert tool._context_param_name == "tool_context"
assert tool._ignore_params == [
"tool_context",
"input_stream",
"progress_callback",
]
def test_context_param_detection_no_context():
"""Test that FunctionTool defaults to 'tool_context' when no context param exists."""
def my_tool(query: str, count: int) -> str:
return query
tool = FunctionTool(my_tool)
assert tool._context_param_name == "tool_context"
assert tool._ignore_params == [
"tool_context",
"input_stream",
"progress_callback",
]
@pytest.mark.asyncio
async def test_run_async_with_custom_context_param_name(mock_tool_context):
"""Test that run_async correctly injects context with custom parameter name."""
def my_tool(query: str, ctx: Context) -> dict:
return {"query": query, "has_context": ctx is not None}
tool = FunctionTool(my_tool)
result = await tool.run_async(
args={"query": "test"},
tool_context=mock_tool_context,
)
assert result == {"query": "test", "has_context": True}
@pytest.mark.asyncio
async def test_run_async_injects_progress_callback(mock_tool_context):
"""Test that run_async injects a UI-only progress callback when declared."""
progress_events = []
async def progress_handler(tool_name, function_call_id, data):
progress_events.append((tool_name, function_call_id, data))
async def my_tool(query: str, progress_callback) -> dict:
await progress_callback({"step": 1, "message": "working"})
return {"query": query}
mock_tool_context.function_call_id = "call-123"
mock_tool_context._invocation_context.tool_progress_handler = progress_handler
tool = FunctionTool(my_tool)
result = await tool.run_async(
args={"query": "test"},
tool_context=mock_tool_context,
)
assert result == {"query": "test"}
assert progress_events == [
("my_tool", "call-123", {"step": 1, "message": "working"})
]
@pytest.mark.asyncio
async def test_run_async_progress_callback_no_handler_is_noop(
mock_tool_context,
):
"""Test that an injected progress callback is a no-op without a handler."""
async def my_tool(progress_callback) -> dict:
await progress_callback({"step": 1})
return {"ok": True}
mock_tool_context._invocation_context.tool_progress_handler = None
tool = FunctionTool(my_tool)
result = await tool.run_async(args={}, tool_context=mock_tool_context)
assert result == {"ok": True}
def test_progress_callback_is_hidden_from_declaration():
"""Test that progress_callback is not exposed in the model-facing schema."""
def my_tool(query: str, progress_callback) -> str:
"""Search with UI-only progress."""
return query
declaration = FunctionTool(my_tool)._get_declaration()
assert declaration.parameters_json_schema is not None
properties = declaration.parameters_json_schema["properties"]
assert "query" in properties
assert "progress_callback" not in properties
@pytest.mark.asyncio
async def test_call_live_injects_progress_callback(mock_tool_context):
"""Test that live streaming tools receive the progress callback."""
progress_events = []
def progress_handler(tool_name, function_call_id, data):
progress_events.append((tool_name, function_call_id, data))
async def my_tool(progress_callback):
await progress_callback({"step": "start"})
yield {"status": "done"}
mock_tool_context.function_call_id = "live-call-123"
mock_tool_context._invocation_context.tool_progress_handler = progress_handler
mock_tool_context._invocation_context.active_streaming_tools = {}
tool = FunctionTool(my_tool)
results = [
item
async for item in tool._call_live(
args={},
tool_context=mock_tool_context,
invocation_context=mock_tool_context._invocation_context,
)
]
assert results == [{"status": "done"}]
assert progress_events == [("my_tool", "live-call-123", {"step": "start"})]
@pytest.mark.asyncio
async def test_run_async_with_context_type_annotation(mock_tool_context):
"""Test that run_async works with Context type annotation."""
async def async_tool(query: str, context: Context) -> dict:
return {"query": query, "context_type": type(context).__name__}
tool = FunctionTool(async_tool)
result = await tool.run_async(
args={"query": "hello"},
tool_context=mock_tool_context,
)
assert result["query"] == "hello"
assert result["context_type"] == "Context"