forked from google/adk-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_base_llm_flow.py
More file actions
567 lines (454 loc) · 17 KB
/
Copy pathtest_base_llm_flow.py
File metadata and controls
567 lines (454 loc) · 17 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
# Copyright 2025 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.
"""Unit tests for BaseLlmFlow toolset integration."""
from typing import AsyncGenerator
from unittest import mock
from unittest.mock import AsyncMock
from google.adk.agents.llm_agent import Agent
from google.adk.events.event import Event
from google.adk.flows.llm_flows.base_llm_flow import BaseLlmFlow
from google.adk.models.google_llm import Gemini
from google.adk.models.llm_request import LlmRequest
from google.adk.models.llm_response import LlmResponse
from google.adk.plugins.base_plugin import BasePlugin
from google.adk.tools.base_toolset import BaseToolset
from google.adk.tools.google_search_tool import GoogleSearchTool
from google.adk.tools.tool_context import ToolContext
from google.genai import types
import pytest
from ... import testing_utils
google_search = GoogleSearchTool(bypass_multi_tools_limit=True)
class BaseLlmFlowForTesting(BaseLlmFlow):
"""Test implementation of BaseLlmFlow for testing purposes."""
pass
@pytest.mark.asyncio
async def test_preprocess_calls_toolset_process_llm_request():
"""Test that _preprocess_async calls process_llm_request on toolsets."""
# Create a mock toolset that tracks if process_llm_request was called
class _MockToolset(BaseToolset):
def __init__(self):
super().__init__()
self.process_llm_request_called = False
self.process_llm_request = AsyncMock(side_effect=self._track_call)
async def _track_call(self, **kwargs):
self.process_llm_request_called = True
async def get_tools(self, readonly_context=None):
return []
async def close(self):
pass
mock_toolset = _MockToolset()
# Create a mock model that returns a simple response
mock_response = LlmResponse(
content=types.Content(
role='model', parts=[types.Part.from_text(text='Test response')]
),
partial=False,
)
mock_model = testing_utils.MockModel.create(responses=[mock_response])
# Create agent with the mock toolset
agent = Agent(name='test_agent', model=mock_model, tools=[mock_toolset])
invocation_context = await testing_utils.create_invocation_context(
agent=agent, user_content='test message'
)
flow = BaseLlmFlowForTesting()
# Call _preprocess_async
llm_request = LlmRequest()
events = []
async for event in flow._preprocess_async(invocation_context, llm_request):
events.append(event)
# Verify that process_llm_request was called on the toolset
assert mock_toolset.process_llm_request_called
@pytest.mark.asyncio
async def test_preprocess_calls_toolset_generate_preprocessing_events():
"""Test that _preprocess_async calls generate_preprocessing_events on toolsets."""
# Create a mock toolset that tracks if generate_preprocessing_events was called
class _MockToolset(BaseToolset):
def __init__(self):
super().__init__()
self.generate_preprocessing_events_called = False
self.generated_events = []
async def generate_preprocessing_events(
self, *, tool_context: ToolContext, llm_request: LlmRequest
) -> AsyncGenerator[Event, None]:
self.generate_preprocessing_events_called = True
# Generate a mock authentication event
auth_event = Event(
author='system',
invocation_id='test_invocation',
content=types.Content(
role='model',
parts=[types.Part(text='Mock authentication request')],
),
)
self.generated_events.append(auth_event)
yield auth_event
async def get_tools(self, readonly_context=None):
return []
async def close(self):
pass
mock_toolset = _MockToolset()
# Create a mock model that returns a simple response
mock_response = LlmResponse(
content=types.Content(
role='model', parts=[types.Part.from_text(text='Test response')]
),
partial=False,
)
mock_model = testing_utils.MockModel.create(responses=[mock_response])
# Create agent with the mock toolset
agent = Agent(name='test_agent', model=mock_model, tools=[mock_toolset])
invocation_context = await testing_utils.create_invocation_context(
agent=agent, user_content='test message'
)
flow = BaseLlmFlowForTesting()
# Call _preprocess_async
llm_request = LlmRequest()
events = []
async for event in flow._preprocess_async(invocation_context, llm_request):
events.append(event)
# Verify that generate_preprocessing_events was called on the toolset
assert mock_toolset.generate_preprocessing_events_called
# Verify that the generated event was yielded
assert len(events) == 1
assert events[0].author == 'system'
assert events[0].content.parts[0].text == 'Mock authentication request'
@pytest.mark.asyncio
async def test_preprocess_calls_both_generate_events_and_process_request():
"""Test that _preprocess_async calls both generate_preprocessing_events and process_llm_request."""
# Create a mock toolset that tracks both method calls
class _MockToolset(BaseToolset):
def __init__(self):
super().__init__()
self.generate_preprocessing_events_called = False
self.process_llm_request_called = False
self.call_order = []
async def generate_preprocessing_events(
self, *, tool_context: ToolContext, llm_request: LlmRequest
) -> AsyncGenerator[Event, None]:
self.generate_preprocessing_events_called = True
self.call_order.append('generate_preprocessing_events')
# Generate a mock event
yield Event(
author='system',
invocation_id='test_invocation',
content=types.Content(
role='model', parts=[types.Part(text='Mock event')]
),
)
async def process_llm_request(
self, *, tool_context: ToolContext, llm_request: LlmRequest
) -> None:
self.process_llm_request_called = True
self.call_order.append('process_llm_request')
async def get_tools(self, readonly_context=None):
return []
async def close(self):
pass
mock_toolset = _MockToolset()
# Create a mock model that returns a simple response
mock_response = LlmResponse(
content=types.Content(
role='model', parts=[types.Part.from_text(text='Test response')]
),
partial=False,
)
mock_model = testing_utils.MockModel.create(responses=[mock_response])
# Create agent with the mock toolset
agent = Agent(name='test_agent', model=mock_model, tools=[mock_toolset])
invocation_context = await testing_utils.create_invocation_context(
agent=agent, user_content='test message'
)
flow = BaseLlmFlowForTesting()
# Call _preprocess_async
llm_request = LlmRequest()
events = []
async for event in flow._preprocess_async(invocation_context, llm_request):
events.append(event)
# Verify that both methods were called
assert mock_toolset.generate_preprocessing_events_called
assert mock_toolset.process_llm_request_called
# Verify the correct call order (generate_preprocessing_events first)
assert mock_toolset.call_order == [
'generate_preprocessing_events',
'process_llm_request',
]
# Verify that the generated event was yielded
assert len(events) == 1
assert events[0].author == 'system'
assert events[0].content.parts[0].text == 'Mock event'
@pytest.mark.asyncio
async def test_preprocess_handles_mixed_tools_and_toolsets():
"""Test that _preprocess_async properly handles both tools and toolsets."""
from google.adk.tools.base_tool import BaseTool
# Create a mock tool
class _MockTool(BaseTool):
def __init__(self):
super().__init__(name='mock_tool', description='Mock tool')
self.process_llm_request_called = False
self.process_llm_request = AsyncMock(side_effect=self._track_call)
async def _track_call(self, **kwargs):
self.process_llm_request_called = True
async def call(self, **kwargs):
return 'mock result'
# Create a mock toolset
class _MockToolset(BaseToolset):
def __init__(self):
super().__init__()
self.process_llm_request_called = False
self.process_llm_request = AsyncMock(side_effect=self._track_call)
async def _track_call(self, **kwargs):
self.process_llm_request_called = True
async def get_tools(self, readonly_context=None):
return []
async def close(self):
pass
def _test_function():
"""Test function tool."""
return 'function result'
mock_tool = _MockTool()
mock_toolset = _MockToolset()
# Create agent with mixed tools and toolsets
agent = Agent(
name='test_agent', tools=[mock_tool, _test_function, mock_toolset]
)
invocation_context = await testing_utils.create_invocation_context(
agent=agent, user_content='test message'
)
flow = BaseLlmFlowForTesting()
# Call _preprocess_async
llm_request = LlmRequest()
events = []
async for event in flow._preprocess_async(invocation_context, llm_request):
events.append(event)
# Verify that process_llm_request was called on both tools and toolsets
assert mock_tool.process_llm_request_called
assert mock_toolset.process_llm_request_called
# TODO(b/448114567): Remove the following test_preprocess_with_google_search
# tests once the workaround is no longer needed.
@pytest.mark.asyncio
async def test_preprocess_with_google_search_only():
"""Test _preprocess_async with only the google_search tool."""
agent = Agent(name='test_agent', model='gemini-pro', tools=[google_search])
invocation_context = await testing_utils.create_invocation_context(
agent=agent, user_content='test message'
)
flow = BaseLlmFlowForTesting()
llm_request = LlmRequest(model='gemini-pro')
async for _ in flow._preprocess_async(invocation_context, llm_request):
pass
assert len(llm_request.config.tools) == 1
assert llm_request.config.tools[0].google_search is not None
@pytest.mark.asyncio
async def test_preprocess_with_google_search_workaround():
"""Test _preprocess_async with google_search and another tool."""
def _my_tool(sides: int) -> int:
"""A simple tool."""
return sides
agent = Agent(
name='test_agent', model='gemini-pro', tools=[_my_tool, google_search]
)
invocation_context = await testing_utils.create_invocation_context(
agent=agent, user_content='test message'
)
flow = BaseLlmFlowForTesting()
llm_request = LlmRequest(model='gemini-pro')
async for _ in flow._preprocess_async(invocation_context, llm_request):
pass
assert len(llm_request.config.tools) == 1
declarations = llm_request.config.tools[0].function_declarations
assert len(declarations) == 2
assert {d.name for d in declarations} == {'_my_tool', 'google_search_agent'}
@pytest.mark.asyncio
async def test_preprocess_calls_convert_tool_union_to_tools():
"""Test that _preprocess_async calls _convert_tool_union_to_tools."""
class _MockTool:
process_llm_request = AsyncMock()
mock_tool_instance = _MockTool()
def _my_tool(sides: int) -> int:
"""A simple tool."""
return sides
with mock.patch(
'google.adk.agents.llm_agent._convert_tool_union_to_tools',
new_callable=AsyncMock,
) as mock_convert:
mock_convert.return_value = [mock_tool_instance]
model = Gemini(model='gemini-2')
agent = Agent(
name='test_agent', model=model, tools=[_my_tool, google_search]
)
invocation_context = await testing_utils.create_invocation_context(
agent=agent, user_content='test message'
)
flow = BaseLlmFlowForTesting()
llm_request = LlmRequest(model='gemini-2')
async for _ in flow._preprocess_async(invocation_context, llm_request):
pass
mock_convert.assert_called_with(
google_search,
mock.ANY, # ReadonlyContext(invocation_context)
model,
True, # multiple_tools
)
# TODO(b/448114567): Remove the following
# test_handle_after_model_callback_grounding tests once the workaround
# is no longer needed.
def dummy_tool():
pass
@pytest.mark.parametrize(
'tools, state_metadata, expect_metadata',
[
([], None, False),
([google_search, dummy_tool], {'foo': 'bar'}, True),
([dummy_tool], {'foo': 'bar'}, False),
([google_search, dummy_tool], None, False),
],
ids=[
'no_search_no_grounding',
'with_search_with_grounding',
'no_search_with_grounding',
'with_search_no_grounding',
],
)
@pytest.mark.asyncio
async def test_handle_after_model_callback_grounding_with_no_callbacks(
tools, state_metadata, expect_metadata
):
"""Test handling grounding metadata when there are no callbacks."""
agent = Agent(name='test_agent', tools=tools)
invocation_context = await testing_utils.create_invocation_context(
agent=agent
)
if state_metadata:
invocation_context.session.state['temp:_adk_grounding_metadata'] = (
state_metadata
)
llm_response = LlmResponse(
content=types.Content(parts=[types.Part.from_text(text='response')])
)
event = Event(
id=Event.new_id(),
invocation_id=invocation_context.invocation_id,
author=agent.name,
)
flow = BaseLlmFlowForTesting()
result = await flow._handle_after_model_callback(
invocation_context, llm_response, event
)
if expect_metadata:
llm_response.grounding_metadata = state_metadata
assert result == llm_response
else:
assert result is None
@pytest.mark.parametrize(
'tools, state_metadata, expect_metadata',
[
([], None, False),
([google_search, dummy_tool], {'foo': 'bar'}, True),
([dummy_tool], {'foo': 'bar'}, False),
([google_search, dummy_tool], None, False),
],
ids=[
'no_search_no_grounding',
'with_search_with_grounding',
'no_search_with_grounding',
'with_search_no_grounding',
],
)
@pytest.mark.asyncio
async def test_handle_after_model_callback_grounding_with_callback_override(
tools, state_metadata, expect_metadata
):
"""Test handling grounding metadata when there is a callback override."""
agent_response = LlmResponse(
content=types.Content(parts=[types.Part.from_text(text='agent')])
)
agent_callback = AsyncMock(return_value=agent_response)
agent = Agent(
name='test_agent', tools=tools, after_model_callback=[agent_callback]
)
invocation_context = await testing_utils.create_invocation_context(
agent=agent
)
if state_metadata:
invocation_context.session.state['temp:_adk_grounding_metadata'] = (
state_metadata
)
llm_response = LlmResponse(
content=types.Content(parts=[types.Part.from_text(text='response')])
)
event = Event(
id=Event.new_id(),
invocation_id=invocation_context.invocation_id,
author=agent.name,
)
flow = BaseLlmFlowForTesting()
result = await flow._handle_after_model_callback(
invocation_context, llm_response, event
)
if expect_metadata:
agent_response.grounding_metadata = state_metadata
assert result == agent_response
agent_callback.assert_called_once()
@pytest.mark.parametrize(
'tools, state_metadata, expect_metadata',
[
([], None, False),
([google_search, dummy_tool], {'foo': 'bar'}, True),
([dummy_tool], {'foo': 'bar'}, False),
([google_search, dummy_tool], None, False),
],
ids=[
'no_search_no_grounding',
'with_search_with_grounding',
'no_search_with_grounding',
'with_search_no_grounding',
],
)
@pytest.mark.asyncio
async def test_handle_after_model_callback_grounding_with_plugin_override(
tools, state_metadata, expect_metadata
):
"""Test handling grounding metadata when there is a plugin override."""
plugin_response = LlmResponse(
content=types.Content(parts=[types.Part.from_text(text='plugin')])
)
class _MockPlugin(BasePlugin):
def __init__(self):
super().__init__(name='mock_plugin')
after_model_callback = AsyncMock(return_value=plugin_response)
plugin = _MockPlugin()
agent = Agent(name='test_agent', tools=tools)
invocation_context = await testing_utils.create_invocation_context(
agent=agent, plugins=[plugin]
)
if state_metadata:
invocation_context.session.state['temp:_adk_grounding_metadata'] = (
state_metadata
)
llm_response = LlmResponse(
content=types.Content(parts=[types.Part.from_text(text='response')])
)
event = Event(
id=Event.new_id(),
invocation_id=invocation_context.invocation_id,
author=agent.name,
)
flow = BaseLlmFlowForTesting()
result = await flow._handle_after_model_callback(
invocation_context, llm_response, event
)
if expect_metadata:
plugin_response.grounding_metadata = state_metadata
assert result == plugin_response
plugin.after_model_callback.assert_called_once()