diff --git a/src/google/adk/flows/llm_flows/core/_finalizer.py b/src/google/adk/flows/llm_flows/core/_finalizer.py index b41b0061520..431aeb39771 100644 --- a/src/google/adk/flows/llm_flows/core/_finalizer.py +++ b/src/google/adk/flows/llm_flows/core/_finalizer.py @@ -20,12 +20,15 @@ from collections.abc import Mapping from collections.abc import Sequence import contextlib +import logging from typing import Any from typing import AsyncGenerator from typing import Iterator from typing import TYPE_CHECKING +from google.genai import types from opentelemetry import trace +from pydantic import ValidationError from ....agents._callback_metadata import _callback_scope from ....agents._callback_metadata import CallbackType @@ -48,10 +51,10 @@ from ._utils import as_llm_agent as _as_llm_agent if TYPE_CHECKING: - from google.genai import types - from ....tools.base_tool import BaseTool +logger = logging.getLogger('google_adk.' + __name__) + def _collect_tool_display_names( function_calls: Sequence[types.FunctionCall], @@ -324,6 +327,13 @@ async def _maybe_add_grounding_metadata( ) if not ground_metadata: return response + # Parallel tool calls merge their state deltas through model_dump, so the + # stored GroundingMetadata can arrive here as a dict. + try: + ground_metadata = types.GroundingMetadata.model_validate(ground_metadata) + except ValidationError as e: + logger.warning('Ignoring invalid temp:_adk_grounding_metadata: %s', e) + return response if not response: response = llm_response diff --git a/tests/unittests/flows/llm_flows/core/test_finalizer.py b/tests/unittests/flows/llm_flows/core/test_finalizer.py index db8b34b75b2..ef4a19c52b5 100644 --- a/tests/unittests/flows/llm_flows/core/test_finalizer.py +++ b/tests/unittests/flows/llm_flows/core/test_finalizer.py @@ -39,6 +39,7 @@ from .... import testing_utils google_search = GoogleSearchTool(bypass_multi_tools_limit=True) +grounding_metadata = types.GroundingMetadata(web_search_queries=["test query"]) def dummy_tool(): @@ -321,8 +322,8 @@ def __init__(self): "tools, state_metadata, expect_metadata", [ ([], None, False), - ([google_search, dummy_tool], {"foo": "bar"}, True), - ([dummy_tool], {"foo": "bar"}, False), + ([google_search, dummy_tool], grounding_metadata, True), + ([dummy_tool], grounding_metadata, False), ([google_search, dummy_tool], None, False), ], ids=[ @@ -370,8 +371,8 @@ async def test_handle_after_model_callback_grounding_with_no_callbacks( "tools, state_metadata, expect_metadata", [ ([], None, False), - ([google_search, dummy_tool], {"foo": "bar"}, True), - ([dummy_tool], {"foo": "bar"}, False), + ([google_search, dummy_tool], grounding_metadata, True), + ([dummy_tool], grounding_metadata, False), ([google_search, dummy_tool], None, False), ], ids=[ @@ -429,8 +430,8 @@ async def test_handle_after_model_callback_grounding_with_callback_override( "tools, state_metadata, expect_metadata", [ ([], None, False), - ([google_search, dummy_tool], {"foo": "bar"}, True), - ([dummy_tool], {"foo": "bar"}, False), + ([google_search, dummy_tool], grounding_metadata, True), + ([dummy_tool], grounding_metadata, False), ([google_search, dummy_tool], None, False), ], ids=[ @@ -521,9 +522,9 @@ async def call(self, **kwargs): assert invocation_context.canonical_tools_cache is None - invocation_context.session.state["temp:_adk_grounding_metadata"] = { - "foo": "bar" - } + invocation_context.session.state["temp:_adk_grounding_metadata"] = ( + grounding_metadata + ) llm_response = LlmResponse( content=types.Content(parts=[types.Part.from_text(text="response")]) @@ -553,9 +554,40 @@ async def call(self, **kwargs): assert len(invocation_context.canonical_tools_cache) == 1 assert invocation_context.canonical_tools_cache[0].name == "research_agent" - assert result1.grounding_metadata == {"foo": "bar"} - assert result2.grounding_metadata == {"foo": "bar"} - assert result3.grounding_metadata == {"foo": "bar"} + assert result1.grounding_metadata == grounding_metadata + assert result2.grounding_metadata == grounding_metadata + assert result3.grounding_metadata == grounding_metadata + + +@pytest.mark.asyncio +async def test_handle_after_model_callback_ignores_invalid_grounding_metadata( + caplog: pytest.LogCaptureFixture, +): + """Invalid grounding metadata in state is logged and not attached.""" + agent = Agent(name="test_agent", tools=[google_search, dummy_tool]) + invocation_context = await testing_utils.create_invocation_context( + agent=agent + ) + 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, + ) + + result = await _model_response_finalizer.handle_after_model_callback( + invocation_context, llm_response, event + ) + + assert result is None + assert llm_response.grounding_metadata is None + assert "Ignoring invalid temp:_adk_grounding_metadata" in caplog.text # --- Tests for run_and_handle_error --- diff --git a/tests/unittests/tools/test_google_search_agent_tool.py b/tests/unittests/tools/test_google_search_agent_tool.py index 701f3c45414..e85266cd208 100644 --- a/tests/unittests/tools/test_google_search_agent_tool.py +++ b/tests/unittests/tools/test_google_search_agent_tool.py @@ -183,3 +183,59 @@ async def test_grounding_metadata_is_not_stored_in_state_after_invocation(): # Verify grounding_metadata is not stored in the root_agent's state assert 'temp:_adk_grounding_metadata' not in runner.session.state + + +@mark.asyncio +async def test_grounding_metadata_keeps_its_type_with_parallel_tool_calls(): + """Grounding metadata stays typed when another tool runs in the same step.""" + search_grounding_metadata = types.GroundingMetadata( + web_search_queries=['test query'], + search_entry_point=types.SearchEntryPoint( + rendered_content='