iT邦幫忙

2025 iThome 鐵人賽

DAY 27
0
生成式 AI

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

【Day 27】 小專案 - 將 Master Agent 改寫成可供前端呼叫的 API

  • 分享至 

  • xImage
  •  

前一篇,我們已經成功建立了 Master Agent,能夠整合所有 Sub-Agent(飯店查詢、飯店比較、交通查詢、日程規劃)。
但若要讓前端能與後端互動,就需要將 Agent 改寫成 API 模式
這篇將一步步示範如何進行改寫,並實際測試運作結果。

專案構造

以下是最終的專案目錄:

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

這裡多了一個新的檔案 main.py,它是整個專案的入口點,負責啟動 FastAPI,並讓前端能夠呼叫 Root Agent。

注意 __init__.py 不需要了,可以刪除。

main.py

main.py 的任務就是「用 FastAPI 包住 Master Agent」。

  • 匯入必要模組

    from fastapi import FastAPI, HTTPException
    from typing import Dict, Any
    from MasterAgent import root_agent
    from google.genai import types
    from google.adk.runners import Runner
    from google.adk.artifacts.in_memory_artifact_service import InMemoryArtifactService
    from google.adk.sessions import InMemorySessionService
    

    除了 FastAPI,本體還導入了以下幾個核心模組:

    • Runner:負責執行 Agent 的整個推理流程。
    • InMemorySessionServiceInMemoryArtifactService
      提供臨時的 Session 與記憶體資料保存,不需要外部資料庫即可運作。
  • 建立 FastAPI 應用

    app = FastAPI(
        title="Travel Root Agent API",
        description="API interface to interact with the root agent that coordinates hotel, transport, and itinerary sub-agents.",
        version="1.0.0",
    )
    

    這段建立一個新的 FastAPI 應用,並設定 API 的標題與描述。

  • 建立 Session 與 Artifact 服務

    session_service = InMemorySessionService()
    artifacts_service = InMemoryArtifactService()
    

    這兩個服務負責讓 Agent 在多次互動中「記住」對話狀態。

  • 建立 Root Agent 的 API 端點

    @app.post("/RootAgent")
    async def rootAgent(
        userInput: str,
    ):
        if not userInput:
            return {"error": "Please provide user input"}
    
        try:
            # 建立 session
            session = await session_service.create_session(
                state={}, app_name="compal_ai_hearable_backend", user_id="user"
            )
    
            # 將使用者輸入轉為 Part
            parts = [types.Part(text=userInput)]
    
            content = types.Content(role="user", parts=parts)
    
            # 執行 Root Agent
            runner = Runner(
                app_name="compal_ai_hearable_backend",
                agent=root_agent,
                artifact_service=artifacts_service,
                session_service=session_service,
            )
    
            events_async = runner.run_async(
                session_id=session.id, user_id="user", new_message=content
            )
    
            # 收集回傳結果
            response = []
            async for event in events_async:
                if event.content:
                    for part in event.content.parts:
                        if part.text:
                            response.append(part.text)
    
            full_response = "\n".join(response)
    
            # 以 JSON 的格式回傳 Root Agent 的回應內容
            return {"response": full_response}
    
        except Exception as e:
            print(f"root agent analysis failed: {str(e)}")
            return {"error": "root agent analysis failed"}
    

    總結這個 API 的流程:

    1. 接收使用者輸入 userInput
    2. 建立一個新的 session
    3. 封裝使用者輸入為 Agent 可讀的格式
    4. 使用 Runner 呼叫 root_agent 處理這段輸入
    5. 監聽 Agent 的非同步輸出
    6. 將所有回應整合並回傳給前端

其他 Agent 需要的修改

為了讓 FastAPI 能順利運作,我們需要把所有檔案的相對匯入改成絕對匯入。

  • 所有 Sub-Agent 檔案(HotelContrastAgent.pyHotelSearchAgent.pyTransportAgent.pyItineraryAgent.py

    # 原本
    from . import prompt
    
    # 修改後
    import prompt
    
  • MasterAgent.py

    # 原本
    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
    
    # 修改後
    from HotelContrastAgent import hotel_compare_agent
    from HotelSearchAgent import hotel_search_agent
    from TransportAgent import transport_agent
    from ItineraryAgent import itinerary_agent
    import prompt
    

實際測試圖片

以下展示透過 Root Agent API 呼叫各個子 Agent 的測試畫面:

  • Hotel_Contrast_Agent
    • 請幫我比較 Taipei Grand Hotel 跟 Hotel Proverbs Taipei 哪一個比較便宜
      https://ithelp.ithome.com.tw/upload/images/20251011/20168456qFE4eMappr.png
      https://ithelp.ithome.com.tw/upload/images/20251011/20168456BQXibdPqiB.png
    • 請幫我比較 Taipei Grand Hotel 跟 Hotel Proverbs Taipei 哪一個評價比較高
      https://ithelp.ithome.com.tw/upload/images/20251011/20168456hgDNEUDI9D.png
      https://ithelp.ithome.com.tw/upload/images/20251011/20168456wQ2h8cIn8J.png
  • Hotel_Search_Agent
    • 幫我推薦幾間 Taipei 的飯店
      https://ithelp.ithome.com.tw/upload/images/20251011/20168456G8IDp09Fi6.png
      https://ithelp.ithome.com.tw/upload/images/20251011/20168456CwAra26Kdo.png
  • Itinerary_Agent
    • 幫我規劃3天的Tokyo行程
      https://ithelp.ithome.com.tw/upload/images/20251011/20168456oLLJTAIGUX.png
      https://ithelp.ithome.com.tw/upload/images/20251011/201684566AHv4Rg6ZG.png
    • 幫我規劃2天的Taipei行程
      https://ithelp.ithome.com.tw/upload/images/20251011/20168456gUoN8xHZMf.png
      https://ithelp.ithome.com.tw/upload/images/20251011/20168456ShePtCfdTR.png
  • Transport_Agent
    • 我想從 Taipei 去 Kaohsiung,有哪些交通方式?
      https://ithelp.ithome.com.tw/upload/images/20251011/20168456egcH90cZBx.png
      https://ithelp.ithome.com.tw/upload/images/20251011/20168456VIY6xGGOiC.png
  • 利用 Postman 測試
    https://ithelp.ithome.com.tw/upload/images/20251011/20168456wW2s2NGRNP.png

    這裡只以其中一個的 Agent 查詢作為測試範例。


上一篇
【Day 26】 小專案 - Master Agent 實作並測試
下一篇
【Day 28】 小專案 - 前端聊天介面
系列文
Multi-Agent 實戰:開發多代理智慧小幫手28
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言