Skip to content

Understanding Google Search Grounding

理解 Google 搜索基础

Supported in ADKPython v0.1.0TypeScript v0.2.0

Google Search Grounding tool is a powerful feature in the Agent Development Kit (ADK) that enables AI agents to access real-time, authoritative information from the web. By connecting your agents to Google Search, you can provide users with up-to-date answers backed by reliable sources.

Google 搜索基础工具 是智能体开发工具包 (ADK) 中的一项强大功能,使 AI 智能体能够从网络访问实时、权威的信息。通过将您的智能体连接到 Google 搜索,您可以向用户提供基于可靠来源的最新答案。

This feature is particularly valuable for queries requiring current information like weather updates, news events, stock prices, or any facts that may have changed since the model's training data cutoff. When your agent determines that external information is needed, it automatically performs web searches and incorporates the results into its response with proper attribution.

此功能对于需要最新信息的查询特别有价值,例如天气更新、新闻事件、股票价格,或自模型训练数据截止以来可能已更改的任何事实。当您的智能体确定需要外部信息时,它会自动执行网络搜索,并将结果与正确的归属一起纳入其响应中。

What You'll Learn

您将学到

In this guide, you'll discover:

在本指南中,您将发现:

  • Quick Setup: How to create and run a Google Search-enabled agent from scratch
  • 快速设置: 如何从头开始创建和运行启用了 Google 搜索的智能体
  • Grounding Architecture: The data flow and technical process behind web grounding
  • 基础架构: Web 基础背后的数据流和技术过程
  • Response Structure: How to interpret grounded responses and their metadata
  • 响应结构: 如何解释基础响应及其元数据
  • Best Practices: Guidelines for displaying search results and citations to users
  • 最佳实践: 向用户显示搜索结果和引用的指南

Additional resource

其他资源

As an additional resource, the Deep Search Agent Development Kit (ADK) Quickstart has a practical use of the Google Search grounding as a full stack application example.

作为额外资源,深度搜索智能体开发工具包 (ADK) 快速入门提供了 Google 搜索基础的实用用法,作为全栈应用程序示例。

Google Search Grounding Quickstart

Google 搜索基础快速入门

This quickstart guides you through creating an ADK agent with Google Search grounding feature. This quickstart assumes a local IDE (VS Code or PyCharm, etc.) with Python 3.10+ and terminal access.

此快速入门将指导您创建具有 Google 搜索基础功能的 ADK 智能体。此快速入门假设您使用带有 Python 3.10+ 和终端访问权限的本地 IDE (VS Code 或 PyCharm 等)。

1. Set up Environment & Install ADK

1. 设置环境并安装 ADK

Below are the steps for setting up your environment and installing the ADK for both Python and TypeScript projects.

以下是设置环境并为 Python 和 TypeScript 项目安装 ADK 的步骤。

Create & Activate Virtual Environment:

创建并激活虚拟环境:

# Create
# 创建
python -m venv .venv

# Activate (each new terminal)
# 激活 (每个新终端)
# macOS/Linux: source .venv/bin/activate
# Windows CMD: .venv\Scripts\activate.bat
# Windows PowerShell: .venv\Scripts\Activate.ps1

Install ADK:

安装 ADK:

pip install google-adk

Create a new Node.js project: 创建一个新的 Node.js 项目:

npm init -y

Install ADK:

安装 ADK:

npm install @google/adk

2. Create Agent Project

2. 创建智能体项目

Under a project directory, run the following commands:

在项目目录下,运行以下命令:

# Step 1: Create a new directory for your agent
# 步骤 1: 为您的智能体创建一个新目录
mkdir google_search_agent

# Step 2: Create __init__.py for the agent
# 步骤 2: 为智能体创建 __init__.py
echo "from . import agent" > google_search_agent/__init__.py

# Step 3: Create an agent.py (the agent definition) and .env (Gemini authentication config)
# 步骤 3: 创建 agent.py (智能体定义) 和 .env (Gemini 身份验证配置)
touch google_search_agent/agent.py .env
# Step 1: Create a new directory for your agent
# 步骤 1: 为您的智能体创建一个新目录
mkdir google_search_agent

# Step 2: Create __init__.py for the agent
# 步骤 2: 为智能体创建 __init__.py
echo "from . import agent" > google_search_agent/__init__.py

# Step 3: Create an agent.py (the agent definition) and .env (Gemini authentication config)
# 步骤 3: 创建 agent.py (智能体定义) 和 .env (Gemini 身份验证配置)
type nul > google_search_agent\agent.py
type nul > google_search_agent\.env

Edit agent.py or agent.ts

编辑 agent.pyagent.ts

Copy and paste the following code into agent.py or agent.ts:

将以下代码复制并粘贴到 agent.pyagent.ts:

google_search_agent/agent.py
from google.adk.agents import Agent
from google.adk.tools import google_search

