iT邦幫忙

2025 iThome 鐵人賽

DAY 24
0
生成式 AI

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

【Day 24】 小專案 - 日程規劃 Agent(上)

  • 分享至 

  • xImage
  •  

接下來我們要完成最後一支 Sub-Agent
這個 Agent 的任務是根據使用者提供的「城市」與「天數」,自動產生每天的旅遊行程。

注意:這裡使用的是 模擬資料,不會串接真實 API。

使用 FastAPI 建立日程規劃 API

我們一樣先用 FastAPI 來實作一個簡單的日程規劃 API,確認整體邏輯能正常運作。

from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
import random

app = FastAPI()

# 模擬景點資料庫
SIGHTSEEING_SPOTS = {
    "Taipei": ["台北101", "士林夜市", "故宮博物院", "象山步道", "淡水老街"],
    "Kaohsiung": ["蓮池潭", "駁二藝術特區", "六合夜市", "旗津", "美麗島站"],
    "Tokyo": ["淺草寺", "東京塔", "秋葉原", "上野公園", "新宿御苑"],
}

class ItineraryRequest(BaseModel):
    city: str
    days: int = 1

@app.post("/generate-itinerary")
def generate_itinerary(request: ItineraryRequest) -> dict:
    """
    呼叫日程規劃 Agent
    功能:
      - 根據天數生成簡單行程
      - 可隨機選景點或依固定規則排程
    """
    try:
        city = request.city.strip()
        days = request.days

        if not city:
            raise ValueError("City is required.")
        if days <= 0:
            raise ValueError("Days must be a positive integer.")

        spots = SIGHTSEEING_SPOTS.get(city, [])
        if not spots:
            return {"status": "error", "message": f"No sightseeing data for city '{city}'."}

        itinerary = {}
        for day in range(1, days + 1):
            # 每天安排最多 2-3 個景點,隨機挑選
            itinerary[f"Day {day}"] = random.sample(spots, min(len(spots), 3))

        return {"status": "success", "city": city, "days": days, "itinerary": itinerary}

    except Exception as e:
        raise HTTPException(status_code=500, detail=f"An error occurred: {e}")

程式簡單解說

  • SIGHTSEEING_SPOTS:模擬的景點資料庫(實際應用中可以串接外部 API)。
  • ItineraryRequest(BaseModel):定義請求格式,包含:
    • city:城市名稱(例如 "Taipei""Tokyo"
    • days:天數(預設為 1)
  • @app.post("/generate-itinerary"):建立 POST 路由來處理請求。
  • random.sample():每天隨機挑選 2~3 個景點作為行程。
  • 錯誤處理:若城市不存在或天數無效,會回傳清楚的錯誤訊息。
  • HTTPException:確保錯誤能以正確的 HTTP 狀態碼回傳。

實際測試

  • API
    https://ithelp.ithome.com.tw/upload/images/20251008/20168456823ywZWlWp.png
  • Taipei
    https://ithelp.ithome.com.tw/upload/images/20251008/20168456w0tRrxzPse.png
    https://ithelp.ithome.com.tw/upload/images/20251008/20168456XXWXJd7cPX.png
  • Kaohsiung
    https://ithelp.ithome.com.tw/upload/images/20251008/20168456QKJssKVSt7.png
    https://ithelp.ithome.com.tw/upload/images/20251008/20168456dNYcpSq0u6.png
  • Tokyo
    https://ithelp.ithome.com.tw/upload/images/20251008/20168456dzE1LNoU7Y.png
    https://ithelp.ithome.com.tw/upload/images/20251008/201684567D79PJFzWA.png
  • 增加天數
    https://ithelp.ithome.com.tw/upload/images/20251008/201684565Jm0we1WZO.png
    https://ithelp.ithome.com.tw/upload/images/20251008/20168456vK9yYgc9C1.png
  • 錯誤訊息
    https://ithelp.ithome.com.tw/upload/images/20251008/20168456XtErfXlXzh.png
    https://ithelp.ithome.com.tw/upload/images/20251008/20168456DreDL9o7so.png

上一篇
【Day 23】 小專案 - 交通查詢 Agent(下)
系列文
Multi-Agent 實戰:開發多代理智慧小幫手24
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言