使用 ADK 构建 AI 智能体:通过工具赋能

1. 准备工作

欢迎观看“使用 ADK 构建 AI 智能体”系列的第二部分!在此实践 Codelab 系列中,您将踏上激动人心的旅程,使用 Google 的 Agent Development Kit (ADK) 创建自己的智能 AI 代理。

此 Codelab 从 ADK 基础知识 Codelab 结束的地方开始。我们将假定您此时已完成必要的设置,并使用 ADK 成功构建了个人助理代理,因此我们不会在此处重复这些设置步骤。

在此 Codelab 结束时,您将为个人助理代理配备各种用途的工具,从而更进一步,在后续部分中将其转变为复杂的多代理系统 (MAS)。

前提条件

学习内容

  • 通过构建自定义 Python 函数作为工具,为代理赋予新技能。
  • 使用 Google 搜索等内置工具将您的代理连接到实时信息。
  • 通过为复杂任务创建专用子代理来构建多工具代理。
  • 集成 LangChain 等热门 AI 框架中的工具,快速扩展功能。

所需条件

  • 一台可正常运行的计算机和稳定的 Wi-Fi 连接
  • 浏览器(例如 Chrome),用于访问 Google Cloud 控制台
  • 启用了结算功能的 Google Cloud 项目
  • 好奇心和学习热情

2. 简介

ADK 基础知识 Codelab 中,您构建了一个具有强大 LLM 大脑的个人助理智能体。不过,您可能已经注意到它的局限性:它无法访问训练日期之后创建的信息,也无法与外部服务互动。这就像一位才华横溢、博览群书的助理被锁在没有电话或互联网的图书馆里。

为了让我们的代理真正有用,我们需要为其提供工具

您可以将工具视为让这位出色的助理能够访问外部世界:计算器、网络浏览器或对特定公司数据库的访问权限。在 ADK 中,工具是一段模块化代码,可让代理执行特定操作,例如查找实时数据或调用外部 API。使用工具可让其功能远超简单的对话。

ADK 提供三类工具:

  1. 功能工具:您开发的自定义工具,用于满足应用的独特需求,例如预定义函数和代理。
  2. 内置工具:框架提供的可直接使用的工具,用于执行常见操作,例如 Google 搜索和代码执行。
  3. 第三方工具:热门的外部库,例如 Serper 以及 LangChain 和 CrewAI 中的工具。

如需详细了解如何将工具与 ADK 智能体搭配使用,请参阅官方文档。在此 Codelab 中,我们将添加一些工具,将简单的代理转变为功能强大的个人旅行助理。我们开始吧!

3. 添加函数工具

继续上一次会话,您应该已经通过 Web 界面运行了个人助理代理。

7b779b9601941a12.png

假设您正在为下个月的日本之旅做准备,需要查看当前的货币兑换汇率。询问代理:

What is the exchange rate from Singapore dollars to Japanese yen?

a8f38e3c404ada9c.png

您会看到,该代理无法检索实时汇率。这是因为代理目前无法访问互联网,也无法连接到外部系统。为解决此问题,我们将实现一个 Python 函数,用于通过 REST API 检索汇率,并将其作为函数工具集成到代理中。

首先,使用键盘快捷键 Ctrl + C(适用于 Windows/Linux)或 Cmd + C(适用于 macOS)终止正在运行的代理进程。

然后,创建一个名为 custom_functions.py 的 Python 文件。此文件将包含负责从外部 API 检索汇率数据的 Python 函数。

创建 custom_functions.py

import requests

# define a function to get exchange rate
def get_fx_rate(base: str, target: str):
        """
        Fetches the current exchange rate between two currencies.

        Args:
                base: The base currency (e.g., "SGD").
                target: The target currency (e.g., "JPY").

        Returns:
                The exchange rate information as a json response,
                or None if the rate could not be fetched.
        """
        base_url = "https://hexarate.paikama.co/api/rates/latest"
        api_url = f"{base_url}/{base}?target={target}"

        response = requests.get(api_url)
        if response.status_code == 200:
                return response.json()

现在,修改 agent.py 文件:导入 get_fx_rate 函数并将其分配为 FunctionTool

更新 agent.py

from google.adk.agents import Agent
from google.adk.tools import FunctionTool

from .custom_functions import get_fx_rate

root_agent = Agent(
    model='gemini-2.0-flash-001',
    name='root_agent',
    description='A helpful assistant for user questions.',
    instruction='Answer user questions to the best of your knowledge',
    tools=[FunctionTool(get_fx_rate)]
)