root_agent = Agent(
    name="google_search_agent",
    model="gemini-2.5-flash",
    instruction="Answer questions using Google Search when needed. Always cite sources.",
    description="Professional search assistant with Google Search capabilities",
    tools=[google_search]
)
google_search_agent/agent.ts
import { LlmAgent, GOOGLE_SEARCH } from '@google/adk';

const rootAgent = new LlmAgent({
    name: "google_search_agent",
    model: "gemini-2.5-flash",
    instruction: "Answer questions using Google Search when needed. Always cite sources.",
    description: "Professional search assistant with Google Search capabilities",
    tools: [GOOGLE_SEARCH],
});

Now you would have the following directory structure:

现在您将拥有以下目录结构:

my_project/
    google_search_agent/
        __init__.py
        agent.py
    .env
my_project/
    google_search_agent/
        agent.ts
    package.json
    tsconfig.json
    .env

3. Choose a platform

3. 选择平台

To run the agent, you need to select a platform that the agent will use for calling the Gemini model. Choose one from Google AI Studio or Vertex AI:

要运行智能体,您需要选择智能体将用于调用 Gemini 模型的平台。从 Google AI Studio 或 Vertex AI 中选择一个:

  1. Get an API key from Google AI Studio. 从 Google AI Studio 获取 API 密钥。
  2. When using Python, open the .env file and copy-paste the following code. 使用 Python 时,打开 .env 文件并复制粘贴以下代码。

    .env
    GOOGLE_GENAI_USE_VERTEXAI=FALSE
    GOOGLE_API_KEY=PASTE_YOUR_ACTUAL_API_KEY_HERE
    
  3. Replace PASTE_YOUR_ACTUAL_API_KEY_HERE with your actual API KEY. 将 PASTE_YOUR_ACTUAL_API_KEY_HERE 替换为您的实际 API KEY

  1. You need an existing Google Cloud account and a project. 您需要一个现有的 Google Cloud 帐户和一个项目。
  2. When using Python, open the .env file and copy-paste the following code and update the project ID and location. 使用 Python 时,打开 .env 文件并复制粘贴以下代码并更新项目 ID 和位置。

    .env
    GOOGLE_GENAI_USE_VERTEXAI=TRUE
    GOOGLE_CLOUD_PROJECT=YOUR_PROJECT_ID
    GOOGLE_CLOUD_LOCATION=LOCATION
    

4. Run Your Agent

4. 运行您的智能体

There are multiple ways to interact with your agent:

有多种方法可以与您的智能体交互:

Run the following command to launch the dev UI.

运行以下命令以启动 开发 UI

adk web

Note for Windows users

!!!"Windows 用户注意"

When hitting the `_make_subprocess_transport NotImplementedError`, consider using `adk web --no-reload` instead.

当遇到 `_make_subprocess_transport NotImplementedError` 时,考虑使用 `adk web --no-reload` 代替。

