Google ADK Multi-Agent System Implementation

Overview / 概述

This project implements an intelligent agent system based on Google Agent Development Kit (ADK), specifically designed for querying and providing weather and time information for cities. The system supports both Chinese and English city names and obtains the latest information through external APIs.

此專案實現了一個基於Google Agent Development Kit (ADK)的智能代理系統,專門用於查詢和提供城市的天氣和時間資訊。系統支援中英文城市名稱,並通過外部API獲取最新資訊。

File Structure / 檔案結構

The project contains two main files:

  • agent.py - Main functionality implementation, including weather and time query functions and agent definitions
  • __init__.py - Package initialization file, making the package importable

專案包含兩個主要檔案:

  • agent.py - 主要功能實現,包含天氣和時間查詢函數以及代理定義
  • __init__.py - 套件初始化檔案,使套件可被導入

__init__.py Analysis / __init__.py 分析

This is an initialization file for a Python package, used to make the package correctly importable.

這是一個Python套件的初始化檔案,用於使套件可被正確導入。

#package的初始文件 from . import agent

This short file implements two key functions:

  1. Marks the directory as a Python package
  2. Imports the agent module from the same directory, making it available when the package is imported

This pattern allows users to access the functionality in the agent module directly through import packagename.

這個簡短的檔案實現了兩個關鍵功能:

  1. 標記目錄為Python套件
  2. 從同一目錄導入agent模組,使其在導入套件時可用

這種模式允許用戶通過import packagename的方式直接訪問agent模組中的功能。

agent.py Analysis / agent.py 分析

This is the main implementation file, containing weather and time query functions as well as the Google ADK agent definition.

這是主要實現檔案,包含了天氣和時間查詢功能以及Google ADK代理的定義。

Imports / 導入部分

import os import requests import datetime from zoneinfo import ZoneInfo from google.adk.agents import Agent from google.adk.models.lite_llm import LiteLlm

The imported modules include:

  • os - For accessing environment variables
  • requests - For sending HTTP requests to the weather API
  • datetime and ZoneInfo - For handling time and time zones
  • google.adk related modules - For creating and configuring the intelligent agent

導入的模組包括:

  • os - 用於訪問環境變數
  • requests - 用於發送HTTP請求至天氣API
  • datetimeZoneInfo - 用於處理時間和時區
  • google.adk 相關模組 - 用於創建和配置智能代理

City Name Mapping / 城市名稱映射表

# 城市名稱對應表:中文轉英文 CITY_TRANSLATIONS = { "台北": "Taipei", "紐約": "New York", "倫敦": "London", "東京": "Tokyo", # 可擴充更多城市 }

This dictionary maps Chinese city names to English names, allowing the system to support Chinese input. Users can use Chinese city names, and the system will automatically convert them to English names that the API can recognize. This dictionary can be expanded with more cities as needed.

這個字典將中文城市名稱映射到英文名稱,使系統能夠支援中文輸入。用戶可以使用中文城市名稱,系統會自動轉換為API能識別的英文名稱。這個字典可以根據需要擴充更多城市。

Weather Query Function / 天氣查詢功能

def fetch_weather_info(city_name: str) -> dict: """ 查詢指定城市的即時天氣資訊。 支援中文城市名稱,會自動轉換為英文。 """ if not city_name: return { "status": "error", "error_message": "請提供城市名稱以查詢天氣資訊。" } api_key = os.getenv("WEATHER_API_KEY") api_endpoint = "http://api.weatherapi.com/v1/current.json" query_city = CITY_TRANSLATIONS.get(city_name, city_name) try: response = requests.get(api_endpoint, params={"key": api_key, "q": query_city}) if response.status_code == 200: data = response.json() location = data["location"]["name"] country = data["location"]["country"] temp_c = data["current"]["temp_c"] temp_f = data["current"]["temp_f"] condition = data["current"]["condition"]["text"] humidity = data["current"]["humidity"] wind_speed = data["current"]["wind_kph"] weather_report = ( f"目前{city_name}({country})的天氣為{condition}," f"溫度 {temp_c}°C({temp_f}°F)," f"濕度 {humidity}%,風速 {wind_speed} 公里/小時。" ) return { "status": "success", "report": weather_report, } else: return { "status": "error", "error_message": f"無法取得「{city_name}」的天氣資訊。API 回應代碼:{response.status_code},請檢查城市名稱是否正確。" } except Exception as e: return { "status": "error", "error_message": f"取得「{city_name}」的天氣資訊時發生錯誤:{str(e)}" }

This function is used to query weather information for a specified city:

  1. Check if a city name is provided
  2. Get the API key from environment variables
  3. Convert Chinese city names to English (if in the mapping table)
  4. Call the WeatherAPI service to get weather data
  5. Parse the returned JSON data, extracting key weather information
  6. Format the weather report into an easy-to-read Chinese sentence
  7. Handle possible error situations

The return value is a dictionary containing status and report (or error_message).

