chore: import upstream snapshot with attribution
Continuous Integration / Pre-commit Linter (push) Has been cancelled
Continuous Integration / Mypy Check (Python 3.10) (push) Has been cancelled
Continuous Integration / Mypy Check (Python 3.11) (push) Has been cancelled
Continuous Integration / Mypy Check (Python 3.12) (push) Has been cancelled
Continuous Integration / Mypy Check (Python 3.13) (push) Has been cancelled
Continuous Integration / Unit Tests (Python 3.10) (push) Has been cancelled
Continuous Integration / Unit Tests (Python 3.11) (push) Has been cancelled
Continuous Integration / Unit Tests (Python 3.12) (push) Has been cancelled
Continuous Integration / Unit Tests (Python 3.13) (push) Has been cancelled
Continuous Integration / Unit Tests (Python 3.14) (push) Has been cancelled
Continuous Integration / A2A v0.3 Tests (Python 3.10) (push) Has been cancelled
Continuous Integration / A2A v0.3 Tests (Python 3.11) (push) Has been cancelled
Continuous Integration / A2A v0.3 Tests (Python 3.12) (push) Has been cancelled
Copybara PR Handler / close-imported-pr (push) Has been cancelled
Continuous Integration / A2A v0.3 Tests (Python 3.13) (push) Has been cancelled
Continuous Integration / A2A v0.3 Tests (Python 3.14) (push) Has been cancelled