更改完成后,输入以下命令,重新启动代理:

uv run adk web

当代理启动后,再次提出相同的问题:

What is the exchange rate from Singapore dollars to Japanese yen?

这次,您应该会看到 get_fx_rate 工具提供的实际汇率。

4f671fe04f8421f5.png

您可以随时提出与货币兑换相关的任何问题。

4. 添加内置工具

现在,代理能够提供汇率,下一个任务是获取下个月的天气预报。向代理提出以下问题:

What is the weather forecast in Tokyo, Japan for next month?

96c175077957fdd0.png

您可能已经猜到,天气预报需要实时信息,而我们的代理没有这些信息。虽然我们可以为每项所需的实时数据编写新的 Python 函数,但添加越来越多的自定义工具很快就会使代理变得过于复杂且难以管理。

幸运的是,代理开发套件 (ADK) 提供了一套内置工具,包括可随时使用的 Google 搜索,从而简化了代理与外部世界的互动方式。我们来为代理添加 Google 搜索工具。为此,您需要按如下方式修改 agent.py 文件:

from google.adk.agents import Agent
from google.adk.tools import FunctionTool
from google.adk.tools import google_search

from .custom_functions import get_fx_rate

root_agent = Agent(
    model='gemini-2.0-flash-001',
    name='root_agent',
    description='A helpful assistant for user questions.',
    instruction='Answer user questions to the best of your knowledge',
    tools=[
        FunctionTool(get_fx_rate), 
        google_search,
    ]
)

修改完文件后,重启 adk web 实例。以防您忘记,

  1. 点击终端,然后按 Ctrl + C 或 Cmd + C 停止实例
  2. uv run adk web 以启动实例

您会遇到错误!

此错误是有意为之,旨在传达 ADK 的核心架构原则。为避免歧义并保持代理设计简洁,代理设计为仅使用一种基于搜索的主要工具。您不能简单地将 google_search 与同一代理中的其他复杂工具并列。

正确的方法是采用多智能体模式:我们创建一个新的专用智能体,其唯一任务是执行 Google 搜索。然后,我们将此搜索代理作为工具提供给我们的主要 personal_assistant

现在,创建一个名为 custom_agents.py 的 Python 文件。此文件将包含专用 google_search_agent 的代码。将以下代码复制到 custom_agents.py 文件中。

正在创建“custom_agents.py

from google.adk.agents import Agent
from google.adk.tools import google_search


# Create an agent with google search tool as a search specialist
google_search_agent = Agent(
    model='gemini-2.0-flash-001',
    name='google_search_agent',
    description='A search agent that uses google search to get latest information about current events, weather, or business hours.',
    instruction='Use google search to answer user questions about real-time, logistical information.',
    tools=[google_search],
)

创建文件后,更新 agent.py 文件,如下所示。

正在更新“agent.py

from google.adk.agents import Agent
from google.adk.tools import FunctionTool
from google.adk.tools import agent_tool

from .custom_functions import get_fx_rate
from .custom_agents import google_search_agent


root_agent = Agent(
    model='gemini-2.0-flash-001',
    name='root_agent',
    description='A helpful assistant for user questions.',
    tools=[
        FunctionTool(get_fx_rate), 
        agent_tool.AgentTool(agent=google_search_agent),
    ]
)

我们来分析一下代码中强大的新模式:

  • 新的专家代理:我们定义了一个全新的代理 google_search_agent。请注意其具体说明以及其唯一工具是 google_search。他是搜索专家。
  • agent_tool.AgentTool:这是 ADK 中的一个特殊封装容器。它会获取整个代理 (google_search_agent),并将其打包,使其看起来像一个标准工具,并像一个标准工具一样运行。
  • 更智能的**root_agent**:我们的 root_agent 现在有了一个新工具:agent_tool.AgentTool(agent=google_search_agent)。它不知道如何搜索网络,但知道自己有一个可以委托搜索任务的工具。

请注意,root_agent 中已不再显示指令字段。其指令现在由其可用的工具隐式定义。它已成为编排程序或路由器,其主要工作是理解用户的请求,并将其传递给正确的工具,即 get_fx_rate 函数或 google_search_agent。这种去中心化设计是构建复杂且可维护的代理系统的关键。

现在,重启 adk web 实例,然后再次向代理提出此问题:

What is the weather forecast in Tokyo, Japan for next month?

9771716f64132c54.png

代理现在使用 google_search_agent 获取最新信息

