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

Aberta
#8,205 3 comentários 0 reações 1 responsável Ver no GitHub

Mantenedores costumam responder em até 3 dias

@surajksharma07 já está trabalhando nisso.

Desde 18/11/2026.

  • #8206 de @SoroushRF — aberto

Avaliação

Esta issue ainda não foi avaliada.

Descrição

🔴 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).

Linguagem predominante
Python
Estrelas
22.3k
Forks
4.4k
Merge médio
1d 2h
PRs com merge (30d)
6

Preparar o ambiente

Primeiros passos

  1. Leia a issue inteira e depois o guia de contribuição do projeto.
  2. Comente na issue dizendo que vai assumir — evita que duas pessoas façam o mesmo trabalho.
  3. Faça um fork do repositório e trabalhe em uma branch.
  4. Abra um pull request que referencie o número da issue.

Mais de google/adk-python

Todas as issues de google/adk-python

Issues semelhantes

Mais issues de Python

Receba novas issues na sua caixa de entrada

Um resumo curto de issues do GitHub para quem está começando.