使用 ADK 和 Google 地图实景关联功能构建行程规划智能体

1. 简介

在此 Codelab 中,您将使用智能体开发套件 (ADK) 构建行程规划智能体,并使用 Google 地图为其提供接地信息。您将提示智能体生成风景优美的路线和餐厅推荐,利用 Google 地图中的真实世界数据。

您将执行的操作

  • 使用 Agent Starter Pack 初始化智能体项目
  • 配置智能体以使用 Google 地图接地 工具
  • 使用 Web 界面在本地测试生成的智能体

所需条件

  • 网络浏览器,例如 Chrome
  • 启用了结算功能的 Google Cloud 项目

此 Codelab 适用于对 Python 和 Google Cloud 有一定了解但并非专家的中级开发者。

2. 准备工作

创建 Google Cloud 项目

  1. Google Cloud 控制台 的项目选择器页面上,选择或创建一个 Google Cloud 项目
  2. 确保您的云项目已启用结算功能。了解如何检查项目是否已启用结算功能

启动 Cloud Shell

  1. 核实身份验证:
gcloud auth list
  1. 确认您的项目:
gcloud config get project
  1. 根据需要进行设置:
export PROJECT_ID=<YOUR_PROJECT_ID>
gcloud config set project $PROJECT_ID

启用 API

运行以下命令以启用所有必需的 API:

gcloud services enable \
  aiplatform.googleapis.com

3. 安装 Agent Starter Pack

开始 ADK 项目的最简单方法是使用 Agent Starter Pack。Google Cloud Agent Starter Pack 是一款开源命令行界面 (CLI) 工具,旨在加快在 Google Cloud 上开发和部署可用于生产用途的生成式 AI 智能体的速度。

  1. 确保已安装 uv,然后运行 create 命令以初始化新的智能体项目:
uvx agent-starter-pack create
  1. 系统提示时,请提供以下选项,以配置项目以使用 React 前端进行本地开发:
  • 智能体模板adk(简单 React 智能体)
  • 部署: none(暂时停用 Cloud 部署)
  • 区域: us-central1

这将生成一个项目目录结构,其中包含您的主要智能体逻辑、测试和 GEMINI.md 指南。进入新目录:

cd my-agent

4. 配置接地

Agent Starter Pack 会生成一个 GEMINI.md 文件,用于指示 AI 辅助编码工具如何管理您的项目。我们将更新此文件,以包含 Google 地图接地文档。

  1. 在编辑器中打开 GEMINI.md
  2. ## Reference Documentation 部分下添加以下参考链接:
- **Google Maps Grounding**: https://docs.cloud.google.com/vertex-ai/generative-ai/docs/grounding/grounding-with-google-maps

此上下文将帮助任何 AI 编码助理了解接地功能。

5. 更新智能体

现在,我们将配置智能体以充当行程规划工具,并使用 Google 地图接地工具。

  1. 打开文件 app/agent.py
  2. app/agent.py 的全部内容替换为以下代码:
"""Agent application for the itinerary planner codelab."""

import os
import google.auth
from google.adk.agents import Agent
from google.adk.apps import App
from google.adk.models import Gemini
from google.adk.tools import google_maps_grounding
from google.genai import types

# Authenticate and set environment variables
_, project_id = google.auth.default()
os.environ["GOOGLE_CLOUD_PROJECT"] = project_id
os.environ["GOOGLE_CLOUD_LOCATION"] = "global"
os.environ["GOOGLE_GENAI_USE_VERTEXAI"] = "True"

# Define the root agent
root_agent = Agent(
    name="itinerary_planner_agent",
    model=Gemini(
        model="gemini-2.5-flash",
        retry_options=types.HttpRetryOptions(attempts=3),
    ),
    instruction=(
        "You are an itinerary planner agent. Help users plan their trips by"
        " recommending restaurants and scenic routes. Use the"
        " google_maps_grounding tool to get both restaurant recommendations and"
        " route recommendations based on user preferences. When calling for"
        " restaurant recommendation, prompt the tool to tell you about the vibe"
        " of the place. When calling for routes with multiple legs, describe"
        " each of those legs with a brief sentence. Always describe the key"
        " landmarks along the route in one brief sentence."
    ),
    # Add the Google Maps Grounding tool to the agent
    tools=[google_maps_grounding],
)