您也可以尝试提出当前汇率方面的问题。现在,代理应该能够针对相应问题使用合适的工具。

2a8e6525a9f5a4ee.png

您可以随意向代理提出需要实时信息的问题,并观察代理如何使用其可用的工具处理查询。

5. 添加第三方工具

我们的代理正在成为出色的旅行助理。它可以使用 get_fx_rate 工具处理货币兑换,并使用 google_search_agent 工具管理物流。但一次精彩的旅行不仅仅是后勤保障,还要了解目的地的文化和历史。

虽然 google_search_agent 工具可以根据搜索结果提供文化和历史信息,但您可能希望从维基百科等更可靠的来源获取此类信息。同样,您也可以创建自己的 Python 函数来从维基百科中抓取信息,但肯定有更好的方法。

幸运的是,ADK 的设计具有高度可扩展性,可让您无缝集成 CrewAI 和 LangChain 等其他 AI 代理框架中的工具。这种互操作性至关重要,因为它可以缩短开发时间,并让您能够重复使用现有工具。对于此用例,我们将利用 LangChain 中的维基百科工具。

首先,停止正在运行的代理进程(按 Ctrl + C 或 Cmd + C),然后将其他库安装到当前的 Python 虚拟环境中。

uv add langchain-community
uv add wikipedia

安装完成后。创建名为 third_party_tools.py 的文件。 此文件将包含 LangChain Wikipedia 工具的实现。

正在创建“third_party_tools.py

from langchain_community.tools import WikipediaQueryRun
from langchain_community.utilities import WikipediaAPIWrapper

# Configure the Wikipedia LangChain tool to act as our cultural guide
langchain_wikipedia_tool = WikipediaQueryRun(
    api_wrapper=WikipediaAPIWrapper(top_k_results=1, doc_content_chars_max=3000)
)

# Give the tool a more specific description for our agent
langchain_wikipedia_tool.description = (
    "Provides deep historical and cultural information on landmarks, concepts, and places."
    "Use this for 'tell me about' or 'what is the history of' type questions."
)

现在,更新 agent.py 文件。

正在更新“agent.py

from google.adk.agents import Agent
from google.adk.tools import FunctionTool
from google.adk.tools import agent_tool
from google.adk.tools import langchain_tool

from .custom_functions import get_fx_rate
from .custom_agents import google_search_agent
from .third_party_tools import langchain_wikipedia_tool


root_agent = Agent(
    model='gemini-2.0-flash-001',
    name='root_agent',
    description='A helpful assistant for user questions.',
    tools=[
        FunctionTool(get_fx_rate), 
        agent_tool.AgentTool(agent=google_search_agent),
        langchain_tool.LangchainTool(langchain_wikipedia_tool),
    ]
)

现在,重启 adk web 实例,然后再次向代理提出此问题:

Tell me about the history of Kyoto

862ec3546a8fbb5f.png

代理正确地将此查询识别为历史查询,并使用其新的 Wikipedia 工具。通过集成第三方工具并为其分配特定角色,您使代理变得更加智能,并且在旅行规划方面更加实用。

如需确切了解代理如何做出此选择,您可以使用 adk web 界面中的事件检查器。点击“活动”标签页,然后点击最新的 functionCall 活动。

e3f388b64d08e666.png

检查器会显示所有可用工具的列表,并突出显示代理执行的工具的 tool_code。

135c9a1068d6c58f.png

6. 清理

由于本 Codelab 不涉及任何长时间运行的产品,因此只需在终端中按 Ctrl + C 停止活跃的代理会话(例如终端中的 adk web 实例)即可。

删除代理项目文件夹和文件

如果您只想从 Cloud Shell 环境中移除代码,请使用以下命令:

cd ~
rm -rf ai-agents-adk

停用 Vertex AI API

如需停用之前启用的 Vertex AI API,请运行以下命令:

gcloud services disable aiplatform.googleapis.com

关闭整个 Google Cloud 项目

如果您希望完全关停 Google Cloud 项目,请参阅官方指南,了解详细说明。

7. 总结

恭喜!您已成功为个人助理代理赋予自定义功能和实时 Google 搜索访问权限。

更重要的是,您已经学习了构建功能强大的智能体的基本架构模式:将专业智能体用作工具。通过创建专用 google_search_agent 并将其提供给 root_agent,您已迈出从构建单个代理到编排简单而强大的多代理系统的第一步。

现在,您已为本系列中的下一个 Codelab 做好充分准备,在该 Codelab 中,我们将深入探讨如何编排多个代理和工作流。到时候见!