iT邦幫忙

2025 iThome 鐵人賽

DAY 26
0
生成式 AI

Multi-Agent 實戰:開發多代理智慧小幫手系列 第 26

【Day 26】 小專案 - Master Agent 實作並測試

  • 分享至 

  • xImage
  •  

經過前面幾天的練習,我們已經完成了四個獨立的 Sub-Agent:

  • 飯店搜尋(Hotel Search Agent)
  • 飯店比較(Hotel Compare Agent)
  • 交通查詢(Transport Agent)
  • 日程規劃(Itinerary Agent)

這篇我們要把這四支 Agent 全部包裝進一個 Master Agent(Root Agent),讓它能根據使用者的輸入,自動判斷需求並選擇合適的 Sub-Agent 來執行。

專案結構

整個專案的最終目錄如下:

ExampleProject
 └─ TravelAgent
     ├─ __init__.py
     ├─ HotelContrastAgent.py
     ├─ HotelSearchAgent.py
     ├─ TransportAgent.py
     ├─ ItineraryAgent.py
     ├─ prompt.py
     ├─ .env
     └─ MasterAgent.py

__init__.py

為了讓整個模組在匯入時能自動載入 root_agent,我們只需要在 __init__.py 中加入:

from .MasterAgent import root_agent

這樣當導入 TravelAgent 時,就會自動載入我們的 Master Agent。

.env

別忘了在專案根目錄放上 API Key 設定:

GOOGLE_GENAI_USE_VERTEXAI=FALSE
GOOGLE_API_KEY=YOUR_API_KEY

MasterAgent.py

  • 匯入 Sub-Agent 與必要模組
    在這個檔案中,我們要整合所有先前建立好的 Agent:
    from google.adk.agents import Agent
    import os
    from dotenv import load_dotenv
    from .HotelContrastAgent import hotel_compare_agent
    from .HotelSearchAgent import hotel_search_agent
    from .TransportAgent  import transport_agent
    from .ItineraryAgent  import itinerary_agent
    from . import prompt
    
  • 載入環境變數
    load_dotenv()
    
  • 包裝成 Master Agent
    接著建立 root_agent,並把四個 Sub-Agent 全部掛上去:
    root_agent = Agent(
        name="root_agent",
        model="gemini-2.5-flash",
        description=prompt.ROOT_AGENT_DESCRIPTION,
        instruction=prompt.ROOT_AGENT_INSTRUCTION,
        sub_agents=[
            hotel_compare_agent,
            hotel_search_agent,
            itinerary_agent,
            transport_agent
        ],
    )
    

簡單prompt

  • description

    ROOT_AGENT_DESCRIPTION = """
    This is a root coordination agent that integrates multiple sub-agents, including hotel search, hotel comparison, transport queries, and itinerary planning.
    """
    

    這裡簡單的說明了,Master Agent 是整個系統的中樞,負責協調與整合所有子代理。

  • instruction

    ROOT_AGENT_INSTRUCTION = """
    You are a root agent responsible for coordinating sub-agents and integrating their responses. You can use the following sub-agents:
    
    1. **Hotel Search Agent**
       - **Purpose:** Searches hotels by city, returning up to 3 results.
       - **Parameters:**
         - `city` (str): The target city for hotel search.
       - **Example Input:**
         ```json
         { "city": "Tokyo" }
         ```
    
    2. **Hotel Compare Agent**
       - **Purpose:** Compares two hotels based on price or rating, recommending the best one.
       - **Parameters:**
         - `hotel1` (str): The first hotel name.
         - `hotel2` (str): The second hotel name.
         - `criterion` (str): Comparison basis, either `"cheapest"` or `"best_rating"`.
       - **Example Input:**
         ```json
         { "hotel1": "Hotel Sakura", "hotel2": "Hotel Fuji", "criterion": "cheapest" }
         ```
    
    3. **Transport Agent**
       - **Purpose:** Provides available transport options between an origin and destination.
       - **Parameters:**
         - `start` (str): Starting location.
         - `end` (str): Destination location.
       - **Example Input:**
         ```json
         { "start": "Taipei", "end": "Kaohsiung" }
         ```
    
    4. **Itinerary Agent**
       - **Purpose:** Generates travel itineraries based on city and number of days.
       - **Parameters:**
         - `city` (str): The target city for the itinerary.
         - `days` (int): Number of days to plan.
       - **Example Input:**
         ```json
         { "city": "Seoul", "days": 3 }
         ```
    
    Your responsibilities:
    - Analyze the user’s input and decide which sub-agent(s) should handle the request.
    - Integrate outputs into a single coherent, helpful response.
    - Return an error if the request cannot be handled by any sub-agent.
    
    Dispatch guidelines:
    - Hotel-related queries → Hotel Search or Hotel Compare Agent
    - Transport-related queries → Transport Agent
    - Itinerary-related queries → Itinerary Agent
    
    Always respond in a natural, helpful, and user-friendly manner.
    """
    

    prompt 內容概述

    1. 輸入要求
      • 接收使用者輸入,可能包含查飯店、比價、交通查詢或日程規劃等需求。
    2. 執行邏輯
      • 分析使用者問題並判斷該由哪個 Sub-Agent 處理。
      • 根據判斷結果呼叫對應 Sub-Agent 並回傳結果。
    3. 語氣與風格
      • 回覆需自然、友善、易懂。
      • 回答要條理分明,清楚說明每個 Sub-Agent 的結果。

這樣,我們的 Master Agent 就能自動根據使用者問題選擇對應的 Sub-Agent。

實際測試

整合完成後,我們就可以啟動測試:

adk web --port 5000

記得先切換到最外層資料夾(ExampleProject

接著開啟瀏覽器,就能測試每個 Sub-Agent 是否都能被 Master Agent 正確調用。

測試畫面示範

  • Hotel_Contrast_Agent
    • 比較價格(選出較便宜者)
      https://ithelp.ithome.com.tw/upload/images/20251010/20168456jhDXDJTGso.png
    • 比較評價(選出評價較高者)
      https://ithelp.ithome.com.tw/upload/images/20251010/20168456qlSfu51PbQ.png
  • Hotel_Search_Agent
    https://ithelp.ithome.com.tw/upload/images/20251010/20168456O9RIIHx6Xz.png
  • Itinerary_Agent
    • 3天Tokyo行程
      https://ithelp.ithome.com.tw/upload/images/20251010/20168456En1ZzSBOXO.png
    • 2天Taipei行程
      https://ithelp.ithome.com.tw/upload/images/20251010/20168456j5LHs1o88V.png
  • Transport_Agent
    https://ithelp.ithome.com.tw/upload/images/20251010/201684565U9oyhKSjT.png

上一篇
【Day 25】 小專案 - 日程規劃 Agent(下)
下一篇
【Day 27】 小專案 - 將 Master Agent 改寫成可供前端呼叫的 API
系列文
Multi-Agent 實戰:開發多代理智慧小幫手28
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言