Step 1: Open the URL provided (usually http://localhost:8000 or http://127.0.0.1:8000) directly in your browser.

步骤 1: 直接在浏览器中打开提供的 URL (通常是 http://localhost:8000http://127.0.0.1:8000)。

Step 2. In the top-left corner of the UI, you can select your agent in the dropdown. Select "google_search_agent".

步骤 2. 在 UI 的左上角,您可以在下拉菜单中选择您的智能体。选择 "google_search_agent"。

Troubleshooting

!!!注意"故障排除"

If you do not see "google_search_agent" in the dropdown menu, make sure you
are running `adk web` in the **parent folder** of your agent folder
(i.e. the parent folder of google_search_agent).

如果您在下拉菜单中没有看到 "google_search_agent",请确保您在智能体文件夹的 **父文件夹** 中运行 `adk web` (即 google_search_agent 的父文件夹)。

Step 3. Now you can chat with your agent using the textbox.

步骤 3. 现在您可以使用文本框与智能体聊天。

Run the following command, to chat with your Weather agent.

运行以下命令,与您的天气智能体聊天。

adk run google_search_agent
To exit, use Cmd/Ctrl+C. 要退出,请使用 Cmd/Ctrl+C。

Example prompts to try

示例提示词

With those questions, you can confirm that the agent is actually calling Google Search to get the latest weather and time.

通过这些问题,您可以确认智能体确实在调用 Google 搜索以获取最新的天气和时间。

  • What is the weather in New York?
  • 纽约的天气如何?
  • What is the time in New York?
  • 纽约的时间是几点?
  • What is the weather in Paris?
  • 巴黎的天气如何?
  • What is the time in Paris?
  • 巴黎的时间是几点?

Try the agent with adk web

You've successfully created and interacted with your Google Search agent using ADK!

您已成功使用 ADK 创建并与您的 Google 搜索智能体进行交互!

How grounding with Google Search works

Google 搜索基础的工作原理

Grounding is the process that connects your agent to real-time information from the web, allowing it to generate more accurate and current responses. When a user's prompt requires information that the model was not trained on, or that is time-sensitive, the agent's underlying Large Language Model intelligently decides to invoke the google_search tool to find the relevant facts

基础是将您的智能体连接到网络实时信息的过程,使其能够生成更准确和当前的响应。当用户的提示词需要模型未训练的信息,或具有时间敏感性时,智能体的底层大型语言模型智能地决定调用 google_search 工具以查找相关事实

Data Flow Diagram

数据流图

This diagram illustrates the step-by-step process of how a user query results in a grounded response.

此图说明了用户查询如何导致基础响应的逐步过程。

Detailed Description

详细说明

The grounding agent uses the data flow described in the diagram to retrieve, process, and incorporate external information into the final answer presented to the user.

基础智能体使用图中描述的数据流来检索、处理和将外部信息纳入呈现给用户的最终答案中。

  1. User Query: An end-user interacts with your agent by asking a question or giving a command.
  2. 用户查询: 最终用户通过提问或给出命令与您的智能体交互。
  3. ADK Orchestration : The Agent Development Kit orchestrates the agent's behavior and passes the user's message to the core of your agent.
  4. ADK 编排: 智能体开发工具包编排智能体的行为,并将用户的消息传递到智能体的核心。
  5. LLM Analysis and Tool-Calling : The agent's LLM (e.g., a Gemini model) analyzes the prompt. If it determines that external, up-to-date information is required, it triggers the grounding mechanism by calling the google_search tool. This is ideal for answering queries about recent news, weather, or facts not present in the model's training data.
  6. LLM 分析和工具调用: 智能体的 LLM (例如 Gemini 模型) 分析提示词。如果它确定需要外部、最新的信息,它将通过调用 google_search 工具来触发基础机制。这非常适合回答有关最新新闻、天气或模型训练数据中不存在的事实的查询。
  7. Grounding Service Interaction : The google_search tool interacts with an internal grounding service that formulates and sends one or more queries to the Google Search Index.
  8. 基础服务交互: google_search 工具与内部基础服务交互,该服务制定并向 Google 搜索索引发送一个或多个查询。
  9. Context Injection: The grounding service retrieves the relevant web pages and snippets. It then integrates these search results into the model's context before the final response is generated. This crucial step allows the model to "reason" over factual, real-time data.
  10. 上下文注入: 基础服务检索相关的网页和片段。然后,在生成最终响应之前,将这些搜索结果集成到模型的上下文中。这一关键步骤允许模型对事实的实时数据进行"推理"。
  11. Grounded Response Generation: The LLM, now informed by the fresh search results, generates a response that incorporates the retrieved information.
  12. 基础响应生成: LLM 现在由新的搜索结果通知,生成包含检索信息的响应。
  13. Response Presentation with Sources : The ADK receives the final grounded response, which includes the necessary source URLs and groundingMetadata, and presents it to the user with attribution. This allows end-users to verify the information and builds trust in the agent's answers.
  14. 带有来源的响应呈现: ADK 接收最终的基础响应,其中包括必要的源 URL 和 groundingMetadata,并以归属的形式呈现给用户。这允许最终用户验证信息,并建立对智能体答案的信任。

Understanding grounding with Google Search response

理解 Google 搜索基础响应

When the agent uses Google Search to ground a response, it returns a detailed set of information that includes not only the final text answer but also the sources it used to generate that answer. This metadata is crucial for verifying the response and for providing attribution to the original sources.

当智能体使用 Google 搜索来建立响应的基础时,它返回一组详细信息,不仅包括最终文本答案,还包括它用于生成该答案的来源。此元数据对于验证响应和为原始来源提供归属至关重要。

Example of a Grounded Response

基础响应示例

The following is an example of the content object returned by the model after a grounded query.

以下是模型在基础查询后返回的内容对象示例。

Final Answer Text: 最终答案文本:

"Yes, Inter Miami won their last game in the FIFA Club World Cup. They defeated FC Porto 2-1 in their second group stage match. Their first game in the tournament was a 0-0 draw against Al Ahly FC. Inter Miami is scheduled to play their third group stage match against Palmeiras on Monday, June 23, 2025."

Grounding Metadata Snippet: 基础元数据片段:

"groundingMetadata": {
  "groundingChunks": [
    { "web": { "title": "mlssoccer.com", "uri": "..." } },
    { "web": { "title": "intermiamicf.com", "uri": "..." } },
    { "web": { "title": "mlssoccer.com", "uri": "..." } }
  ],
  "groundingSupports": [
    {
      "groundingChunkIndices": [0, 1],
      "segment": {
        "startIndex": 65,
        "endIndex": 126,
        "text": "They defeated FC Porto 2-1 in their second group stage match."
      }
    },
    {
      "groundingChunkIndices": [1],
      "segment": {
        "startIndex": 127,
        "endIndex": 196,
        "text": "Their first game in the tournament was a 0-0 draw against Al Ahly FC."
      }
    },
    {
      "groundingChunkIndices": [0, 2],
      "segment": {
        "startIndex": 197,
        "endIndex": 303,
        "text": "Inter Miami is scheduled to play their third group stage match against Palmeiras on Monday, June 23, 2025."
      }
    }
  ],
  "searchEntryPoint": { ... }
}

How to Interpret the Response

如何解释响应

The metadata provides a link between the text generated by the model and the sources that support it. Here is a step-by-step breakdown:

元数据提供了模型生成的文本与其支持来源之间的链接。以下是逐步分解:

  1. groundingChunks: This is a list of the web pages the model consulted. Each chunk contains the title of the webpage and a uri that links to the source.
  2. groundingChunks: 这是模型咨询的网页列表。每个块包含网页的标题和链接到源的 uri。
  3. groundingSupports: This list connects specific sentences in the final answer back to the groundingChunks.
  4. groundingSupports: 此列表将最终答案中的特定句子连接回 groundingChunks。
  5. segment: This object identifies a specific portion of the final text answer, defined by its startIndex, endIndex, and the text itself.
    • segment: 此对象标识最终文本答案的特定部分,由其 startIndex、endIndex 和文本本身定义。
  6. groundingChunkIndices: This array contains the index numbers that correspond to the sources listed in the groundingChunks. For example, the sentence "They defeated FC Porto 2-1..." is supported by information from groundingChunks at index 0 and 1 (both from mlssoccer.com and intermiamicf.com).
    • groundingChunkIndices: 此数组包含对应于 groundingChunks 中列出的来源的索引号。例如,句子 "They defeated FC Porto 2-1..." 由索引 0 和 1 的 groundingChunks 中的信息支持 (两者都来自 mlssoccer.com 和 intermiamicf.com)。

如何显示 Google 搜索基础响应

A critical part of using grounding is to correctly display the information, including citations and search suggestions, to the end-user. This builds trust and allows users to verify the information.

使用基础的一个关键部分是向最终用户正确显示信息,包括引用和搜索建议。这建立了信任并允许用户验证信息。

Responnses from Google Search

Displaying Search Suggestions

显示搜索建议

The searchEntryPoint object in the groundingMetadata contains pre-formatted HTML for displaying search query suggestions. As seen in the example image, these are typically rendered as clickable chips that allow the user to explore related topics.

groundingMetadata 中的 searchEntryPoint 对象包含用于显示搜索查询建议的预格式化 HTML。如示例图像所示,这些通常呈现为可点击的芯片,允许用户探索相关主题。

Rendered HTML from searchEntryPoint: The metadata provides the necessary HTML and CSS to render the search suggestions bar, which includes the Google logo and chips for related queries like "When is the next FIFA Club World Cup" and "Inter Miami FIFA Club World Cup history". Integrating this HTML directly into your application's front end will display the suggestions as intended.

从 searchEntryPoint 呈现的 HTML: 元数据提供了呈现搜索建议栏所需的 HTML 和 CSS,其中包括 Google 徽标和相关查询的芯片,如 "When is the next FIFA Club World Cup" 和 "Inter Miami FIFA Club World Cup history"。将此 HTML 直接集成到您应用程序的前端将按预期显示建议。

For more information, consult using Google Search Suggestions in Vertex AI documentation.

有关更多信息,请参阅 Vertex AI 文档中的使用 Google 搜索建议

Summary

总结

Google Search Grounding transforms AI agents from static knowledge repositories into dynamic, web-connected assistants capable of providing real-time, accurate information. By integrating this feature into your ADK agents, you enable them to:

Google 搜索基础将 AI 智能体从静态知识存储库转变为能够提供实时、准确信息的动态、网络连接助手。通过将此功能集成到您的 ADK 智能体中,您使它们能够:

  • Access current information beyond their training data
  • 访问超出其训练数据的当前信息
  • Provide source attribution for transparency and trust
  • 提供来源归属以提高透明度和信任
  • Deliver comprehensive answers with verifiable facts
  • 提供带有可验证事实的全面答案
  • Enhance user experience with relevant search suggestions
  • 通过相关搜索建议增强用户体验

The grounding process seamlessly connects user queries to Google's vast search index, enriching responses with up-to-date context while maintaining the conversational flow. With proper implementation and display of grounded responses, your agents become powerful tools for information discovery and decision-making.

基础过程将用户查询无缝连接到 Google 庞大的搜索索引,在保持对话流程的同时,用最新的上下文丰富响应。通过正确实施和显示基础响应,您的智能体将成为信息发现和决策的强大工具。