Skip to content

Google Search Tool does not return grounding metadata in ADK Runner events #1693

Closed

Description

@robert-h-dss

** Please make sure you read the contribution guide and file the issues in the right place. **
Contribution guide.

Describe the bug
When utilizing the Google Search tool within an ADK Runner flow, the event objects emitted by the Runner do not contain the expected grounding_metadata. This metadata, crucial for understanding the source and reliability of information, is absent from the event representing the tool's output.

While grounding_metadata appears to be logged elsewhere (e.g., in debug or info logs), it is not accessible directly within the Runner's event stream after the tool execution, which prevents programmatic access to provenance information.

To Reproduce

Steps to reproduce the behavior:

  1. Configure the ADK agents with the structure shown below, which includes an orchestrator_agent using a chat_agent, which in turn uses a google_search_agent as a tool:

    from google.adk.agents.llm_agent import LlmAgent
    from google.adk.tools import agent_tool
    from google.adk.tools import google_search
    
    orchestrator_agent = LlmAgent(
        model=_settings.google_llm_model,
        name="ai_assistant",
        instruction=(prompt.INSTRUCTION_PROMPT),
        sub_agents=[
          chat_agent,
          # ... other sub_agents
        ],
    )
    
    chat_agent = LlmAgent(
        model=_settings.google_llm_model,
        name="chat_ai_assistant",
        instruction=(prompt.INSTRUCTION_PROMPT),
        global_instruction=(prompt.GLOBAL_PROMPT),
        tools=[
            agent_tool.AgentTool(agent=google_search_agent, skip_summarization=True),
        ],
        sub_agents=[
            faq_agent,
            # ... other sub_agents
        ],
    )
    
    google_search_agent = LlmAgent(
        model=_settings.google_llm_model,
        name="google_search_agent",
        instruction=prompt.GOOGLE_SEARCH_PROMPT,
        tools=[
            google_search
        ],
    )
    
    faq_agent = LlmAgent(
        model=_settings.google_llm_model,
        name="faq_agent",
        instruction=prompt.FAQ_PROMPT,
        tools=(
            [
              faq_tool
            ]
        ),
    )
  2. Implement a process_message function that uses the Runner to interact with the orchestrator agent and iterates through its events:

    async def process_message(
        self, query: str, session_id: str, user_id: str, dtr_token: str
      ) -> str:
        """Process a message and get the agent's response.
    
        Args:
          query: The user's query
          session_id: The session ID
    
        Returns:
          str: The agent's response
        """
        try:
          # Ensure session exists
          self.get_or_create_session(session_id, user_id, dtr_token)
    
          # Create runner
          runner = Runner(
            agent=orchestrator_agent,
            app_name=self.app_name,
            session_service=self.session_service,
          )
    
          # Prepare user message
          content = types.Content(role="user", parts=[types.Part(text=query)])
    
          # Default response
          final_response_text = "Agent did not produce a final response."
    
          # Run agent and get response
          async for event in runner.run_async(
            user_id=user_id, session_id=session_id, new_message=content
          ):
            # Observe 'event' objects here.
            # print(f"Received event: {event}") # Add this to inspect events
            if event.is_final_response():
              if event.content and event.content.parts:
                if event.content.parts[0].function_response:
                  final_response_text = event.content.parts[
                    0
                  ].function_response.response["result"]
                elif event.content.parts[0].text:
                  final_response_text = event.content.parts[0].text
                else:
                  final_response_text = event.content.parts[1].text
              elif event.actions and event.actions.escalate:
                final_response_text = f"Agent escalated: {event.error_message or 'No specific message.'}"
              break
    
          return final_response_text
    
        except Exception as e:
          logger.error(f"Error processing message: ") # Consider adding {e} to the log message
          raise
  3. Call process_message with a query that prompts the chat_agent to use the google_search_agent tool.

  4. Examine the event objects yielded by runner.run_async(). Observe that the event pertaining to the google_search tool's result lacks grounding_metadata.

