Skip to content

Grounding metadata becomes a dict when a grounding tool runs alongside another tool call #8205

Description

@SoroushRF

🔴 Required Information

Describe the Bug:

Follow-up to #6848. Since #6932 the parallel merge no longer crashes, but the grounding metadata now comes out with the wrong type.

When a grounding tool (AgentTool(propagate_grounding_metadata=True), which is what GoogleSearchAgentTool uses) runs in the same model step as any other tool call, the final event's grounding_metadata is a plain dict with camelCase keys instead of a google.genai.types.GroundingMetadata. With a single tool call it is a GroundingMetadata, as expected.

Cause, on current main (277553a02):

  1. AgentTool stores the sub-agent's GroundingMetadata object in temp:_adk_grounding_metadata (src/google/adk/tools/agent_tool.py:532).
  2. With two or more tool calls, merge_parallel_function_response_events merges the response events through event.actions.model_dump(exclude_none=True, by_alias=True) (src/google/adk/flows/llm_flows/tools/_batch_executor.py:88). state_delta is dict[str, Any], so the dump turns the stored object into {'webSearchQueries': [...], 'searchEntryPoint': {...}} and it stays a dict when the merged event is applied to the session state.
  3. handle_after_model_callback reads that value and assigns it to response.grounding_metadata without validating it (src/google/adk/flows/llm_flows/core/_finalizer.py:330). LlmResponse does not validate on assignment, so the dict ends up on the event.

As a result, event.grounding_metadata.search_entry_point (and any other attribute) raises AttributeError, and event.model_dump_json() emits PydanticSerializationUnexpectedValue warnings.

Steps to Reproduce:

  1. Install ADK from main (pip install git+https://github.com/google/adk-python.git).
  2. Save the script under Minimal Reproduction Code as repro.py. It uses a local stub model, so no API key or network call is needed.
  3. Run python repro.py.

Expected Behavior:

The final event's grounding_metadata is a GroundingMetadata, the same as with a single tool call:

<class 'google.genai.types.GroundingMetadata'>
<div>chips</div>

Observed Behavior:

<class 'dict'>
Traceback (most recent call last):
  ...
    print(metadata.search_entry_point.rendered_content)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'dict' object has no attribute 'search_entry_point'

Serializing the same event with event.model_dump_json() emits two warnings of the form:

UserWarning: Pydantic serializer warnings:
  PydanticSerializationUnexpectedValue(Expected `GroundingMetadata` - serialized value may not be as expected [field_name='grounding_metadata', ...

The same happens when two grounding tools are called in the same step: the value is a dict produced by the recursive merge of both calls' metadata (later values win where fields overlap).

Environment Details:

  • ADK Library Version (pip show google-adk): main at 277553a02 (version string 2.14.1)
  • Desktop OS: Windows 11 (the code path is not OS-specific)
  • Python Version (python -V): 3.12.10
  • google-genai 2.34.0, pydantic 2.14.3

Model Information:

  • Are you using LiteLLM: No
  • Which model is being used: N/A, a local stub model returns the grounding metadata. I have not run it against a live Gemini model with Google Search.

🟡 Optional Information

Regression:

Not checked against earlier releases. Before #6932 the same parallel setup could raise during the merge instead (#6848).

Additional Context:

Validating the value where the finalizer reads it (types.GroundingMetadata.model_validate(...)) fixes the single-tool, tool-plus-search and two-search cases. I have a PR ready with that change and a regression test that goes through the parallel tool-call path.

Open PR #6849 changes how deferred Pydantic state models are serialized and does not restore the type of this field.

Minimal Reproduction Code:

import asyncio

from google.adk.agents import LlmAgent
from google.adk.models.base_llm import BaseLlm
from google.adk.models.llm_response import LlmResponse
from google.adk.runners import InMemoryRunner
from google.adk.tools.agent_tool import AgentTool
from google.genai import types


class ScriptedModel(BaseLlm):
  """Stub model: returns the next scripted response, no network."""

  model: str = 'scripted'
  responses: list[LlmResponse]

  async def generate_content_async(self, llm_request, stream=False):
    yield self.responses.pop(0)


def reply(*parts, grounding_metadata=None):
  return LlmResponse(
      content=types.Content(role='model', parts=list(parts)),
      grounding_metadata=grounding_metadata,
  )


def call(name, args):
  return types.Part(function_call=types.FunctionCall(name=name, args=args))


def get_weather(city: str) -> dict:
  return {'city': city, 'weather': 'sunny'}


# A sub-agent whose model answers with search grounding, wrapped the way
# GoogleSearchAgentTool wraps its search agent.
searcher = LlmAgent(
    name='searcher',
    description='Searches the web.',
    model=ScriptedModel(
        responses=[
            reply(
                types.Part(text='ADK 2.14 was released.'),
                grounding_metadata=types.GroundingMetadata(
                    web_search_queries=['adk release'],
                    search_entry_point=types.SearchEntryPoint(
                        rendered_content='<div>chips</div>'
                    ),
                ),
            )
        ]
    ),
)

# The root model calls the search tool and one other tool in the same step.
root = LlmAgent(
    name='root',
    model=ScriptedModel(
        responses=[
            reply(
                call('searcher', {'request': 'adk release'}),
                call('get_weather', {'city': 'Paris'}),
            ),
            reply(types.Part(text='final answer')),
        ]
    ),
    tools=[AgentTool(searcher, propagate_grounding_metadata=True), get_weather],
)


async def main():
  runner = InMemoryRunner(agent=root)
  session = await runner.session_service.create_session(
      app_name=runner.app_name, user_id='u'
  )
  events = [
      e
      async for e in runner.run_async(
          user_id='u',
          session_id=session.id,
          new_message=types.Content(role='user', parts=[types.Part(text='hi')]),
      )
  ]
  metadata = events[-1].grounding_metadata
  print(type(metadata))
  print(metadata.search_entry_point.rendered_content)


asyncio.run(main())

Remove the get_weather call from the first scripted reply and the script prints the expected output.

How often has this issue occurred?:

  • Always (100%), whenever a grounding tool runs in the same step as at least one other tool call

Prepared with AI assistance (Claude Code). The reproduction above was run on current main (277553a02).

Activity

  1. surajksharma07 commented on Nov 19, 2026

    @surajksharma07
    Collaborator

    @SoroushRF. Reproduced on 2.14.1 and 1.27.2 too: a single call gives GroundingMetadata, while search + get_weather in the same step gives a dict.

    Until #8206 lands, a small plugin with an on_event_callback that does types.GroundingMetadata.model_validate(event.grounding_metadata) when it’s a dict works as a workaround on my end. It also fixes the copy that gets saved to the session.

    Since your repro uses a stub model, could you try it with a real GoogleSearchAgentTool plus one function tool and confirm the metadata comes back typed?

    If that holds up on your side we can push #8206 forward for review. It would also be good to confirm the merged result for the two-search case is what we want.

  2. SoroushRF commented on Nov 19, 2026

    @SoroushRF
    ContributorAuthor

    Thanks, @surajksharma07, for reproducing this on 2.14.1 and 1.27.2 and for sharing the on_event_callback workaround. The detail about the saved session event is helpful.

    The regression test in #8206 uses GoogleSearchAgentTool and a function tool in the same step, with stubbed model responses. It checks that both tool responses merge and that the final event retains the original GroundingMetadata. I tried the live check with a free-tier Gemini project, but both model requests returned a 404 before the tools could run, so live validation is still open.

    On the two-search case, the current merge replaces overlapping fields with later values and can retain fields from both calls. That can leave citation supports from one search pointing at chunks from the other. #8206 restores the type of the merged metadata. Combining citations from both searches needs its own merge policy.

  3. surajksharma07 commented on Nov 23, 2026

    @surajksharma07
    Collaborator

    Thanks @SoroushRF, no worries about the live run. The 404 happens before any tool runs, and everything after the model response goes through the same code path your stub does, so I don't think it should block #8206.

    Checked again on 2.15.0 (current main): _finalizer.py hasn't changed and the parallel case still comes back as a dict. Also went through #8206. model_validate turns the camelCase dict back into an equal GroundingMetadata and returns the same object when it's already typed, so the single-call path stays as it is. Validating where the value is read looks like the right minimal fix to me.

    Agreed on the two-search case. Merging citations from two searches needs its own policy, so could you open a separate issue for it and keep #8206 focused on restoring the type? I'll flag #8206 for review and mention the one-line import conflict with #7896 you noted.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

No labels
No labels

Type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions