ADK changes

PiperOrigin-RevId: 814319961
This commit is contained in:
Xuan Yang
2025-10-02 13:44:05 -07:00
committed by Copybara-Service
parent 2e2d61b6fe
commit d3148dacc9
6 changed files with 622 additions and 6 deletions
@@ -26,6 +26,7 @@ from google.adk.agents.readonly_context import ReadonlyContext
from google.adk.models.llm_request import LlmRequest
from google.adk.models.registry import LLMRegistry
from google.adk.sessions.in_memory_session_service import InMemorySessionService
from google.adk.tools.google_search_tool import google_search
from google.genai import types
from pydantic import BaseModel
import pytest
@@ -279,3 +280,63 @@ def test_allow_transfer_by_default():
assert not agent.disallow_transfer_to_parent
assert not agent.disallow_transfer_to_peers
# TODO(b/448114567): Remove TestCanonicalTools once the workaround
# is no longer needed.
class TestCanonicalTools:
"""Unit tests for canonical_tools in LlmAgent."""
@staticmethod
def _my_tool(sides: int) -> int:
return sides
async def test_handle_google_search_with_other_tools(self):
"""Test that google_search is wrapped into an agent."""
agent = LlmAgent(
name='test_agent',
model='gemini-pro',
tools=[
self._my_tool,
google_search,
],
)
ctx = await _create_readonly_context(agent)
tools = await agent.canonical_tools(ctx)
assert len(tools) == 2
assert tools[0].name == '_my_tool'
assert tools[1].name == 'google_search_agent'
assert tools[1].__class__.__name__ == 'GoogleSearchAgentTool'
async def test_handle_google_search_only(self):
"""Test that google_search is not wrapped into an agent."""
agent = LlmAgent(
name='test_agent',
model='gemini-pro',
tools=[
google_search,
],
)
ctx = await _create_readonly_context(agent)
tools = await agent.canonical_tools(ctx)
assert len(tools) == 1
assert tools[0].name == 'google_search'
assert tools[0].__class__.__name__ == 'GoogleSearchTool'
async def test_no_google_search(self):
"""Test other tools are not affected."""
agent = LlmAgent(
name='test_agent',
model='gemini-pro',
tools=[
self._my_tool,
],
)
ctx = await _create_readonly_context(agent)
tools = await agent.canonical_tools(ctx)
assert len(tools) == 1
assert tools[0].name == '_my_tool'
assert tools[0].__class__.__name__ == 'FunctionTool'
@@ -14,13 +14,18 @@
"""Unit tests for BaseLlmFlow toolset integration."""
from typing import Optional
from unittest.mock import AsyncMock
from google.adk.agents.callback_context import CallbackContext
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.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 google_search
from google.genai import types
import pytest
@@ -148,3 +153,222 @@ async def test_preprocess_handles_mixed_tools_and_toolsets():
# 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'}
# 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()
@@ -0,0 +1,139 @@
# 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.
from google.adk.agents.invocation_context import InvocationContext
from google.adk.agents.llm_agent import Agent
from google.adk.models.llm_response import LlmResponse
from google.adk.sessions.in_memory_session_service import InMemorySessionService
from google.adk.tools.google_search_agent_tool import GoogleSearchAgentTool
from google.adk.tools.tool_context import ToolContext
from google.genai import types
from google.genai.types import Part
from pytest import mark
from .. import testing_utils
function_call_no_schema = Part.from_function_call(
name='tool_agent', args={'request': 'test1'}
)
grounding_metadata = types.GroundingMetadata(web_search_queries=['test query'])
# TODO(b/448114567): Remove test_grounding_metadata_ tests once the workaround
# is no longer needed.
@mark.asyncio
async def test_grounding_metadata_is_stored_in_state_during_invocation():
"""Verify grounding_metadata is stored in the state during invocation."""
# Mock model for the tool_agent that returns grounding_metadata
tool_agent_model = testing_utils.MockModel.create(
responses=[
LlmResponse(
content=types.Content(
parts=[Part.from_text(text='response from tool')]
),
grounding_metadata=grounding_metadata,
)
]
)
tool_agent = Agent(
name='tool_agent',
model=tool_agent_model,
)
agent_tool = GoogleSearchAgentTool(agent=tool_agent)
session_service = InMemorySessionService()
session = await session_service.create_session(
app_name='test_app', user_id='test_user'
)
invocation_context = InvocationContext(
invocation_id='invocation_id',
agent=tool_agent,
session=session,
session_service=session_service,
)
tool_context = ToolContext(invocation_context=invocation_context)
tool_result = await agent_tool.run_async(
args=function_call_no_schema.function_call.args, tool_context=tool_context
)
# Verify the tool result
assert tool_result == 'response from tool'
# Verify grounding_metadata is stored in the state
assert tool_context.state['temp:_adk_grounding_metadata'] == (
grounding_metadata
)
@mark.asyncio
async def test_grounding_metadata_is_not_stored_in_state_after_invocation():
"""Verify grounding_metadata is not stored in the state after invocation."""
# Mock model for the tool_agent that returns grounding_metadata
tool_agent_model = testing_utils.MockModel.create(
responses=[
LlmResponse(
content=types.Content(
parts=[Part.from_text(text='response from tool')]
),
grounding_metadata=grounding_metadata,
)
]
)
tool_agent = Agent(
name='tool_agent',
model=tool_agent_model,
)
# Mock model for the root_agent
root_agent_model = testing_utils.MockModel.create(
responses=[
function_call_no_schema, # Call the tool_agent
'Final response from root',
]
)
root_agent = Agent(
name='root_agent',
model=root_agent_model,
tools=[GoogleSearchAgentTool(agent=tool_agent)],
)
runner = testing_utils.InMemoryRunner(root_agent)
events = runner.run('test input')
# Find the function response event
function_response_event = None
for event in events:
if event.get_function_responses():
function_response_event = event
break
# Verify the function response
assert function_response_event is not None
function_responses = function_response_event.get_function_responses()
assert len(function_responses) == 1
tool_output = function_responses[0].response
assert tool_output == {'result': 'response from tool'}
# Verify grounding_metadata is not stored in the root_agent's state
assert 'temp:_adk_grounding_metadata' not in runner.session.state