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

未关闭
#8,205 3 条评论 0 个 reaction 已指派 1 人 在 GitHub 查看

维护者通常 3 天内回复

@surajksharma07 已经在做这个了。

开始于 2026年11月18日。

  • #8206 来自 @SoroushRF —— 未关闭

评估

这个 Issue 还没有评估数据。

描述

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

主要语言
Python
星标
22.3k
派生
4.4k
平均合并
1 天 2 小时
30 天内合并 PR
6

环境准备

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

google/adk-python 的其他 Issue

查看 google/adk-python 的全部 Issue

相似的 Issue

更多 Python Issue

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。