這個函數用於查詢指定城市的天氣資訊:

  1. 檢查是否提供了城市名稱
  2. 從環境變數獲取API密鑰
  3. 將中文城市名稱轉換為英文(如果在映射表中)
  4. 呼叫WeatherAPI服務獲取天氣資料
  5. 解析返回的JSON數據,提取關鍵天氣信息
  6. 格式化天氣報告為易讀的中文句子
  7. 處理可能出現的錯誤情況

返回值是一個包含statusreport(或error_message)的字典。

Time Query Function / 時間查詢功能

def fetch_local_time(city_name: str) -> dict: """ 查詢指定城市的當前時間。 支援中文城市名稱,會自動轉換為英文。 """ if not city_name: return { "status": "error", "error_message": "請提供城市名稱以查詢當前時間。" } api_key = os.getenv("WEATHER_API_KEY") api_endpoint = "http://api.weatherapi.com/v1/current.json" query_city = CITY_TRANSLATIONS.get(city_name, city_name) try: response = requests.get(api_endpoint, params={"key": api_key, "q": query_city}) if response.status_code == 200: data = response.json() timezone_id = data["location"]["tz_id"] local_time = data["location"]["localtime"] time_report = f"目前{city_name}的時間是 {local_time}({timezone_id} 時區)" return { "status": "success", "report": time_report } else: return { "status": "error", "error_message": f"無法取得「{city_name}」的時區資訊。API 回應代碼:{response.status_code},請檢查城市名稱是否正確。" } except Exception as e: return { "status": "error", "error_message": f"取得「{city_name}」的時間資訊時發生錯誤:{str(e)}" }

This function is used to query the current time for a specified city:

  1. Check if a city name is provided
  2. Use the same API as the weather query, but only extract time-related information
  3. Parse the returned JSON data to get the timezone ID and local time
  4. Format the time report into an easy-to-read Chinese sentence
  5. Handle possible error situations

Similar to the weather query function, the return value is a dictionary containing status and report (or error_message).

這個函數用於查詢指定城市的當前時間:

  1. 檢查是否提供了城市名稱
  2. 使用與天氣查詢相同的API,但只提取時間相關資訊
  3. 解析返回的JSON數據,獲取時區ID和當地時間
  4. 格式化時間報告為易讀的中文句子
  5. 處理可能出現的錯誤情況

與天氣查詢函數類似,返回值是一個包含statusreport(或error_message)的字典。

Agent Definition / 代理定義

# 定義代理 os.environ["OPENAI_API_BASE"] = os.getenv("OPENAI_BASE_URL") model = os.getenv("CHAT_MODEL", "gpt-4o-mini") root_agent = Agent( name="weather_time_agent", model=LiteLlm(model="openai/" + model), description="回答有關城市時間和天氣的問題。", instruction="我將回答您關於城市時間和天氣的問題,請提供城市名稱。", tools=[fetch_weather_info, fetch_local_time] )

This part of the code defines an intelligent agent using Google ADK:

  1. Set the base URL for the OpenAI API (via environment variables)
  2. Get the chat model name from environment variables, defaulting to "gpt-4o-mini"
  3. Create an agent instance named "weather_time_agent"
  4. Configure the agent to use the LiteLlm model, connecting to OpenAI
  5. Provide the agent's description and instructions
  6. Register two tool functions for the agent: fetch_weather_info and fetch_local_time

This agent can understand user queries and automatically decide which function to call to answer questions about city weather or time.

這部分程式碼定義了使用Google ADK的智能代理:

  1. 設置OpenAI API的基礎URL(通過環境變數)
  2. 從環境變數獲取聊天模型名稱,默認為"gpt-4o-mini"
  3. 創建名為"weather_time_agent"的代理實例
  4. 配置代理使用LiteLlm模型,連接到OpenAI
  5. 提供代理的描述和指令
  6. 為代理註冊兩個工具函數:fetch_weather_infofetch_local_time

這個代理能夠理解用戶查詢,並自動決定調用哪個函數來回答關於城市天氣或時間的問題。

System Workflow / 系統運作流程

  1. User asks the agent about the weather or time in a specific city
  2. Agent understands the user's intent and identifies the city name
  3. Based on the type of question, the agent calls the appropriate function (weather or time query)
  4. The function sends a request to an external API to get data
  5. The data is formatted into an easy-to-understand Chinese response
  6. The agent returns the response to the user
  1. 用戶向代理詢問特定城市的天氣或時間
  2. 代理理解用戶意圖,識別城市名稱
  3. 根據用戶的問題類型,代理調用相應的函數(天氣或時間查詢)
  4. 函數向外部API發送請求獲取資料
  5. 將資料格式化為易理解的中文回應
  6. 代理將回應返回給用戶

Extension Suggestions / 擴展建議

  • Add more Chinese-English city name mappings
  • Add weather forecast functionality, not just current weather
  • Add temperature unit conversion options
  • Add support for more languages
  • Add city time difference calculation functionality
  • 增加更多城市的中英文對照
  • 增加天氣預報功能,不僅是當前天氣
  • 增加溫度單位轉換選項
  • 增加更多語言支援
  • 增加城市時差計算功能