大家好,歡迎來到鐵人賽第十四天!今天,我們寫程式!
在昨天的理論鋪墊後,我們知道 Agent Development Kit(adk)
是一個功能全面、對開發者友善的套件。今天,我們就要來實際感受它的簡潔與強大。我們將一步步完成從環境設定到成功發送 tools/list
請求的完整流程。
打開你的終端機和程式碼編輯器,讓我們開始吧!
在開始安裝任何東西之前,建立一個乾淨、獨立的 Python 開發環境是專業開發的第一步。我們將使用 Python 內建的 venv
來建立一個虛擬環境。
前提: 請確保你的電腦已安裝 Python 3.9 或更新版本。
第一步:建立並啟用虛擬環境
打開你的終端機 (Terminal 或 PowerShell),進入你的專案資料夾,然後依序輸入以下指令:
# 1. 建立一個名為 "venv" 的虛擬環境資料夾
python -m venv venv
# 2. 啟用虛擬環境
# Windows 系統:
venv\Scripts\activate
# macOS / Linux 系統:
source venv/bin/activate
當你看到終端機提示符前面出現 (venv)
的字樣時,就代表你已經成功進入了這個獨立的開發環境。
為什麼要用虛擬環境?
它可以將這個專案所安裝的函式庫,與你電腦上其他 Python 專案完全隔離,避免版本衝突的惡夢。
google-adk
函式庫在虛擬環境啟用後,安裝 google-adk
就只是一行指令的事。
pip install google-adk
pip
會自動下載並安裝 google-adk
及其所有相依套件。
我們將採用一個標準的 Python 套件結構。請打開你的終端機,在你想放置專案的地方,依序執行以下指令:
# 1. 建立最外層的專案資料夾
mkdir adk_ithelp
cd adk_ithelp
# 2. 建立我們主要的 Python 套件資料夾
mkdir multi_tool_agent
# 3. 建立必要的 Python 檔案
# macOS / Linux
touch multi_tool_agent/__init__.py multi_tool_agent/agent.py multi_tool_agent/.env
# Windows (PowerShell)
New-Item -ItemType File multi_tool_agent/__init__.py, multi_tool_agent/agent.py, .env
完成後,你的資料夾結構應該會是:
打開一個名為 agent.py
的檔案,並將範例程式碼貼上:
import datetime
from zoneinfo import ZoneInfo
from google.adk.agents import Agent
def get_weather(city: str) -> dict:
"""Retrieves the current weather report for a specified city.
Args:
city (str): The name of the city for which to retrieve the weather report.
Returns:
dict: status and result or error msg.
"""
if city.lower() == "new york":
return {
"status": "success",
"report": (
"The weather in New York is sunny with a temperature of 25 degrees"
" Celsius (77 degrees Fahrenheit)."
),
}
else:
return {
"status": "error",
"error_message": f"Weather information for '{city}' is not available.",
}
def get_current_time(city: str) -> dict:
"""Returns the current time in a specified city.
Args:
city (str): The name of the city for which to retrieve the current time.
Returns:
dict: status and result or error msg.
"""
if city.lower() == "new york":
tz_identifier = "America/New_York"
else:
return {
"status": "error",
"error_message": (
f"Sorry, I don't have timezone information for {city}."
),
}
tz = ZoneInfo(tz_identifier)
now = datetime.datetime.now(tz)
report = (
f'The current time in {city} is {now.strftime("%Y-%m-%d %H:%M:%S %Z%z")}'
)
return {"status": "success", "report": report}
root_agent = Agent(
name="weather_time_agent",
model="gemini-2.0-flash",
description=(
"Agent to answer questions about the time and weather in a city."
),
instruction=(
"You are a helpful agent who can answer user questions about the time and weather in a city."
),
tools=[get_weather, get_current_time],
)
簡單來說,它做了三件事:
整個程式碼可以分成三個主要部分:
這裡定義了兩個 Python 函式,它們是 AI 代理可以使用的「工具」。
get_weather(city: str)
"new york"
(不分大小寫)。# 範例:查詢天氣
get_weather("New York")
# 回傳: {'status': 'success', 'report': 'The weather in New York is sunny...'}
get_weather("Taipei")
# 回傳: {'status': 'error', 'error_message': "Weather information for 'Taipei' is not available."}
get_current_time(city: str)
"new york"
。zoneinfo
函式庫來取得「America/New_York」時區的現在時間,並格式化後回傳。# 範例:查詢時間
get_current_time("New York")
# 回傳: {'status': 'success', 'report': 'The current time in New York is 2025-09-07 23:18:41 EST-0500'}
# (日期時間會是當下執行時的紐約時間)
這部分是程式碼的核心,它使用 google.adk.agents
函式庫來建立一個 AI 代理。
root_agent = Agent(
name="weather_time_agent",
model="gemini-2.0-flash",
description="Agent to answer questions about the time and weather in a city.",
instruction="You are a helpful agent who can answer user questions about the time and weather in a city.",
tools=[get_weather, get_current_time],
)
name
: 給這個代理取一個名字,方便識別。model
: 指定代理背後使用的 AI 模型,這裡是 Google 的 gemini-2.0-flash
。description
: 簡短描述這個代理的功能,幫助模型或其他系統了解它的用途。instruction
: 給予 AI 代理的系統指令或角色設定。這會影響它回答問題的語氣和風格。這裡指示它要扮演一個樂於助人的角色。tools
: 最關鍵的部分。這裡把前面定義的 get_weather
和 get_current_time
這兩個函式註冊為該代理可以使用的工具。當你對這個 root_agent
提出問題時(例如:「紐約現在幾點而且天氣如何?」),整個運作流程如下:
gemini-2.0-flash
模型會分析你的問題,理解你想要查詢「紐約」的「時間」和「天氣」。tools
列表 ([get_weather, get_current_time]
),判斷需要使用這兩個工具來完成任務。get_current_time("new york")
。get_weather("new york")
。gemini-2.0-flash
模型會根據收到的資訊和它的 instruction
("You are a helpful agent..."
),用自然、流暢的語言生成最終的答案給你。例如,它可能會回答:「紐約的現在時間是 2025-09-07 23:18:41,天氣晴朗,溫度為攝氏 25 度(華氏 77 度)。」
adk_ithelp
。source venv/bin/activate
或 venv\Scripts\activate
)。adk web
如上圖所示,就已經成功啟動 dev UI了,可在瀏覽器直接開啟 http://127.0.0.1:8000
如上圖,左側先選擇 multi_tool_agent
,就可以跟你的 agent 溝通囉!
如上圖,可以成功使用剛剛撰寫的工具,可以取得紐約天氣和取得紐約時間
可在終端機打上下方指令
adk run multi_tool_agent
成果如下圖:
恭喜你!今天我們正式踏入了 Python MCP 的世界。這是一個意義非凡的里程碑!
讓我們回顧一下今天滿滿的收穫:
venv
建立虛擬環境,並搭建了一個清晰、可擴展的專案框架。google-adk
: 我們成功安裝了核心的 google-adk
函式庫,這是我們後續所有開發的基礎。get_weather
, get_current_time
),透過 Agent
的 tools
參數,輕鬆地變成了 AI Agent 可以呼叫的能力。adk web
這個強大的內建工具,快速啟動一個網頁介面來與我們親手打造的 AI Agent 進行互動與測試。最重要的是,我們親身體會到了 google-adk
的設計哲學——高度抽象與開發者友善。我們幾乎沒有去處理任何複雜的伺服器設定或協議細節,只是專注在編寫工具本身的邏輯,ADK 就為我們搞定了剩下的一切。
我們現在擁有了一個堅實的基礎和一個能運作的 Agent。雖然它目前只有寫兩個寫死的回覆,但這已經證明了整個流程是暢通的。
明天,我們將在這個專案的基礎上繼續擴展,改造我們的工具函式,讓它不再是寫死的假資料,而是去串接真實的外部 API,賦予我們的 AI Agent 獲取即時資訊的超能力!