iT邦幫忙

2025 iThome 鐵人賽

DAY 27
0
生成式 AI

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

Gradio + n8n:把 Agent 包裝成 Web App

  • 分享至 

  • xImage
  •  

目標與概念

  • 目標:建立一個可互動的 Web App,讓使用者透過 Gradio 與 n8n 中的 LLM Agent 進行即時對話。

  • 概念

    • Gradio 提供前端介面(輸入框、按鈕、檔案上傳)
    • n8n Workflow 作為後端處理邏輯
    • 整體流程:使用者輸入 → Gradio → Webhook → LLM Agent → 回傳結果 → Gradio 顯示

操作環境準備

  • 已完成 來自昨天給你的任務流程 Workflow
  • n8n Docker 容器已啟動並可使用
  • Python 3.9 以上版本
  • 安裝必要套件:
pip install gradio requests
  • 確保 n8n Webhook /task-agent 可以正常接收請求

步驟流程

Step 1:建立 Gradio UI

建立一個簡單的互動介面,包含輸入框與送出按鈕,將使用者輸入的文字傳送到 n8n Webhook。

import gradio as gr
import requests

def chat_with_agent(user_input):
    response = requests.post(
        "http://localhost:5678/webhook/task-agent",
        json={"text": user_input, "metadata": {"user": "Test"}}
    )
    data = response.json()
    return data.get("summary", "Agent 沒有回應")

iface = gr.Interface(
    fn=chat_with_agent,
    inputs="text",
    outputs="text",
    title="LLM Agent Web App",
    description="輸入文字後,Agent 將自動分析並回覆摘要或回答。"
)

iface.launch()

Step 2:n8n Workflow 處理邏輯

  • Webhook 接收 Gradio 傳入的文字
  • HTTP Request 節點呼叫 Gemini 或 OpenAI API
  • Function 節點整理結果並輸出
  • Webhook 回傳最終 JSON 給 Gradio 顯示

Step 3:測試流程

  1. 啟動 Gradio:

    python gradio_app.py
    
  2. 瀏覽器開啟預設頁面:http://127.0.0.1:7860

  3. 在文字框中輸入問題或內容並送出

  4. 預期顯示 LLM Agent 回覆的摘要或答案


測試與驗證

  • 確認 n8n Webhook 節點有收到 Gradio 的請求
  • Function 節點正確解析與處理 LLM 回覆
  • Gradio 頁面能即時顯示回傳結果
  • 若 Workflow 已啟用(Active),即可直接互動

錯誤排查與調整建議

問題 解決方式
Agent 無回應 檢查 Webhook URL 是否正確,Workflow 是否啟用
Gradio 顯示空白 檢查回傳的 JSON key 名稱是否為 summary
Docker 端口衝突 確認 n8n 與 Gradio 運行於不同 port
LLM 回傳結構錯誤 檢查 API Response 結構與 Function 節點 JSON 路徑

今日小結

  • 完成 Gradio + n8n 串接 LLM Agent
  • 建立使用者可即時互動的 Web App
  • 理解從前端 UI → Webhook → Agent → 回傳結果的完整流程
  • 為下一階段(檔案分析與自動化)打下基礎

上一篇
完整任務流程:讀取 → 理解 → 整理 → 回報
系列文
30 天打造你的 AI Agent:LangChain × n8n 實戰27
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言