-
Notifications
You must be signed in to change notification settings - Fork 3.3k
Expand file tree
/
Copy pathtest_base_llm_flow.py
More file actions
1089 lines (857 loc) · 34.1 KB
/
test_base_llm_flow.py
File metadata and controls
1089 lines (857 loc) · 34.1 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
# 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.
"""Unit tests for BaseLlmFlow toolset integration."""
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 _handle_after_model_callback
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.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_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,
)
result = await _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,
)
result = await _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,
)
result = await _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()
@pytest.mark.asyncio
async def test_handle_after_model_callback_caches_canonical_tools():
"""Test that canonical_tools is only called once per invocation_context."""
canonical_tools_call_count = 0
async def mock_canonical_tools(self, readonly_context=None):
nonlocal canonical_tools_call_count
canonical_tools_call_count += 1
from google.adk.tools.base_tool import BaseTool
class MockGoogleSearchTool(BaseTool):
def __init__(self):
super().__init__(name='google_search_agent', description='Mock search')
self.propagate_grounding_metadata = True
async def call(self, **kwargs):
return 'mock result'
return [MockGoogleSearchTool()]
agent = Agent(name='test_agent', tools=[google_search, dummy_tool])
with mock.patch.object(
type(agent), 'canonical_tools', new=mock_canonical_tools
):
invocation_context = await testing_utils.create_invocation_context(
agent=agent
)
assert invocation_context.canonical_tools_cache is None
invocation_context.session.state['temp:_adk_grounding_metadata'] = {
'foo': 'bar'
}
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,
)
# Call _handle_after_model_callback multiple times with the same context
result1 = await _handle_after_model_callback(
invocation_context, llm_response, event
)
result2 = await _handle_after_model_callback(
invocation_context, llm_response, event
)
result3 = await _handle_after_model_callback(
invocation_context, llm_response, event
)
assert canonical_tools_call_count == 1, (
'canonical_tools should be called once, but was called '
f'{canonical_tools_call_count} times'
)
assert invocation_context.canonical_tools_cache is not None
assert len(invocation_context.canonical_tools_cache) == 1
assert (
invocation_context.canonical_tools_cache[0].name
== 'google_search_agent'
)
assert result1.grounding_metadata == {'foo': 'bar'}
assert result2.grounding_metadata == {'foo': 'bar'}
assert result3.grounding_metadata == {'foo': 'bar'}
@pytest.mark.asyncio
async def test_run_live_reconnects_on_connection_closed():
"""Test that run_live reconnects when ConnectionClosed occurs."""
from google.adk.agents.live_request_queue import LiveRequestQueue
from websockets.exceptions import ConnectionClosed
real_model = Gemini()
mock_connection = mock.AsyncMock()
async def mock_receive():
# Simulate receiving a session resumption handle from the server.
yield LlmResponse(
live_session_resumption_update=types.LiveServerSessionResumptionUpdate(
new_handle='test_handle'
)
)
# Simulate connection dropping, triggering reconnection logic.
raise ConnectionClosed(None, None)
mock_connection.receive = mock.Mock(side_effect=mock_receive)
agent = Agent(name='test_agent', model=real_model)
invocation_context = await testing_utils.create_invocation_context(
agent=agent
)
invocation_context.live_request_queue = LiveRequestQueue()
flow = BaseLlmFlowForTesting()
with mock.patch.object(
flow, '_send_to_model', new_callable=AsyncMock
) as mock_send:
mock_connection_2 = mock.AsyncMock()
# We need a way to break the infinite loop in run_live for testing.
class NonRetryableError(Exception):
pass
async def mock_receive_2():
yield LlmResponse(
content=types.Content(parts=[types.Part.from_text(text='hi')])
)
# Raise non-retryable exception to exit the loop and finish test.
raise NonRetryableError('stop')
mock_connection_2.receive = mock.Mock(side_effect=mock_receive_2)
mock_aenter = mock.AsyncMock()
# First connection attempt uses mock_connection (drops), second uses mock_connection_2 (stops test).
mock_aenter.side_effect = [mock_connection, mock_connection_2]
with mock.patch(
'google.adk.models.google_llm.Gemini.connect'
) as mock_connect:
mock_connect.return_value.__aenter__ = mock_aenter
events = []
try:
async for event in flow.run_live(invocation_context):
events.append(event)
except NonRetryableError:
pass
# Verify that we attempted to connect twice (initial + reconnect).
assert mock_connect.call_count == 2
assert invocation_context.live_session_resumption_handle == 'test_handle'
@pytest.mark.asyncio
async def test_run_live_reconnects_on_api_error():
"""Test that run_live reconnects when APIError occurs."""
from google.adk.agents.live_request_queue import LiveRequestQueue
from google.genai.errors import APIError
real_model = Gemini()
mock_connection = mock.AsyncMock()
async def mock_receive():
# Simulate receiving a session resumption handle from the server.
yield LlmResponse(
live_session_resumption_update=types.LiveServerSessionResumptionUpdate(
new_handle='test_handle'
)
)
# Simulate an API error occurring, triggering reconnection logic.
raise APIError(1000, {})
mock_connection.receive = mock.Mock(side_effect=mock_receive)
agent = Agent(name='test_agent', model=real_model)
invocation_context = await testing_utils.create_invocation_context(
agent=agent
)
invocation_context.live_request_queue = LiveRequestQueue()
flow = BaseLlmFlowForTesting()
with mock.patch.object(
flow, '_send_to_model', new_callable=AsyncMock
) as mock_send:
mock_connection_2 = mock.AsyncMock()
# We need a way to break the infinite loop in run_live for testing.
class NonRetryableError(Exception):
pass
async def mock_receive_2():
yield LlmResponse(
content=types.Content(parts=[types.Part.from_text(text='hi')])
)
# Raise non-retryable exception to exit the loop and finish test.
raise NonRetryableError('stop')
mock_connection_2.receive = mock.Mock(side_effect=mock_receive_2)
mock_aenter = mock.AsyncMock()
# First connection attempt uses mock_connection (fails with APIError), second uses mock_connection_2 (stops test).
mock_aenter.side_effect = [mock_connection, mock_connection_2]
with mock.patch(
'google.adk.models.google_llm.Gemini.connect'
) as mock_connect:
mock_connect.return_value.__aenter__ = mock_aenter
events = []
try:
async for event in flow.run_live(invocation_context):
events.append(event)
except NonRetryableError:
pass
# Verify that we attempted to connect twice (initial + reconnect).
assert mock_connect.call_count == 2
assert invocation_context.live_session_resumption_handle == 'test_handle'
@pytest.mark.asyncio
async def test_run_live_skips_send_history_on_resumption():
"""Test that run_live skips send_history when resuming a session."""
from google.adk.agents.live_request_queue import LiveRequestQueue
real_model = Gemini()
mock_connection = mock.AsyncMock()
agent = Agent(name='test_agent', model=real_model)
invocation_context = await testing_utils.create_invocation_context(
agent=agent
)
# Set resumption handle to simulate a resumed session.
invocation_context.live_session_resumption_handle = 'test_handle'
invocation_context.live_request_queue = LiveRequestQueue()
flow = BaseLlmFlowForTesting()
async def mock_preprocess(ctx, req):
req.contents = [types.Content(parts=[types.Part.from_text(text='history')])]
if False:
yield
with mock.patch.object(
flow, '_preprocess_async', side_effect=mock_preprocess
):
with mock.patch.object(
flow, '_send_to_model', new_callable=AsyncMock
) as mock_send:
# We need a way to break the infinite loop in run_live for testing.
class StopError(Exception):
pass
async def mock_receive():
yield LlmResponse(
content=types.Content(parts=[types.Part.from_text(text='hi')])
)
# Raise StopError to exit the loop and finish test.
raise StopError('stop')
mock_connection.receive = mock.Mock(side_effect=mock_receive)
with mock.patch(
'google.adk.models.google_llm.Gemini.connect'
) as mock_connect:
mock_connect.return_value.__aenter__.return_value = mock_connection
try:
async for _ in flow.run_live(invocation_context):
pass
except StopError:
pass
# Verify that send_history was not called because we resumed.
mock_connection.send_history.assert_not_called()
@pytest.mark.asyncio
async def test_live_session_resumption_go_away():
"""Test that go_away triggers reconnection."""
from google.adk.agents.live_request_queue import LiveRequestQueue
real_model = Gemini()
mock_connection = mock.AsyncMock()
agent = Agent(name='test_agent', model=real_model)
invocation_context = await testing_utils.create_invocation_context(
agent=agent
)
invocation_context.live_request_queue = LiveRequestQueue()
invocation_context.live_session_resumption_handle = 'old_handle'
flow = BaseLlmFlowForTesting()
with mock.patch.object(
flow, '_send_to_model', new_callable=AsyncMock
) as mock_send:
mock_connection_2 = mock.AsyncMock()
# We need a way to break the infinite loop in run_live for testing.
class StopError(Exception):
pass
async def mock_receive_1():
# Simulate receiving a go_away signal from the server.
yield LlmResponse(go_away=types.LiveServerGoAway())
async def mock_receive_2():
yield LlmResponse(
content=types.Content(parts=[types.Part.from_text(text='hi')])
)
# Raise StopError to exit the loop and finish test.
raise StopError('stop')
mock_connection.receive = mock.Mock(side_effect=mock_receive_1)
mock_connection_2.receive = mock.Mock(side_effect=mock_receive_2)
mock_aenter = mock.AsyncMock()
# First connection attempt uses mock_connection (receives go_away), second uses mock_connection_2 (stops test).
mock_aenter.side_effect = [mock_connection, mock_connection_2]
with mock.patch(
'google.adk.models.google_llm.Gemini.connect'
) as mock_connect:
mock_connect.return_value.__aenter__ = mock_aenter
try:
async for _ in flow.run_live(invocation_context):
pass
except StopError:
pass
# Verify that we attempted to connect twice (initial + reconnect after go_away).
assert mock_connect.call_count == 2
@pytest.mark.asyncio
async def test_run_live_no_reconnect_without_handle():
"""Test that run_live does not reconnect when handle is missing."""
from google.adk.agents.live_request_queue import LiveRequestQueue
from websockets.exceptions import ConnectionClosed
real_model = Gemini()
mock_connection = mock.AsyncMock()
async def mock_receive():
# Simulate connection drop without any handle update.
if False:
yield
raise ConnectionClosed(None, None)
mock_connection.receive = mock.Mock(side_effect=mock_receive)
agent = Agent(name='test_agent', model=real_model)
invocation_context = await testing_utils.create_invocation_context(
agent=agent
)
invocation_context.live_request_queue = LiveRequestQueue()
# Ensure no handle is set
invocation_context.live_session_resumption_handle = None
flow = BaseLlmFlowForTesting()
with mock.patch.object(
flow, '_send_to_model', new_callable=AsyncMock
) as mock_send:
with mock.patch(
'google.adk.models.google_llm.Gemini.connect'
) as mock_connect:
mock_connect.return_value.__aenter__.return_value = mock_connection
with pytest.raises(ConnectionClosed):
async for _ in flow.run_live(invocation_context):
pass
# Verify that we only attempted to connect once.
assert mock_connect.call_count == 1
@pytest.mark.asyncio
async def test_run_live_reconnect_limit():
"""Test that run_live stops reconnecting after 5 attempts."""
from google.adk.agents.live_request_queue import LiveRequestQueue
from websockets.exceptions import ConnectionClosed
real_model = Gemini()
connection_cnt = 0
async def mock_connect_impl(*args, **kwargs):
nonlocal connection_cnt
connection_cnt += 1
conn = mock.AsyncMock()
async def mock_receive():
if connection_cnt == 1:
# Yield handle only on the first connection.
yield LlmResponse(
live_session_resumption_update=types.LiveServerSessionResumptionUpdate(
new_handle='test_handle'
),
turn_complete=True,
)
# All subsequent receives (and all receives on later connections) fail.
raise ConnectionClosed(None, None)
conn.receive = mock.Mock(side_effect=mock_receive)
return conn
agent = Agent(name='test_agent', model=real_model)
invocation_context = await testing_utils.create_invocation_context(
agent=agent
)
invocation_context.live_request_queue = LiveRequestQueue()
flow = BaseLlmFlowForTesting()
with mock.patch.object(
flow, '_send_to_model', new_callable=AsyncMock
) as mock_send:
with mock.patch(
'google.adk.models.google_llm.Gemini.connect'
) as mock_connect:
# Mock the async context manager
mock_connect.return_value.__aenter__.side_effect = mock_connect_impl
with pytest.raises(ConnectionClosed):
async for _ in flow.run_live(invocation_context):
pass
from google.adk.flows.llm_flows.base_llm_flow import DEFAULT_MAX_RECONNECT_ATTEMPTS
# 1 initial attempt + DEFAULT_MAX_RECONNECT_ATTEMPTS retries
assert mock_connect.call_count == DEFAULT_MAX_RECONNECT_ATTEMPTS + 1
@pytest.mark.asyncio
async def test_run_live_reconnect_reset_attempt():
"""Test that attempt counter is reset on successful communication."""
from google.adk.agents.live_request_queue import LiveRequestQueue
from google.adk.flows.llm_flows.base_llm_flow import DEFAULT_MAX_RECONNECT_ATTEMPTS
from websockets.exceptions import ConnectionClosed
real_model = Gemini()
connection_cnt = 0
async def mock_connect_impl(*args, **kwargs):
nonlocal connection_cnt
connection_cnt += 1
conn = mock.AsyncMock()
async def mock_receive():
if connection_cnt <= 2:
# Yield handle on the first two connections.
yield LlmResponse(
live_session_resumption_update=types.LiveServerSessionResumptionUpdate(
new_handle='test_handle'
),
turn_complete=True,
)
# All subsequent receives fail.
raise ConnectionClosed(None, None)
conn.receive = mock.Mock(side_effect=mock_receive)
return conn
agent = Agent(name='test_agent', model=real_model)
invocation_context = await testing_utils.create_invocation_context(
agent=agent
)
invocation_context.live_request_queue = LiveRequestQueue()
flow = BaseLlmFlowForTesting()
with mock.patch.object(
flow, '_send_to_model', new_callable=AsyncMock
) as mock_send:
with mock.patch(
'google.adk.models.google_llm.Gemini.connect'
) as mock_connect:
mock_connect.return_value.__aenter__.side_effect = mock_connect_impl
with pytest.raises(ConnectionClosed):
async for _ in flow.run_live(invocation_context):
pass
# We expect 2 successful attempts + DEFAULT_MAX_RECONNECT_ATTEMPTS failed attempts
# Total calls = 2 + 5 = 7
assert mock_connect.call_count == DEFAULT_MAX_RECONNECT_ATTEMPTS + 2
@pytest.mark.asyncio
async def test_run_live_no_reconnect_after_queue_close_api_error_1000():
"""Test that run_live does not reconnect after LiveRequestQueue.close() (APIError 1000).
Calling LiveRequestQueue.close() signals an intentional client-side shutdown.
When the resulting APIError(1000) arrives, run_live must terminate instead of
reconnecting — even when a session resumption handle is present.
"""
from google.adk.agents.live_request_queue import LiveRequestQueue
from google.genai.errors import APIError
real_model = Gemini()
mock_connection = mock.AsyncMock()
async def mock_receive():
# Simulate receiving a session resumption handle from the server.
yield LlmResponse(
live_session_resumption_update=types.LiveServerSessionResumptionUpdate(
new_handle='test_handle'
)
)
# Simulate the normal-close APIError that arrives after llm_connection.close().
raise APIError(1000, {})
mock_connection.receive = mock.Mock(side_effect=mock_receive)
agent = Agent(name='test_agent', model=real_model)
invocation_context = await testing_utils.create_invocation_context(
agent=agent
)
invocation_context.live_request_queue = LiveRequestQueue()
# Simulate what live_request_queue.close() does before the error arrives.
invocation_context.live_request_queue.close()
flow = BaseLlmFlowForTesting()
with mock.patch.object(flow, '_send_to_model', new_callable=AsyncMock):
with mock.patch(
'google.adk.models.google_llm.Gemini.connect'
) as mock_connect:
mock_connect.return_value.__aenter__.return_value = mock_connection
events = []
async for event in flow.run_live(invocation_context):
events.append(event)
# run_live must terminate after the first connection — no reconnect.
assert mock_connect.call_count == 1
@pytest.mark.asyncio
async def test_run_live_no_reconnect_after_queue_close_connection_closed():
"""Test that run_live does not reconnect after LiveRequestQueue.close() (ConnectionClosed).
Same as the APIError(1000) case but the connection surfaces as ConnectionClosed,
which can happen depending on the websockets library version or transport layer.
"""
from google.adk.agents.live_request_queue import LiveRequestQueue
from websockets.exceptions import ConnectionClosed
real_model = Gemini()
mock_connection = mock.AsyncMock()
async def mock_receive():
yield LlmResponse(
live_session_resumption_update=types.LiveServerSessionResumptionUpdate(
new_handle='test_handle'
)
)
raise ConnectionClosed(None, None)
mock_connection.receive = mock.Mock(side_effect=mock_receive)
agent = Agent(name='test_agent', model=real_model)
invocation_context = await testing_utils.create_invocation_context(
agent=agent
)
invocation_context.live_request_queue = LiveRequestQueue()
invocation_context.live_request_queue.close()
flow = BaseLlmFlowForTesting()
with mock.patch.object(flow, '_send_to_model', new_callable=AsyncMock):
with mock.patch(
'google.adk.models.google_llm.Gemini.connect'
) as mock_connect:
mock_connect.return_value.__aenter__.return_value = mock_connection
events = []
async for event in flow.run_live(invocation_context):
events.append(event)
# run_live must terminate after the first connection — no reconnect.
assert mock_connect.call_count == 1
@pytest.mark.asyncio
async def test_run_live_still_reconnects_on_unintentional_drop_with_handle():
"""Test that session-resumption reconnection still works for genuine drops.
A genuine network drop (ConnectionClosed without queue.close()) with a session
resumption handle must still trigger reconnection. The queue.close() fix
must not break this existing behaviour.