Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 12 additions & 2 deletions src/google/adk/flows/llm_flows/core/_finalizer.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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],
Expand Down Expand Up @@ -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
Expand Down
56 changes: 44 additions & 12 deletions tests/unittests/flows/llm_flows/core/test_finalizer.py
Original file line number Diff line number Diff line change
Expand Up @@ -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():
Expand Down Expand Up @@ -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=[
Expand Down Expand Up @@ -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=[
Expand Down Expand Up @@ -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=[
Expand Down Expand Up @@ -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")])
Expand Down Expand Up @@ -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 ---
Expand Down
56 changes: 56 additions & 0 deletions tests/unittests/tools/test_google_search_agent_tool.py
Original file line number Diff line number Diff line change
Expand Up @@ -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='<div>search suggestions</div>'
),
)
tool_agent_model = testing_utils.MockModel.create(
responses=[
LlmResponse(
content=types.Content(
parts=[Part.from_text(text='response from tool')]
),
grounding_metadata=search_grounding_metadata,
)
]
)

tool_agent = Agent(
name='tool_agent',
model=tool_agent_model,
)

def other_tool() -> str:
return 'other result'

# Both calls come in one model response, so they run in parallel and their
# response events are merged.
root_agent_model = testing_utils.MockModel.create(
responses=[
[
function_call_no_schema,
Part.from_function_call(name='other_tool', args={}),
],
'Final response from root',
]
)

root_agent = Agent(
name='root_agent',
model=root_agent_model,
tools=[GoogleSearchAgentTool(agent=tool_agent), other_tool],
)

runner = testing_utils.InMemoryRunner(root_agent)
events = runner.run('test input')

assert any(len(event.get_function_responses()) == 2 for event in events)
final_event = events[-1]
assert final_event.content.parts[0].text == 'Final response from root'
assert isinstance(final_event.grounding_metadata, types.GroundingMetadata)
assert final_event.grounding_metadata == search_grounding_metadata
Loading