Expected behavior
The event object corresponding to the google_search tool's output should include grounding_metadata. This metadata should be accessible directly within the event structure (e.g., event.content.parts[0].tool_output.grounding_metadata or a similar path) to allow downstream processing of sourced information.

It is suspected that an intermediary event object might be missing between the AgentTool call event and its eventual result event that should contain this metadata.

Screenshots
If applicable, add screenshots to help explain your problem.

Desktop (please complete the following information):

  • OS: macOS 15.5
  • Python version(python -V): 3.13.2
  • ADK version(pip show google-adk): 1.3.0

Model Information:
gemini-2.5-flash

Additional context
The described agent structure (orchestrator -> chat_agent -> google_search_agent) is intended to fully leverage the Google Search tool. However, the current event emission by the Runner prevents direct access to grounding information.

Additionally, related functionalities such as skip_summarization (when set on the AgentTool) and general tool callback mechanisms also do not appear to function as expected.

Activity

  1. added
    tracing[Component] This issue is related to OpenTelemetry tracing
    on Jun 27, 2025
  2. KSonPham commented on Jul 2, 2025

    @KSonPham

    Hey @robert-h-dss have you tried:

    gm = event.grounding_metadata
            if gm and gm.grounding_chunks:
                for chunk in gm.grounding_chunks:
                    if chunk.web and chunk.web.uri:
                        citations.append(chunk.web.uri)
    
  3. robert-h-dss commented on Jul 2, 2025

    @robert-h-dss
    Author

    Hey @KSonPham as I mentioned with the setup above, the whole event stream does not contain grounding_metadata.

  4. renshi-a commented on Jul 19, 2025

    @renshi-a

    I've investigated this issue and found the root cause of why GroundingMetadata is not being returned when using google_search_agent through AgentTool.

    Investigation Summary

    Test Setup

    I created comprehensive tests in ADK-Java with different approaches:

    1. Direct LlmAgent with GoogleSearchTool
    2. Using Runner with GoogleSearchTool
    3. Using AgentTool.create() to wrap the search agent

    Results

    • Test 1 & 2: ✅ Successfully retrieved GroundingMetadata
    • Test 3: ❌ No GroundingMetadata returned through AgentTool

    Root Cause

    The issue is in the AgentTool implementation in both ADK-Python and ADK-Java. The tool only returns the text content from the last event, discarding all other event metadata including GroundingMetadata:

    ADK-Python

    user_id='tmp_user',
    state=tool_context.state.to_dict(),
    )
    last_event = None
    async for event in runner.run_async(
    user_id=session.user_id, session_id=session.id, new_message=content
    ):

      if not last_event or not last_event.content or not last_event.content.parts:
        return ''
      merged_text = '\n'.join(p.text for p in last_event.content.parts if p.text)
      # ... 
      return tool_result  # Only returns text or parsed object, no metadata

    ADK-Java (AgentTool.java:113-145):

      .lastElement()
      .map(optionalLastEvent -> {
          // ... extracts only text content
          return ImmutableMap.of("result", output);
      })

    When Google Search is executed, the agent's response event contains both:

    • The answer text in event.content
    • The GroundingMetadata in event.groundingMetadata

    However, AgentTool only extracts and returns the text portion, discarding the GroundingMetadata.

    Update

    I've discovered that while AgentTool loses GroundingMetadata, using a custom BaseAgent as a subagent successfully preserves it.

    When you create a custom agent that extends BaseAgent and use it as a subagent (not via AgentTool), the entire event stream is propagated to the parent agent, including GroundingMetadata:

    Python equivalent example

      class GoogleSearchAgent(BaseAgent):
          def __init__(self):
              super().__init__(name="google_search_agent",
      description="Performs Google searches")
              self.internal_agent = LlmAgent(
                  tools=[GoogleSearchTool()],
                  # ... other config
              )
    
          async def run_async(self, invocation_context):
              # Simply return the internal agent's event 
      stream
              async for event in
      self.internal_agent.run_async(invocation_context):
                  yield event  # All events including 
      GroundingMetadata are preserved
    
      ### Use as subagent
      main_agent = LlmAgent(
          sub_agents=[GoogleSearchAgent()],  # ✅ 
      GroundingMetadata preserved
          # ... other config
      )

    The crucial difference is that:

    • AgentTool: Extracts only the final text/object from the event stream
    • SubAgent: Passes the entire event stream to the parent, preserving all metadata

    This provides a viable workaround for scenarios where you need to modularize Google Search functionality while preserving GroundingMetadata.

  5. robert-h-dss commented on Jul 21, 2025

    @robert-h-dss
    Author

    @renshi-a Hi! Thank you for your comment!

    I have tried this work around, doesn't work in case you want to use more sub-agents (see example implementation above).

    Error is the following:

    2025-07-21 09:08:56.429 | ERROR | process_message:85 | Error processing message: 400 INVALID_ARGUMENT. {'error': {'code': 400, 'message': 'Multiple tools are supported only when they are all search tools.', 'status': 'INVALID_ARGUMENT'}} 2025-07-21 09:08:56.430 | ERROR | chat:50 | Error in chat endpoint: 400 INVALID_ARGUMENT. {'error': {'code': 400, 'message': 'Multiple tools are supported only when they are all search tools.', 'status': 'INVALID_ARGUMENT'}}

    The code doesn't run if you have multiple sub-agents or either agent as tools. (And of course the important thing is that you have more than one (sub)agent than Google Search.)

  6. bmigette commented on Aug 5, 2025

    @bmigette

    I'm facing the same issue, I have an agent that leverages 2 Agents as AgentTool, one for websearch, and one for RAG, it seems to be loosing groundingMetadata with this approach

    main_agent = Agent(
        model=GEMINI_MODEL,
        name='main_agent',
        description="Agent to answer question",
        instruction=return_instructions_root(),
        tools=[        
            AgentTool(agent=rag_agent),
            AgentTool(agent=google_search_agent),
        ]
    )
    

    Is there a way to retrieve the groundingMetadata one way or the other ?
    Edit: It seems using SequentialAgent + ParallelAgent as described in this example might do the trick:
    https://google.github.io/adk-docs/agents/workflow-agents/parallel-agents/#how-it-works

    Edit2: While I get the event results for all sub_agents running the main agent locally (via adk web), I get only the final event when using a deployed agent on AgentEngine, and grounding info is not retrieved. So still looking for a good solution for this too :)

  7. added this to the 08/11 FixIt Week milestone on Aug 8, 2025
  8. odrobek commented on Aug 22, 2025

    @odrobek

    I'd also like to see a solution to this. While building an agent, Google Search and RAG tools are vital, but the only workaround is using AgentTool wrappers, which as this issue describes, loses all grounding metadata, which is also vital to the function of the agent. Would love to know if there will be a solution for this or if anyone has found any workarounds, especially for the deployed agents.

    As @robert-h-dss notes above, using multiple sub-agents is not possible with multiple different built in tools, so AgentTool wrapping is currently the only way to get the search working, but the grounding metadata is lost. Hoping this is resolved sometime soon.

  9. seanzhou1023 commented on Aug 29, 2025

    @seanzhou1023
    Collaborator

    Thanks for reporting the issue. I understand this issue only happens when you use an agent (which uses google_search tool) as tool. This is the current limitation. we don't support tool response with grounding_metadata.

    a work around you can do is that the parent agent and the agent wrapped in the tool shares artifact service, you can use artifact service as a media to pass this information :

    1. you have an after_model_callback for the agent that is wrapped as tool that save the grounding_metadata from the llm_response to artifact service.
    2. you have an after_agent_callback / after_tool_callback for the parent agent to read the grounding_metadata from the artifact service

    Let me know if that works for you.

    meanwhile we will explore how we can let tool return some metadata that agent can encode them into event yielded

  10. maryshgh commented on Sep 8, 2025

    @maryshgh

    I believe artifacts are recommended for specific types of data and use cases, my issue is that the python dictionary returned by tool is converted to a text by agent wrapped in the AgentTool, it doesn't seem practical to add all that complexities with artifacts to only be able to pass a python dictionary, can we just store them in state using the callback tools?

  11. bmigette commented on Sep 11, 2025

    @bmigette

    Hi, here's a working example I've managed to do. I haven't tested it thoroughly. The session state might persists during multiple messages, so you might need a before_model callback to clear it. In my case, appending the temp: prefix prevented to get the output.

    Agent:

    corpus = os.environ.get("RAG_JIRA_CORPUS")
    assert corpus is not None
    
    def save_grounding_metadata(callback_context: CallbackContext, llm_response: LlmResponse) -> Optional[types.Content]:
        callback_context.state["rag_grounding_sources"] = llm_response.grounding_metadata
        # temp: to persist only during invocation. Won't be available after agent execution
        # https://google.github.io/adk-docs/sessions/state/#organizing-state-with-prefixes-scope-matters
        return None
    
    jira_rag_tool = VertexAiRagRetrieval(
        name='jira_rag_tool',
        description=(
            'Use this tool to retrieve Jira ticket details from the RAG corpus,'
        ),
        rag_resources=[
            rag.RagResource(
                rag_corpus=corpus
            )
        ],
        similarity_top_k=10,
        vector_distance_threshold=0.6,
    )
    
    jira_rag_agent_rag = Agent(
        model=GEMINI_MODEL,
        name="jira_rag_agent",
        description="Agent to answer questions RAG with Jira Tickets.",
        instruction=prompt.JIRA_RAG_PROMPT_RAG,
        #output_key="google_search_output",
        tools=[jira_rag_tool],
        after_model_callback = save_grounding_metadata
    )
    # https://google.github.io/adk-docs/tools/built-in-tools/#use-built-in-tools-with-other-tools
    # Currently, for each root agent or single agent, only one built-in tool is supported. No other tools of any type can be used in the same agent.
    # Solution: Create a secondary agent with RAG tool and include it as a tool in root agent
    jira_rag_agent = Agent(
        model=GEMINI_MODEL,
        name="jira_rag_agent",
        description="Agent to answer questions RAG with Jira Tickets.",
        instruction=prompt.JIRA_RAG_PROMPT,
        #output_key="google_search_output",
        #tools=[jira_rag_tool, get_single_jira_details],
        tools=[AgentTool(jira_rag_agent_rag), get_single_jira_details],
    )
    
    root_agent = jira_rag_agent

    Getting metadata:

    async def get_chat_response_from_chat_id(self, query: str, user: str, chat_id: str) -> AIAgentResult:
            """
            Retrieve chat response using specific chat ID for Google Search Agent
    
            Args:
                query (str): User's input message
                chat_id (str): Unique identifier for the chat session
                urns:
                dict: Response from ADK
            """
            # Placeholder for actual implementation
            #
            #session = self.agent_engine.get_session(user_id=user, session_id=chat_id)
            logger.debug("get_chat_response_from_chat_id session %s", chat_id)
            text_parts = []
            sources = []
            events = []
            source_offset = 0
            content = types.Content(role="user", parts=[types.Part(text=query)])
            async for event in self.runner.run_async(
                user_id=user,
                session_id=chat_id,
                new_message=content,
            ):
    
                logger.debug("\n\n-------------------------")
                logger.debug(f"event : ")
                logger.debug("-------------------------\n\n")
    
                logger.debug(f"event.invocation_id: {event.invocation_id}")
                logger.debug(f"event.id: {event.id}")
                logger.debug(f"event.is_final_response(): {event.is_final_response()}")                       
    
                if event.is_final_response():
                    session = self.session_service.get_session_sync(user_id=user, session_id=chat_id, app_name=APP_NAME)
                    logger.debug("Session State Grounding Data: %s", session.state['rag_grounding_sources']) #Here  you can get 
                    text_part = self._get_text_parts_from_event(event)
                    text_parts.extend(text_part)
                    sources.extend(self._get_sources_from_event(event, source_offset))
                    source_offset += len(text_part)
    
                events.append(event)
            self._last_events = events
            return AIAgentResult(True, self.model_name, text_parts, sources, events)
  12. removed this from the 08/11 FixIt Week milestone on Oct 28, 2025
  13. 2 remaining items

  14. added
    tools[Component] This issue is related to tools
    and removed
    tracing[Component] This issue is related to OpenTelemetry tracing
    on Nov 6, 2025
  15. added theissue type on Nov 6, 2025
  16. kurochig commented on Dec 24, 2025

    @kurochig

    In my case the callback_context example from the above didn't work. I have an orchestrator agent having search agent as a tool, which has a search tool of its own. In a nutshell orchestrator => search => tool.

    There is session isolation: When AgentTool calls search_agent, it creates a separate session with its own session ID (see agent_tool.py in ADK lines 137-152):

    • Orchestrator agent: Session A
    • First search_agent call: Session B
    • Second search_agent call: Session C

    When we store metadata in callback_context.state['metadata'], which is invocation-scoped and stored in each search_agent's session state.
    State forwarding: Only event.actions.state_delta is forwarded from child to parent (see agent_tool.py lines 162-163)
    Also, when state is updated, then it replaces values (dict.update), so lists aren't merged. When we have two child sessions running in parallel, then only one of them would end up in parent, the other one is simply overwritten.

    Hence the function that collects metadata

    async def save_grounding_metadata(callback_context: CallbackContext, llm_response: LlmResponse) -> None:
        """Save grounding metadata from LLM response to state for later retrieval.
    
        Stores the metadata in state_delta so it gets forwarded from child agent sessions
        to the parent agent session. This allows the parent agent (triage_agent) to access
        grounding metadata from all search_agent invocations.
    
        STRATEGY: Since State.update() replaces values (doesn't merge lists), and parallel
        child agent calls can overwrite each other's state_delta, we use a unique key per
        call. Each search_agent call stores its metadata with a unique identifier (timestamp + UUID),
        and the plugin collects all such entries and merges them.
    
        Args:
            callback_context: The callback context with access to event_actions
            llm_response: The LLM response containing grounding_metadata
        """
        grounding_metadata = llm_response.grounding_metadata
    
        if grounding_metadata is None:
            return None
    
        # Set state_delta to forward metadata to parent session
        # Use a unique key per call to avoid overwriting when multiple search_agent calls
        # happen in parallel. The plugin will collect all such entries and merge them.
        event_actions = callback_context._event_actions
        if event_actions is not None:
            # Generate a unique key for this call using timestamp and UUID
            unique_key = f"google_search_grounding_sources_{int(time.time() * 1000000)}_{uuid.uuid4().hex[:8]}"
            event_actions.state_delta[unique_key] = grounding_metadata
    
        return None

    This function is attached as the following:

    LlmAgent(
            name=SEARCH_AGENT_NAME,
            model=ModelProviders.GEMINI_2_5_FLASH_ADK,
            description="Agent to answer questions using Google Search.",
            instruction=SEARCH_AGENT_INSTRUCTION,
            tools=[google_search],
            before_model_callback=get_global_callbacks(),
            after_model_callback=save_grounding_metadata,
        )

    I have a plugin that collects the metadata

        app = App(
            name=app_name,
            root_agent=run_agent,
            ...        
            plugins=[
                FinalResponseTaggerPlugin(),
            ],
        )

    The plugin has after_run_callback:

    class FinalResponseTaggerPlugin(BasePlugin):
    ...
        async def after_run_callback(self, *, invocation_context: InvocationContext) -> None:
                """Finds the last final response and updates it in the DB and memory."""
                session = invocation_context.session
                current_invocation_id = invocation_context.invocation_id
                target_event = self._find_target_event(session, current_invocation_id)
                if not target_event:
                    logger.warning(
                        "No final response event found to tag for invocation %s",
                        current_invocation_id,
                    )
                    return
        
                grounding_sources = self._extract_grounding_sources(session, invocation_context)
                self._update_event_in_memory(target_event, grounding_sources)
                self._update_event_in_database(invocation_context.session_service, session, target_event)

    here is what _extract_grounding_sources does, it's written very defensively, so kind of verbose

            def _extract_grounding_sources(self, session: Session, invocation_context: InvocationContext) -> list[str] | None:
                """Extract google_search_grounding_sources from state if available.
        
                This is stored by save_grounding_metadata callback in search_agent via state_delta.
                The state_delta is forwarded from child agent sessions to the parent session via
                AgentTool's state forwarding mechanism.
        
                STRATEGY: Since State.update() replaces values and parallel calls can overwrite
                each other, each search_agent call stores its metadata with a unique key
                (google_search_grounding_sources_<timestamp>_<uuid>). This method collects all
                such keys from the session state and merges them into a single list.
        
                Returns:
                    List of grounding metadata entries, or None if not found
                """
                try:
                    session_state = None
                    if hasattr(session, "state"):
                        session_state = session.state
                    elif hasattr(invocation_context, "session") and invocation_context.session is not None:
                        if hasattr(invocation_context.session, "state"):
                            session_state = invocation_context.session.state
        
                    if session_state is None:
                        return None
        
                    all_grounding_metadata = []
                    try:
                        if isinstance(session_state, dict):
                            state_dict = session_state
                        elif hasattr(session_state, "to_dict"):
                            state_dict = session_state.to_dict()
                        else:
                            # Try to access it like a dict
                            state_dict = dict(session_state) if hasattr(session_state, "__iter__") else {}
                    except Exception as e:
                        # Fallback: try to use it as-is if it's dict-like
                        state_dict = session_state if isinstance(session_state, dict) else {}
        
                    # Collect all keys matching the pattern google_search_grounding_sources_*
                    for key, value in state_dict.items():
                        if key.startswith("google_search_grounding_sources_"):
                            if value is not None:
                                if isinstance(value, list):
                                    all_grounding_metadata.extend(value)
                                else:
                                    all_grounding_metadata.append(value)
        
                    if all_grounding_metadata:
                        return all_grounding_metadata
        
                    return None
                except Exception as e:
                    logger.warning(f"Could not retrieve grounding_sources from state: {e}")
                return None

    This solution worked for me.

  17. surajksharma07 commented on Jan 16, 2026

    @surajksharma07
    Collaborator

    This is a known limitation with AgentTool - it only extracts text content and discards grounding_metadata.

    Use GoogleSearchAgentTool from google.adk.tools.google_search_agent_tool instead:

    from google.adk.tools.google_search_agent_tool import GoogleSearchAgentTool, create_google_search_agent
    search_tool = GoogleSearchAgentTool(create_google_search_agent("gemini-2.0-flash"))

    After the run completes, access grounding metadata via session.state.get("temp:_adk_grounding_metadata").

  18. surajksharma07 commented on Feb 4, 2026

    @surajksharma07
    Collaborator

    Checked against latest ADK (post v1.23.0) — the core AgentTool bug is still present.

    agent_tool.py:247-276 still only extracts text from the last event and discards grounding_metadata.

    However, GoogleSearchAgentTool (google_search_agent_tool.py:111-140) is available as a workaround — it captures grounding metadata and stores it in session.state["temp:_adk_grounding_metadata"].

    This workaround is marked temporary internally (TODO(b/448114567)), indicating the team intends to fix AgentTool itself.

  19. added
    needs review[Status] The PR/issue is awaiting review from the maintainer
    on Feb 4, 2026
  20. surajksharma07 commented on Feb 4, 2026

    @surajksharma07
    Collaborator

    @Jacksunwei Please have a look into it once.

  21. xuanyang15 commented on Apr 5, 2026

    @xuanyang15
    Collaborator

    Grounding metadata is part of the llm response, it is not an event to emit. We have added a propagate_grounding_metadata parameter in AgentTool (d689a04), which can be used to propagate grounding metadata from AgentTool to its parent agent. If you need other operation on the grounding metadata, you can also consider using callbacks to read and manipulate the metadata in state['temp:_adk_grounding_metadata'].

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

Metadata

Metadata

Assignees

Labels

needs review[Status] The PR/issue is awaiting review from the maintainertools[Component] This issue is related to tools

Type

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions