iT邦幫忙

2025 iThome 鐵人賽

DAY 4
0
生成式 AI

30 天打造你的 AI Agent:LangChain × n8n 實戰系列 第 4

讓 Agent 進化成 FastAPI 服務!

  • 分享至 

  • xImage
  •  

昨天我們成功做出了一個最簡單的規則型 Agent,用 if/else 來分支決策。
今天要更進一步,讓這個 Agent 走出台灣 CLI 世界,進化成 API 服務!

這麼一來,我們不需要在命令列輸入 input(),而是可以用 HTTP 呼叫,甚至未來能接前端網頁、LINE Bot 或 Discord Bot 🎉


升級重點

  • 從 CLI 到 API:不再用 input() 與程式互動,而是用 HTTP POST 傳送資料。
  • 集中邏輯:決策函數 (decide_action) 保持不變,專心負責邏輯;FastAPI 負責提供 API 介面。
  • 更容易擴充:只要新增分支邏輯,API 自動支援,不需要改動主架構。

Python 實作:「FastAPI Agent」

from datetime import datetime
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

# 設定api要輸入的格式
class UserInput(BaseModel):
    command: str     #命令
    mood: str | None = None   #心情(選填預設為None)
 
# 決策邏輯函數
def decide_action(user_input: UserInput):
    if user_input.command == "天氣":
        return "今天是晴天哦!"

    elif user_input.command == "時間":
        return f"現在時間是:{datetime.now().strftime('%H:%M')}"

    elif user_input.command == "心情":
        if user_input.mood == "好":
            return "太棒了!保持好心情吧~"
        elif user_input.mood == "不好":
            return "沒關係,明天會更好!"
        else:
            return "我還不太懂這個心情,但希望你一切順利!"

    elif user_input.command == "離開":
        return "掰掰~"

    else:
        return "抱歉,我還不懂這個指令。"

# API endpoint
@app.post("/agent")    
def agent_api(user_input: UserInput):
    result = decide_action(user_input)
    return {"response": result}

▶️ 使用方式

安裝需要的套件:
pip install fastapi uvicorn

啟動伺服器:
uvicorn main:app --reload

https://ithelp.ithome.com.tw/upload/images/20250918/20168458bJNyqDKnCc.png

可以看到裡面有一串網址127.0.0.1:8000,打開網頁在網址後面加上/docs,就可以看到我們寫著這隻api的內容了!127.0.0.1:8000/docs or localhost:8000/docs
https://ithelp.ithome.com.tw/upload/images/20250918/20168458fHuiOvBf3w.png

要怎麼啟動這個api呢??
相信大家的畫面右上角也跟我一樣有一個try it out點開就可以輸入內容了!
https://ithelp.ithome.com.tw/upload/images/20250918/20168458Lbu38MV63h.png
https://ithelp.ithome.com.tw/upload/images/20250918/20168458U3ienHbH3z.png

🔹 API Endpoint 說明

@app.post("/agent")
def agent_api(user_input: UserInput):
    result = decide_action(user_input)
    return {"response": result}
  1. @app.post("/agent")

    • 這一行是 FastAPI 的裝飾器 (decorator)
    • 指定這個函數對應的 API 路徑 /agent
    • .post() 表示 HTTP POST 方法,也就是要用 POST 方式傳送資料才能呼叫
  2. def agent_api(user_input: UserInput)

    • 這是 API 的主體函數
    • user_input 會自動解析 POST 的 JSON,並轉成 UserInput 物件
    • 也就是說,你送進來的指令和參數,都會在這個物件裡
  3. result = decide_action(user_input)

    • 呼叫之前寫好的決策函數,根據使用者輸入決定回覆內容
  4. return {"response": result}

    • 將決策結果以 JSON 回傳給使用者
    • 前端或其他程式就可以直接拿這個結果使用

結尾

今天我們成功把原本的規則型 Agent 升級成 FastAPI 服務,不僅保留了原本的決策邏輯,還能透過 HTTP POST 被外部程式或前端呼叫。

這意味著,我們的 Agent 不再只是自己在電腦上玩的 CLI 工具,而是一個可以 提供服務的小助手:

你可以把它接到網頁、LINE Bot、Discord Bot
未來也可以加入更多功能,例如查天氣、倒數日、格式化金額等
下一步,我們會嘗試:
將 OpenWeatherMap 的真實天氣功能整合進 API
擴充更多指令與條件分支,讓 Agent 變得更智慧
將這個 FastAPI Agent 部署到雲端,讓其他人也能使用
透過這個練習,我們已經完成了從 單機互動 → API 服務 → 可擴充小幫手 的完整進化流程。
你的 Agent 已經準備好,開始「思考」並協助你處理日常任務了! 🌟


上一篇
你的第一個「規則型 Agent」
下一篇
替 Agent 安裝「大腦」——註冊 OpenAI API Key
系列文
30 天打造你的 AI Agent:LangChain × n8n 實戰11
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言