iT邦幫忙

2025 iThome 鐵人賽

DAY 22
0
生成式 AI

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

【Day 22】 小專案 - 交通查詢 Agent(上)

  • 分享至 

  • xImage
  •  

接下來,我們要來完成第三支 Agent —— 交通查詢 Agent
這個 Agent 的任務是根據使用者提供的「出發地」與「目的地」,回傳可行的交通方式。

注意:這裡我們使用的是模擬資料,並不會真的串接外部 API。

使用 FastAPI 建立交通查詢 Agent

在正式建立 Agent 之前,我們先用 FastAPI 實作一個簡單的交通查詢 API,確認整體邏輯是否能順利運作。

from fastapi import FastAPI, HTTPException
from pydantic import BaseModel

app = FastAPI()

# 模擬交通資料
TRANSPORT_DATABASE = {
    ("Taipei", "Kaohsiung"): ["高鐵", "飛機", "客運公車"],
    ("Taipei", "Taichung"): ["高鐵", "客運公車"],
    ("Taipei", "Tokyo"): ["飛機"],
    ("Tokyo", "Kyoto"): ["新幹線", "飛機"],
}

class TransportRequest(BaseModel):
    start: str
    end: str

@app.post("/transport")
async def query_transport(request: TransportRequest):
    """
    呼叫交通查詢 API
    功能:
      - 模擬交通方式
      - 根據起點與終點回傳可行交通方式
    """
    try:
        start = request.start.strip()
        end = request.end.strip()

        if not start or not end:
            raise HTTPException(status_code=400, detail="Both start and end locations are required.")

        routes = TRANSPORT_DATABASE.get((start, end), [])

        if not routes:
            return {
                "status": "error",
                "message": f"No transport information found from '{start}' to '{end}'."
            }

        return {"status": "success", "start": start, "end": end, "routes": routes}

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

程式簡單解說

  • TRANSPORT_DATABASE:模擬交通資料庫(實務上可改為串接外部 API)。
  • TransportRequest(BaseModel):定義請求格式,包含出發地 start 與目的地 end
  • @app.post("/transport"):建立 POST 路由,負責處理查詢請求。
  • routes = TRANSPORT_DATABASE.get((start, end), []):依照輸入查詢可行的交通方式。
  • 若查無資料,會回傳 "status": "error" 與提示訊息。
  • HTTPException:用來捕捉錯誤並回傳對應的 HTTP 狀態碼,確保 API 穩定性。

實際測試

  • API
    https://ithelp.ithome.com.tw/upload/images/20251006/201684562SAQoeW137.png
  • Taipei → Kaohsiung
    https://ithelp.ithome.com.tw/upload/images/20251006/20168456KSEsXmEw4t.png
    https://ithelp.ithome.com.tw/upload/images/20251006/20168456PWnL9P4KK0.png
  • Taipei → Taichung
    https://ithelp.ithome.com.tw/upload/images/20251006/201684566p0dBTGyo4.png
    https://ithelp.ithome.com.tw/upload/images/20251006/20168456napMnawqfa.png
  • Taipei → Tokyo
    https://ithelp.ithome.com.tw/upload/images/20251006/20168456UJM2JjJHcY.png
    https://ithelp.ithome.com.tw/upload/images/20251006/20168456hP1BmKiIxu.png
  • Tokyo → Kyoto
    https://ithelp.ithome.com.tw/upload/images/20251006/20168456FYuwvGQzw0.png
    https://ithelp.ithome.com.tw/upload/images/20251006/201684560c4XCbNZZ9.png
  • 查無資料的情況
    https://ithelp.ithome.com.tw/upload/images/20251006/20168456aZ6eLppjrp.png
    https://ithelp.ithome.com.tw/upload/images/20251006/20168456jxYp5cR2Ha.png

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

尚未有邦友留言

立即登入留言