This commit is contained in:
wehub-resource-sync
2026-07-13 13:25:13 +08:00
commit ec2b666284
2231 changed files with 491535 additions and 0 deletions
+13
View File
@@ -0,0 +1,13 @@
# 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.
@@ -0,0 +1,837 @@
# 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 google.adk.agents import Agent
from google.adk.agents import LiveRequestQueue
from google.adk.agents.run_config import RunConfig
from google.adk.models import LlmResponse
from google.genai import types
import pytest
from .. import testing_utils
def test_streaming():
response1 = LlmResponse(
turn_complete=True,
)
mock_model = testing_utils.MockModel.create([response1])
root_agent = Agent(
name='root_agent',
model=mock_model,
tools=[],
)
runner = testing_utils.InMemoryRunner(
root_agent=root_agent, response_modalities=['AUDIO']
)
live_request_queue = LiveRequestQueue()
live_request_queue.send_realtime(
blob=types.Blob(data=b'\x00\xFF', mime_type='audio/pcm')
)
res_events = runner.run_live(live_request_queue)
assert res_events is not None, 'Expected a list of events, got None.'
assert (
len(res_events) > 0
), 'Expected at least one response, but got an empty list.'
assert len(mock_model.requests) == 1
# Get the request that was captured
llm_request_sent_to_mock = mock_model.requests[0]
# Assert that the request contained the correct configuration
assert llm_request_sent_to_mock.live_connect_config is not None
assert (
llm_request_sent_to_mock.live_connect_config.output_audio_transcription
is not None
)
def test_streaming_with_output_audio_transcription():
"""Test streaming with output audio transcription configuration."""
response1 = LlmResponse(
turn_complete=True,
)
mock_model = testing_utils.MockModel.create([response1])
root_agent = Agent(
name='root_agent',
model=mock_model,
tools=[],
)
runner = testing_utils.InMemoryRunner(
root_agent=root_agent, response_modalities=['AUDIO']
)
# Create run config with output audio transcription
run_config = RunConfig(
output_audio_transcription=types.AudioTranscriptionConfig()
)
live_request_queue = LiveRequestQueue()
live_request_queue.send_realtime(
blob=types.Blob(data=b'\x00\xFF', mime_type='audio/pcm')
)
res_events = runner.run_live(live_request_queue, run_config)
assert res_events is not None, 'Expected a list of events, got None.'
assert (
len(res_events) > 0
), 'Expected at least one response, but got an empty list.'
assert len(mock_model.requests) == 1
# Get the request that was captured
llm_request_sent_to_mock = mock_model.requests[0]
# Assert that the request contained the correct configuration
assert llm_request_sent_to_mock.live_connect_config is not None
assert (
llm_request_sent_to_mock.live_connect_config.output_audio_transcription
is not None
)
def test_streaming_with_input_audio_transcription():
"""Test streaming with input audio transcription configuration."""
response1 = LlmResponse(
turn_complete=True,
)
mock_model = testing_utils.MockModel.create([response1])
root_agent = Agent(
name='root_agent',
model=mock_model,
tools=[],
)
runner = testing_utils.InMemoryRunner(
root_agent=root_agent, response_modalities=['AUDIO']
)
# Create run config with input audio transcription
run_config = RunConfig(
input_audio_transcription=types.AudioTranscriptionConfig()
)
live_request_queue = LiveRequestQueue()
live_request_queue.send_realtime(
blob=types.Blob(data=b'\x00\xFF', mime_type='audio/pcm')
)
res_events = runner.run_live(live_request_queue, run_config)
assert res_events is not None, 'Expected a list of events, got None.'
assert (
len(res_events) > 0
), 'Expected at least one response, but got an empty list.'
assert len(mock_model.requests) == 1
# Get the request that was captured
llm_request_sent_to_mock = mock_model.requests[0]
# Assert that the request contained the correct configuration
assert llm_request_sent_to_mock.live_connect_config is not None
assert (
llm_request_sent_to_mock.live_connect_config.input_audio_transcription
is not None
)
def test_streaming_with_realtime_input_config():
"""Test streaming with realtime input configuration."""
response1 = LlmResponse(
turn_complete=True,
)
mock_model = testing_utils.MockModel.create([response1])
root_agent = Agent(
name='root_agent',
model=mock_model,
tools=[],
)
runner = testing_utils.InMemoryRunner(
root_agent=root_agent, response_modalities=['AUDIO']
)
# Create run config with realtime input config
run_config = RunConfig(
realtime_input_config=types.RealtimeInputConfig(
automatic_activity_detection=types.AutomaticActivityDetection(
disabled=True
)
)
)
live_request_queue = LiveRequestQueue()
live_request_queue.send_realtime(
blob=types.Blob(data=b'\x00\xFF', mime_type='audio/pcm')
)
res_events = runner.run_live(live_request_queue, run_config)
assert res_events is not None, 'Expected a list of events, got None.'
assert (
len(res_events) > 0
), 'Expected at least one response, but got an empty list.'
assert len(mock_model.requests) == 1
# Get the request that was captured
llm_request_sent_to_mock = mock_model.requests[0]
# Assert that the request contained the correct configuration
assert llm_request_sent_to_mock.live_connect_config is not None
assert (
llm_request_sent_to_mock.live_connect_config.realtime_input_config.automatic_activity_detection.disabled
is True
)
def test_streaming_with_realtime_input_config_vad_enabled():
"""Test streaming with realtime input configuration with VAD enabled."""
response1 = LlmResponse(
turn_complete=True,
)
mock_model = testing_utils.MockModel.create([response1])
root_agent = Agent(
name='root_agent',
model=mock_model,
tools=[],
)
runner = testing_utils.InMemoryRunner(
root_agent=root_agent, response_modalities=['AUDIO']
)
# Create run config with realtime input config with VAD enabled
run_config = RunConfig(
realtime_input_config=types.RealtimeInputConfig(
automatic_activity_detection=types.AutomaticActivityDetection(
disabled=False
)
)
)
live_request_queue = LiveRequestQueue()
live_request_queue.send_realtime(
blob=types.Blob(data=b'\x00\xFF', mime_type='audio/pcm')
)
res_events = runner.run_live(live_request_queue, run_config)
assert res_events is not None, 'Expected a list of events, got None.'
assert (
len(res_events) > 0
), 'Expected at least one response, but got an empty list.'
assert len(mock_model.requests) == 1
# Get the request that was captured
llm_request_sent_to_mock = mock_model.requests[0]
# Assert that the request contained the correct configuration
assert llm_request_sent_to_mock.live_connect_config is not None
assert (
llm_request_sent_to_mock.live_connect_config.realtime_input_config.automatic_activity_detection.disabled
is False
)
def test_streaming_with_enable_affective_dialog_true():
"""Test streaming with affective dialog enabled."""
response1 = LlmResponse(
turn_complete=True,
)
mock_model = testing_utils.MockModel.create([response1])
root_agent = Agent(
name='root_agent',
model=mock_model,
tools=[],
)
runner = testing_utils.InMemoryRunner(
root_agent=root_agent, response_modalities=['AUDIO']
)
# Create run config with affective dialog enabled
run_config = RunConfig(enable_affective_dialog=True)
live_request_queue = LiveRequestQueue()
live_request_queue.send_realtime(
blob=types.Blob(data=b'\x00\xFF', mime_type='audio/pcm')
)
res_events = runner.run_live(live_request_queue, run_config)
assert res_events is not None, 'Expected a list of events, got None.'
assert (
len(res_events) > 0
), 'Expected at least one response, but got an empty list.'
assert len(mock_model.requests) == 1
# Get the request that was captured
llm_request_sent_to_mock = mock_model.requests[0]
# Assert that the request contained the correct configuration
assert llm_request_sent_to_mock.live_connect_config is not None
assert (
llm_request_sent_to_mock.live_connect_config.enable_affective_dialog
is True
)
def test_streaming_with_enable_affective_dialog_false():
"""Test streaming with affective dialog disabled."""
response1 = LlmResponse(
turn_complete=True,
)
mock_model = testing_utils.MockModel.create([response1])
root_agent = Agent(
name='root_agent',
model=mock_model,
tools=[],
)
runner = testing_utils.InMemoryRunner(
root_agent=root_agent, response_modalities=['AUDIO']
)
# Create run config with affective dialog disabled
run_config = RunConfig(enable_affective_dialog=False)
live_request_queue = LiveRequestQueue()
live_request_queue.send_realtime(
blob=types.Blob(data=b'\x00\xFF', mime_type='audio/pcm')
)
res_events = runner.run_live(live_request_queue, run_config)
assert res_events is not None, 'Expected a list of events, got None.'
assert (
len(res_events) > 0
), 'Expected at least one response, but got an empty list.'
assert len(mock_model.requests) == 1
# Get the request that was captured
llm_request_sent_to_mock = mock_model.requests[0]
# Assert that the request contained the correct configuration
assert llm_request_sent_to_mock.live_connect_config is not None
assert (
llm_request_sent_to_mock.live_connect_config.enable_affective_dialog
is False
)
def test_streaming_with_proactivity_config():
"""Test streaming with proactivity configuration."""
response1 = LlmResponse(
turn_complete=True,
)
mock_model = testing_utils.MockModel.create([response1])
root_agent = Agent(
name='root_agent',
model=mock_model,
tools=[],
)
runner = testing_utils.InMemoryRunner(
root_agent=root_agent, response_modalities=['AUDIO']
)
# Create run config with proactivity config
run_config = RunConfig(proactivity=types.ProactivityConfig())
live_request_queue = LiveRequestQueue()
live_request_queue.send_realtime(
blob=types.Blob(data=b'\x00\xFF', mime_type='audio/pcm')
)
res_events = runner.run_live(live_request_queue, run_config)
assert res_events is not None, 'Expected a list of events, got None.'
assert (
len(res_events) > 0
), 'Expected at least one response, but got an empty list.'
assert len(mock_model.requests) == 1
# Get the request that was captured
llm_request_sent_to_mock = mock_model.requests[0]
# Assert that the request contained the correct configuration
assert llm_request_sent_to_mock.live_connect_config is not None
assert llm_request_sent_to_mock.live_connect_config.proactivity is not None
def test_streaming_with_combined_audio_transcription_configs():
"""Test streaming with both input and output audio transcription configurations."""
response1 = LlmResponse(
turn_complete=True,
)
mock_model = testing_utils.MockModel.create([response1])
root_agent = Agent(
name='root_agent',
model=mock_model,
tools=[],
)
runner = testing_utils.InMemoryRunner(
root_agent=root_agent, response_modalities=['AUDIO']
)
# Create run config with both input and output audio transcription
run_config = RunConfig(
input_audio_transcription=types.AudioTranscriptionConfig(),
output_audio_transcription=types.AudioTranscriptionConfig(),
)
live_request_queue = LiveRequestQueue()
live_request_queue.send_realtime(
blob=types.Blob(data=b'\x00\xFF', mime_type='audio/pcm')
)
res_events = runner.run_live(live_request_queue, run_config)
assert res_events is not None, 'Expected a list of events, got None.'
assert (
len(res_events) > 0
), 'Expected at least one response, but got an empty list.'
assert len(mock_model.requests) == 1
# Get the request that was captured
llm_request_sent_to_mock = mock_model.requests[0]
# Assert that the request contained the correct configuration
assert llm_request_sent_to_mock.live_connect_config is not None
assert (
llm_request_sent_to_mock.live_connect_config.input_audio_transcription
is not None
)
assert (
llm_request_sent_to_mock.live_connect_config.output_audio_transcription
is not None
)
def test_streaming_with_all_configs_combined():
"""Test streaming with all the new configurations combined."""
response1 = LlmResponse(
turn_complete=True,
)
mock_model = testing_utils.MockModel.create([response1])
root_agent = Agent(
name='root_agent',
model=mock_model,
tools=[],
)
runner = testing_utils.InMemoryRunner(
root_agent=root_agent, response_modalities=['AUDIO']
)
# Create run config with all configurations
run_config = RunConfig(
output_audio_transcription=types.AudioTranscriptionConfig(),
input_audio_transcription=types.AudioTranscriptionConfig(),
realtime_input_config=types.RealtimeInputConfig(
automatic_activity_detection=types.AutomaticActivityDetection(
disabled=True
)
),
enable_affective_dialog=True,
proactivity=types.ProactivityConfig(),
)
live_request_queue = LiveRequestQueue()
live_request_queue.send_realtime(
blob=types.Blob(data=b'\x00\xFF', mime_type='audio/pcm')
)
res_events = runner.run_live(live_request_queue, run_config)
assert res_events is not None, 'Expected a list of events, got None.'
assert (
len(res_events) > 0
), 'Expected at least one response, but got an empty list.'
assert len(mock_model.requests) == 1
# Get the request that was captured
llm_request_sent_to_mock = mock_model.requests[0]
# Assert that the request contained the correct configuration
assert llm_request_sent_to_mock.live_connect_config is not None
assert (
llm_request_sent_to_mock.live_connect_config.realtime_input_config
is not None
)
assert llm_request_sent_to_mock.live_connect_config.proactivity is not None
assert (
llm_request_sent_to_mock.live_connect_config.enable_affective_dialog
is True
)
def test_streaming_with_multiple_audio_configs():
"""Test streaming with multiple audio transcription configurations."""
response1 = LlmResponse(
turn_complete=True,
)
mock_model = testing_utils.MockModel.create([response1])
root_agent = Agent(
name='root_agent',
model=mock_model,
tools=[],
)
runner = testing_utils.InMemoryRunner(
root_agent=root_agent, response_modalities=['AUDIO']
)
# Create run config with multiple audio transcription configs
run_config = RunConfig(
input_audio_transcription=types.AudioTranscriptionConfig(),
output_audio_transcription=types.AudioTranscriptionConfig(),
enable_affective_dialog=True,
)
live_request_queue = LiveRequestQueue()
live_request_queue.send_realtime(
blob=types.Blob(data=b'\x00\xFF', mime_type='audio/pcm')
)
res_events = runner.run_live(live_request_queue, run_config)
assert res_events is not None, 'Expected a list of events, got None.'
assert (
len(res_events) > 0
), 'Expected at least one response, but got an empty list.'
assert len(mock_model.requests) == 1
# Get the request that was captured
llm_request_sent_to_mock = mock_model.requests[0]
# Assert that the request contained the correct configuration
assert llm_request_sent_to_mock.live_connect_config is not None
assert (
llm_request_sent_to_mock.live_connect_config.input_audio_transcription
is not None
)
assert (
llm_request_sent_to_mock.live_connect_config.output_audio_transcription
is not None
)
assert (
llm_request_sent_to_mock.live_connect_config.enable_affective_dialog
is True
)
def test_streaming_with_session_resumption_config():
"""Test streaming with multiple audio transcription configurations."""
response1 = LlmResponse(
turn_complete=True,
)
mock_model = testing_utils.MockModel.create([response1])
root_agent = Agent(
name='root_agent',
model=mock_model,
tools=[],
)
runner = testing_utils.InMemoryRunner(
root_agent=root_agent, response_modalities=['AUDIO']
)
# Create run config with multiple audio transcription configs
run_config = RunConfig(
session_resumption=types.SessionResumptionConfig(transparent=True),
)
live_request_queue = LiveRequestQueue()
live_request_queue.send_realtime(
blob=types.Blob(data=b'\x00\xFF', mime_type='audio/pcm')
)
res_events = runner.run_live(live_request_queue, run_config)
assert res_events is not None, 'Expected a list of events, got None.'
assert (
len(res_events) > 0
), 'Expected at least one response, but got an empty list.'
assert len(mock_model.requests) == 1
# Get the request that was captured
llm_request_sent_to_mock = mock_model.requests[0]
# Assert that the request contained the correct configuration
assert llm_request_sent_to_mock.live_connect_config is not None
assert (
llm_request_sent_to_mock.live_connect_config.session_resumption
is not None
)
assert (
llm_request_sent_to_mock.live_connect_config.session_resumption.transparent
is True
)
def test_streaming_with_context_window_compression_config():
"""Test streaming with context window compression config."""
response = LlmResponse(turn_complete=True)
mock_model = testing_utils.MockModel.create([response])
root_agent = Agent(
name='root_agent',
model=mock_model,
tools=[],
)
runner = testing_utils.InMemoryRunner(
root_agent=root_agent, response_modalities=['AUDIO']
)
# Create run config with context window compression
run_config = RunConfig(
context_window_compression=types.ContextWindowCompressionConfig(
trigger_tokens=1000,
sliding_window=types.SlidingWindow(target_tokens=500),
)
)
live_request_queue = LiveRequestQueue()
live_request_queue.send_realtime(
blob=types.Blob(data=b'\x00\xFF', mime_type='audio/pcm')
)
res_events = runner.run_live(live_request_queue, run_config)
assert res_events is not None, 'Expected a list of events, got None.'
assert (
len(res_events) > 0
), 'Expected at least one response, but got an empty list.'
assert len(mock_model.requests) == 1
# Get the request that was captured
llm_request_sent_to_mock = mock_model.requests[0]
# Assert that the request contained the correct configuration
assert llm_request_sent_to_mock.live_connect_config is not None
assert (
llm_request_sent_to_mock.live_connect_config.context_window_compression
is not None
)
assert (
llm_request_sent_to_mock.live_connect_config.context_window_compression.trigger_tokens
== 1000
)
assert (
llm_request_sent_to_mock.live_connect_config.context_window_compression.sliding_window.target_tokens
== 500
)
def test_streaming_with_avatar_config():
"""Test avatar_config propagation and video content through run_live.
Verifies:
1. avatar_config from RunConfig is propagated to live_connect_config.
2. Video inline_data from the model flows through events correctly.
"""
# Mock model returns video content followed by turn_complete.
video_response = LlmResponse(
content=types.Content(
role='model',
parts=[
types.Part(
inline_data=types.Blob(
data=b'video_data', mime_type='video/mp4'
)
)
],
),
)
turn_complete_response = LlmResponse(
turn_complete=True,
)
mock_model = testing_utils.MockModel.create(
[video_response, turn_complete_response]
)
root_agent = Agent(
name='root_agent',
model=mock_model,
tools=[],
)
runner = testing_utils.InMemoryRunner(
root_agent=root_agent, response_modalities=['VIDEO']
)
run_config = RunConfig(
response_modalities=['VIDEO'],
avatar_config=types.AvatarConfig(avatar_name='Kai'),
)
live_request_queue = LiveRequestQueue()
live_request_queue.send_realtime(
blob=types.Blob(data=b'\x00\xFF', mime_type='audio/pcm')
)
res_events = runner.run_live(live_request_queue, run_config)
assert res_events is not None, 'Expected a list of events, got None.'
assert (
len(res_events) > 0
), 'Expected at least one response, but got an empty list.'
assert len(mock_model.requests) == 1
# 1. Verify avatar_config was propagated to the live_connect_config.
llm_request_sent_to_mock = mock_model.requests[0]
assert llm_request_sent_to_mock.live_connect_config is not None
assert llm_request_sent_to_mock.live_connect_config.avatar_config is not None
assert (
llm_request_sent_to_mock.live_connect_config.avatar_config.avatar_name
== 'Kai'
)
# 2. Verify video content flows through events.
video_events = [
e
for e in res_events
if e.content
and e.content.parts
and any(
p.inline_data
and p.inline_data.mime_type
and p.inline_data.mime_type.startswith('video/')
for p in e.content.parts
)
]
assert video_events, 'Expected at least one event with video inline_data.'
video_event = video_events[0]
assert video_event.content.role == 'model'
video_part = video_event.content.parts[0]
assert video_part.inline_data is not None
assert video_part.inline_data.data == b'video_data'
assert video_part.inline_data.mime_type == 'video/mp4'
def test_streaming_default_model_when_not_specified(mocker):
"""Test streaming uses default model when not specified in live mode."""
from google.adk.agents import LlmAgent
from google.adk.models.registry import LLMRegistry
response1 = LlmResponse(turn_complete=True)
mock_model = testing_utils.MockModel.create([response1])
mock_new_llm = mocker.patch.object(
LLMRegistry, 'new_llm', return_value=mock_model
)
# Save original default
original_default = LlmAgent._default_live_model
try:
LlmAgent.set_default_live_model('my-custom-live-model')
root_agent = Agent(
name='root_agent',
tools=[],
)
import asyncio
from contextlib import aclosing
from google.adk.agents.run_config import RunConfig
from google.adk.artifacts.in_memory_artifact_service import InMemoryArtifactService
from google.adk.memory.in_memory_memory_service import InMemoryMemoryService
from google.adk.runners import Runner
from google.adk.sessions.in_memory_session_service import InMemorySessionService
runner = Runner(
app_name='test_app',
agent=root_agent,
artifact_service=InMemoryArtifactService(),
session_service=InMemorySessionService(),
memory_service=InMemoryMemoryService(),
)
live_request_queue = LiveRequestQueue()
live_request_queue.send_realtime(
blob=types.Blob(data=b'\x00\xFF', mime_type='audio/pcm')
)
async def run_test():
session = await runner.session_service.create_session(
app_name='test_app', user_id='test_user'
)
run_config = RunConfig(response_modalities=['AUDIO'])
async with aclosing(
runner.run_live(
user_id=session.user_id,
session_id=session.id,
live_request_queue=live_request_queue,
run_config=run_config,
)
) as agen:
async for event in agen:
# We just need to trigger the resolution
break
asyncio.run(run_test())
mock_new_llm.assert_any_call('my-custom-live-model')
finally:
# Restore original default
LlmAgent.set_default_live_model(original_default)
def test_streaming_with_explicit_vad_signal():
"""Test streaming configuration with explicit_vad_signal enabled."""
response1 = LlmResponse(
turn_complete=True,
)
mock_model = testing_utils.MockModel.create([response1])
root_agent = Agent(
name='root_agent',
model=mock_model,
tools=[],
)
runner = testing_utils.InMemoryRunner(
root_agent=root_agent, response_modalities=['AUDIO']
)
live_request_queue = LiveRequestQueue()
live_request_queue.send_realtime(
blob=types.Blob(data=b'\x00\xFF', mime_type='audio/pcm')
)
res_events = runner.run_live(
live_request_queue, run_config=RunConfig(explicit_vad_signal=True)
)
assert res_events is not None
assert len(mock_model.requests) == 1
llm_request_sent_to_mock = mock_model.requests[0]
assert llm_request_sent_to_mock.live_connect_config is not None
assert (
llm_request_sent_to_mock.live_connect_config.explicit_vad_signal is True
)
@@ -0,0 +1,197 @@
# 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.
import asyncio
import contextlib
from typing import AsyncGenerator
from google.adk.agents.live_request_queue import LiveRequestQueue
from google.adk.agents.llm_agent import Agent
from google.adk.models.llm_response import LlmResponse
from google.genai import types
import pytest
from typing_extensions import override # <-- FIX: Add this import
from websockets import frames # <-- FIX 1: Import the frames module
from websockets.exceptions import ConnectionClosed
from .. import testing_utils
def test_live_streaming_multi_agent_single_tool():
"""Test live streaming with multi-agent delegation for a single tool call."""
# --- 1. Mock LLM Responses ---
# Mock response for the root_agent to delegate the task to the roll_agent.
# FIX: Use from_function_call to represent delegation to a sub-agent.
delegation_to_roll_agent = types.Part.from_function_call(
name='transfer_to_agent', args={'agent_name': 'roll_agent'}
)
root_response1 = LlmResponse(
content=types.Content(role='model', parts=[delegation_to_roll_agent]),
turn_complete=False,
)
root_response2 = LlmResponse(turn_complete=True)
mock_root_model = testing_utils.MockModel.create(
[root_response1, root_response2]
)
# Mock response for the roll_agent to call its `roll_die` tool.
function_call = types.Part.from_function_call(
name='roll_die', args={'sides': 20}
)
roll_agent_response1 = LlmResponse(
content=types.Content(role='model', parts=[function_call]),
turn_complete=False,
)
roll_agent_response2 = LlmResponse(turn_complete=True)
mock_roll_model = testing_utils.MockModel.create(
[roll_agent_response1, roll_agent_response2]
)
# --- 2. Mock Tools and Agents ---
def roll_die(sides: int) -> int:
"""Rolls a die and returns a fixed result for testing."""
return 15
mock_roll_sub_agent = Agent(
name='roll_agent',
model=mock_roll_model,
tools=[roll_die],
)
main_agent = Agent(
name='root_agent',
model=mock_root_model,
sub_agents=[mock_roll_sub_agent],
)
# --- 3. Test Runner Setup ---
class CustomTestRunner(testing_utils.InMemoryRunner):
def run_live(
self,
live_request_queue: LiveRequestQueue,
run_config: testing_utils.RunConfig = None,
) -> list[testing_utils.Event]:
collected_responses = []
async def consume_responses(session: testing_utils.Session):
run_res = self.runner.run_live(
session=session,
live_request_queue=live_request_queue,
run_config=run_config or testing_utils.RunConfig(),
)
from contextlib import aclosing
async with aclosing(run_res) as agen:
async for response in agen:
collected_responses.append(response)
if len(collected_responses) >= 5:
return
try:
session = self.session
asyncio.run(asyncio.wait_for(consume_responses(session), timeout=5.0))
except (asyncio.TimeoutError, asyncio.CancelledError):
pass
return collected_responses
runner = CustomTestRunner(root_agent=main_agent)
live_request_queue = LiveRequestQueue()
live_request_queue.send_realtime(
blob=types.Blob(data=b'Roll a 20-sided die', mime_type='audio/pcm')
)
# --- 4. Run and Assert ---
res_events = runner.run_live(live_request_queue)
assert res_events is not None, 'Expected a list of events, but got None.'
assert len(res_events) >= 1, 'Expected at least one event.'
delegation_found = False
tool_call_found = False
tool_response_found = False
for event in res_events:
if event.content and event.content.parts:
for part in event.content.parts:
if part.function_call:
# FIX: Check for the function call that represents delegation.
if part.function_call.name == 'transfer_to_agent':
delegation_found = True
assert part.function_call.args == {'agent_name': 'roll_agent'}
# Check for the function call made by the roll_agent.
if part.function_call.name == 'roll_die':
tool_call_found = True
assert part.function_call.args['sides'] == 20
# Check for the result from the executed function.
if part.function_response and part.function_response.name == 'roll_die':
tool_response_found = True
assert part.function_response.response['result'] == 15
assert delegation_found, 'A function_call event for delegation was not found.'
assert tool_call_found, 'A function_call event for roll_die was not found.'
assert tool_response_found, 'A function_response for roll_die was not found.'
def test_live_streaming_connection_error_on_connect():
"""
Tests that the runner correctly handles a ConnectionClosed exception
raised from the model's `connect` method during a live run.
"""
# 1. Create a mock model that fails during the connection phase.
class MockModelThatFailsToConnect(testing_utils.MockModel):
@contextlib.asynccontextmanager
@override
async def connect(self, llm_request: testing_utils.LlmRequest):
"""Override connect to simulate an immediate connection failure."""
# FIX 2: Create a proper `Close` frame object first.
close_frame = frames.Close(
1007,
'gemini-live-2.5-flash-preview is not supported in the live api.',
)
# FIX 3: Pass the frame object to the `rcvd` parameter of the exception.
raise ConnectionClosed(rcvd=close_frame, sent=None)
yield # pragma: no cover
# 2. Instantiate the custom mock model.
mock_model = MockModelThatFailsToConnect(responses=[])
# 3. Set up the agent and runner.
agent = Agent(name='test_agent_for_connection_failure', model=mock_model)
runner = testing_utils.InMemoryRunner(root_agent=agent)
live_request_queue = LiveRequestQueue()
live_request_queue.send_realtime(
blob=types.Blob(data=b'Initial audio chunk', mime_type='audio/pcm')
)
# 4. Assert that `run_live` raises `ConnectionClosed`.
with pytest.raises(ConnectionClosed) as excinfo:
runner.run_live(live_request_queue)
# 5. Verify the details of the exception. The `code` and `reason` are
# attributes of the received frame (`rcvd`), not the exception itself.
assert excinfo.value.rcvd.code == 1007
assert (
'is not supported in the live api' in excinfo.value.rcvd.reason
), 'The exception reason should match the simulated server error.'
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,241 @@
# # 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.
# import asyncio
# import time
# from google.adk.agents import Agent
# from google.adk.agents import LiveRequestQueue
# from google.adk.agents.invocation_context import RealtimeCacheEntry
# from google.adk.agents.run_config import RunConfig
# from google.adk.events.event import Event
# from google.adk.models import LlmResponse
# from google.genai import types
# import pytest
# from .. import testing_utils
# def test_audio_caching_direct():
# """Test audio caching logic directly without full live streaming."""
# # This test directly verifies that our audio caching logic works
# audio_data = b'\x00\xFF\x01\x02\x03\x04\x05\x06'
# audio_mime_type = 'audio/pcm'
# # Create mock responses for successful completion
# responses = [
# LlmResponse(
# content=types.Content(
# role='model',
# parts=[types.Part.from_text(text='Processing audio...')],
# ),
# turn_complete=False,
# ),
# LlmResponse(turn_complete=True), # This should trigger flush
# ]
# mock_model = testing_utils.MockModel.create(responses)
# mock_model.model = 'gemini-2.5-flash' # For CFC support
# root_agent = Agent(
# name='test_agent',
# model=mock_model,
# tools=[],
# )
# # Test our implementation by directly calling it
# async def test_caching():
# # Create context similar to what would be created in real scenario
# invocation_context = await testing_utils.create_invocation_context(
# root_agent, run_config=RunConfig(support_cfc=True)
# )
# # Import our caching classes
# from google.adk.agents.invocation_context import RealtimeCacheEntry
# from google.adk.agents.llm.base_llm_flow import BaseLlmFlow
# # Create a mock flow to test our methods
# flow = BaseLlmFlow()
# # Test adding audio to cache
# invocation_context.input_realtime_cache = []
# audio_entry = RealtimeCacheEntry(
# role='user',
# data=types.Blob(data=audio_data, mime_type=audio_mime_type),
# timestamp=1234567890.0,
# )
# invocation_context.input_realtime_cache.append(audio_entry)
# # Verify cache has data
# assert len(invocation_context.input_realtime_cache) == 1
# assert invocation_context.input_realtime_cache[0].data.data == audio_data
# # Test flushing cache
# await flow._handle_control_event_flush(invocation_context, responses[-1])
# # Verify cache was cleared
# assert len(invocation_context.input_realtime_cache) == 0
# # Check if artifacts were created
# artifact_keys = (
# await invocation_context.artifact_service.list_artifact_keys(
# app_name=invocation_context.app_name,
# user_id=invocation_context.user_id,
# session_id=invocation_context.session.id,
# )
# )
# # Should have at least one audio artifact
# audio_artifacts = [key for key in artifact_keys if 'audio' in key.lower()]
# assert (
# len(audio_artifacts) > 0
# ), f'Expected audio artifacts, found: {artifact_keys}'
# # Verify artifact content
# if audio_artifacts:
# artifact = await invocation_context.artifact_service.load_artifact(
# app_name=invocation_context.app_name,
# user_id=invocation_context.user_id,
# session_id=invocation_context.session.id,
# filename=audio_artifacts[0],
# )
# assert artifact.inline_data.data == audio_data
# return True
# # Run the async test
# result = asyncio.run(test_caching())
# assert result is True
# def test_transcription_handling():
# """Test that transcriptions are properly handled and saved to session service."""
# # Create mock responses with transcriptions
# input_transcription = types.Transcription(
# text='Hello, this is transcribed input', finished=True
# )
# output_transcription = types.Transcription(
# text='This is transcribed output', finished=True
# )
# responses = [
# LlmResponse(
# content=types.Content(
# role='model', parts=[types.Part.from_text(text='Processing...')]
# ),
# turn_complete=False,
# ),
# LlmResponse(input_transcription=input_transcription, turn_complete=False),
# LlmResponse(
# output_transcription=output_transcription, turn_complete=False
# ),
# LlmResponse(turn_complete=True),
# ]
# mock_model = testing_utils.MockModel.create(responses)
# mock_model.model = 'gemini-2.5-flash'
# root_agent = Agent(
# name='test_agent',
# model=mock_model,
# tools=[],
# )
# async def test_transcription():
# # Create context
# invocation_context = await testing_utils.create_invocation_context(
# root_agent, run_config=RunConfig(support_cfc=True)
# )
# from google.adk.events.event import Event
# from google.adk.agents.llm.base_llm_flow import BaseLlmFlow
# flow = BaseLlmFlow()
# # Test processing transcription events
# session_events_before = len(invocation_context.session.events)
# # Simulate input transcription event
# input_event = Event(
# id=Event.new_id(),
# invocation_id=invocation_context.invocation_id,
# author='user',
# input_transcription=input_transcription,
# )
# # Simulate output transcription event
# output_event = Event(
# id=Event.new_id(),
# invocation_id=invocation_context.invocation_id,
# author=invocation_context.agent.name,
# output_transcription=output_transcription,
# )
# # Save transcription events to session
# await invocation_context.session_service.append_event(
# invocation_context.session, input_event
# )
# await invocation_context.session_service.append_event(
# invocation_context.session, output_event
# )
# # Verify transcriptions were saved to session
# session_events_after = len(invocation_context.session.events)
# assert session_events_after == session_events_before + 2
# # Check that transcription events were saved
# transcription_events = [
# event
# for event in invocation_context.session.events
# if hasattr(event, 'input_transcription')
# and event.input_transcription
# or hasattr(event, 'output_transcription')
# and event.output_transcription
# ]
# assert len(transcription_events) >= 2
# # Verify input transcription
# input_transcription_events = [
# event
# for event in invocation_context.session.events
# if hasattr(event, 'input_transcription') and event.input_transcription
# ]
# assert len(input_transcription_events) >= 1
# assert (
# input_transcription_events[0].input_transcription.text
# == 'Hello, this is transcribed input'
# )
# assert input_transcription_events[0].author == 'user'
# # Verify output transcription
# output_transcription_events = [
# event
# for event in invocation_context.session.events
# if hasattr(event, 'output_transcription') and event.output_transcription
# ]
# assert len(output_transcription_events) >= 1
# assert (
# output_transcription_events[0].output_transcription.text
# == 'This is transcribed output'
# )
# assert (
# output_transcription_events[0].author == invocation_context.agent.name
# )
# return True
# # Run the async test
# result = asyncio.run(test_transcription())
# assert result is True