前一篇,我們已經成功建立了 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 的整個推理流程。InMemorySessionService
、InMemoryArtifactService
:建立 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 的流程:
userInput
Runner
呼叫 root_agent
處理這段輸入為了讓 FastAPI 能順利運作,我們需要把所有檔案的相對匯入改成絕對匯入。
所有 Sub-Agent 檔案(HotelContrastAgent.py
、HotelSearchAgent.py
、TransportAgent.py
、ItineraryAgent.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 的測試畫面:
這裡只以其中一個的 Agent 查詢作為測試範例。