使用 ADK 建構 AI 代理:運用工具提升效能

1. 事前準備

歡迎來到「使用 ADK 建構 AI 代理」系列文章的第二部分!在本實作程式碼研究室系列中,您將踏上精彩旅程,使用 Google 的 Agent Development Kit (ADK) 建立專屬的智慧型 AI 代理。

本程式碼研究室會接續 ADK 基礎程式碼研究室的內容。我們假設您已完成必要設定,並使用 ADK 成功建構個人助理代理程式,因此不會在此重複這些設定步驟。

完成本程式碼研究室後,您將為個人助理代理程式提供各種用途的工具,並在後續系列課程中,將其轉換為複雜的多代理程式系統 (MAS),朝擴充功能邁進一步。

必要條件

課程內容

  • 您可以建構自訂 Python 函式做為工具,賦予代理程式新技能。
  • 使用 Google 搜尋等內建工具,讓代理程式存取即時資訊。
  • 建立專門處理複雜工作的子代理,建構多工具代理。
  • 整合 LangChain 等熱門 AI 架構的工具,快速擴充功能。

軟硬體需求

  • 可正常運作的電腦和穩定的 Wi-Fi
  • 瀏覽器 (例如 Chrome),用來存取 Google Cloud Console
  • 啟用計費功能的 Google Cloud 專案
  • 好奇心和學習意願

2. 簡介

ADK 基礎程式碼研究室中,您已使用強大的 LLM 腦部建構個人助理代理程式。不過,您可能已發現這項工具的限制:無法存取訓練日期之後建立的資訊,也無法與外部服務互動。就像是聰明又博學的助理被關在圖書館裡,而且沒有手機或網路。

如要讓代理程式真正實用,我們需要提供工具

工具就像是讓這位優秀的助理存取外部世界:計算機、網路瀏覽器或特定公司資料庫。在 ADK 中,工具是一段模組化程式碼,可讓代理程式執行特定動作,例如查詢即時資料或呼叫外部 API。使用工具可讓 Gemini 的功能遠遠超出簡單對話。

ADK 提供三類工具:

  1. 函式工具:您開發的自訂工具,可滿足應用程式的獨特需求,例如預先定義的函式和代理程式。
  2. 內建工具:架構提供的現成工具,可用於常見作業,例如 Google 搜尋和程式碼執行。
  3. 第三方工具:熱門外部程式庫,例如 Serper,以及 LangChain 和 CrewAI 的工具。

如要進一步瞭解如何搭配 ADK 代理程式使用工具,請參閱官方說明文件。在本程式碼研究室中,我們將新增工具,將簡單的代理程式轉換為功能強大的個人旅遊助理。我們馬上開始!

3. 新增函式工具

延續上一個工作階段,您應該已透過網頁介面執行個人助理代理程式。

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 維基百科工具的實作內容。

正在建立「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 UI 中的事件檢查器。按一下「事件」分頁標籤,然後按一下最新的 functionCall 事件。

e3f388b64d08e666.png

檢查器會顯示所有可用工具的清單,並醒目顯示代理執行的工具代碼。

135c9a1068d6c58f.png

6. 清除

由於本程式碼研究室不涉及任何長時間執行的產品,因此只要在終端機中按下 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,從建構單一代理程式邁出第一步,進而協調簡單但功能強大的多代理程式系統。

您現在已做好萬全準備,可以參加本系列下一個程式碼研究室,深入瞭解如何協調多個代理程式和工作流程。到時見!