app = App(
    root_agent=root_agent,
    name="app",
)

此代码配置了一个基于 gemini-2.5-flash 的智能体,该智能体使用 google_maps_grounding 工具检索有关地点和路线的最新信息。

如需查看所有可用模型,请参阅 Vertex AI 文档

6. 运行智能体

智能体逻辑就绪后,请尝试在本地 Web 界面中对其进行测试。

  1. my-agent 目录的根目录下,运行以下命令以启动 Web 应用:
uv run adk web

或者,如果使用虚拟环境:

adk web
  1. 在浏览器中打开终端输出中提供的网址。
  2. 通过向智能体提问来测试智能体。例如:
  • “在旧金山规划 1 日游行程,包括一家不错的意大利餐厅。”
  • “我要去东京,你能给我一份行程,其中包含有趣的古迹和一家氛围舒适且评价很高的拉面店吗?”

您应该会看到类似于详细行程的输出,其中包含直接从 Google 地图提取的真实评价和路线说明。

智能体行程输出示例

7. 在代码中验证接地

如需以编程方式确认智能体是否成功使用地图接地,您可以检查响应事件以获取地图专用元数据。

当您运行智能体(例如,在测试脚本中)时,智能体会生成包含 grounding_metadata 的事件。您可以遍历此元数据中的 grounding_chunks 并检查 maps 属性。

以下示例演示了如何检查 maps 属性,类似于您在自动化测试中可能使用的内容:

async for event in runner.run_async(
    user_id="test_user",
    session_id=session.id,
    new_message=content,
):
    if event.grounding_metadata:
        if event.grounding_metadata.grounding_chunks:
            for chunk in event.grounding_metadata.grounding_chunks:
                # Check for the maps attribute to confirm maps grounding
                if hasattr(chunk, "maps") and chunk.maps:
                    print("SUCCESS: Maps grounding chunks detected in the response!")

8. 提取编码多段线

除了验证是否发生了接地之外,您可能还想提取特定数据,例如路线路径。当地图接地工具返回路线信息时,通常会包含一个“编码多段线”,该多段线可用于在地图前端上呈现路线。

您可以通过检查 grounding_chunksmaps 属性中的文本来找到此多段线。以下示例展示了如何检测它:

async for event in runner.run_async(
    user_id="test_user",
    session_id=session.id,
    new_message=content,
):
    if event.grounding_metadata:
        if event.grounding_metadata.grounding_chunks:
            for chunk in event.grounding_metadata.grounding_chunks:
                # Extract the encoded polyline from the maps chunk text
                if (
                    hasattr(chunk, "maps")
                    and chunk.maps
                    and hasattr(chunk.maps, "text")
                    and chunk.maps.text
                    and "Encoded Polyline" in chunk.maps.text
                ):
                    print("SUCCESS: Encoded Polyline detected in the response!")

9. 清理

为避免系统向您的 Google Cloud 账号持续收取费用,请删除在此 Codelab 中创建的资源。

  1. 如果您为此 Codelab 创建了专用项目,请将其完全删除:
gcloud projects delete $PROJECT_ID

如果您使用的是现有项目并想保留它,则无需删除任何特定资源,因为智能体是在本地运行的,并且使用的 API 是无服务器的。

10. 恭喜

恭喜!您已成功构建行程规划智能体,并使用 Google 地图洞见为其提供接地信息。

您学到的内容

  • 如何使用 Agent Starter Pack 搭建新智能体
  • 如何将接地工具添加到 ADK 智能体定义
  • 如何使用内置 Web 运行程序测试 ADK 智能体

后续步骤

  • 探索其他 ADK 工具和集成模式

参考文档