iT邦幫忙

2025 iThome 鐵人賽

DAY 28
0
生成式 AI

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

加入檔案上傳功能:PDF、CSV 自動處理

  • 分享至 

  • xImage
  •  

目標與概念

  • 目標:讓 Agent 能自動接收並分析上傳的 PDF 或 CSV 檔案。

  • 概念

    • Gradio 支援檔案上傳(File Upload)
    • n8n 可使用節點讀取檔案內容(Read Binary File、Function)
    • LLM Agent 處理並分析文件內容,輸出摘要或重點結論
    • 回傳結果給前端顯示

操作環境準備

  • 已完成 昨天的 Gradio + n8n Web App
  • Python 3.9 以上版本
  • 安裝必要套件:
pip install pandas PyPDF2 requests gradio
  • Docker n8n 容器正在運行
  • 確認 Workflow 可以接收 Webhook JSON

步驟流程

Step 1:Gradio UI 加入檔案上傳

使用 Gradio 的 File 元件上傳 PDF 或 CSV,並將檔案以 multipart/form-data 形式傳送至 n8n Webhook。

import gradio as gr
import requests

def process_file(file):
    files = {"file": open(file.name, "rb")}
    response = requests.post("http://localhost:5678/webhook/file-agent", files=files)
    data = response.json()
    return data.get("result", "Agent 沒有回應")

iface = gr.Interface(
    fn=process_file,
    inputs=gr.File(file_types=[".pdf", ".csv"]),
    outputs="text",
    title="LLM Agent 檔案分析",
    description="上傳 PDF 或 CSV,Agent 會自動分析內容並回傳摘要或結論。"
)
iface.launch()

Step 2:n8n Workflow 設定

  1. Webhook 節點

    • URL:/file-agent
    • Method:POST
  2. Read Binary File 節點

    • 讀取上傳檔案的二進位內容
  3. Function 節點:解析檔案內容

    • 若為 PDF,可使用 pdf-parse

      const pdf = require('pdf-parse');
      return pdf($binary.data).then(data => [{ json: { text: data.text } }]);
      
    • 若為 CSV,可使用 csv-parse/sync

      const csv = require('csv-parse/sync');
      const records = csv.parse($binary.data, { columns: true });
      return [{ json: { text: JSON.stringify(records) } }];
      
  4. HTTP Request 節點

    • 將解析後的文字內容傳給 LLM(如 Gemini 或 OpenAI)進行分析
  5. Function 節點(整理結果)

    • 取出 LLM 回覆並格式化輸出
  6. Webhook Response

    • Response Mode 設為「Last Node」
    • 將結果回傳給 Gradio

範例程式片段

Gradio 上傳端:

def process_file(file):
    files = {"file": open(file.name, "rb")}
    response = requests.post("http://localhost:5678/webhook/file-agent", files=files)
    return response.json().get("result", "Agent 沒有回應")

n8n Function 解析 CSV 範例:

const csv = require('csv-parse/sync');
const records = csv.parse($binary.data, { columns: true });
return [{ json: { text: JSON.stringify(records) } }];

測試與驗證

  1. 上傳 PDF 或 CSV 測試檔案至 Gradio

  2. 驗證 n8n 節點執行順序:

    • Webhook → Read File → Function → LLM → Function → Response
  3. 確認 Gradio 回傳的文字結果包含摘要或分析內容

  4. 若使用 PDF,可檢查內容是否被正確提取


錯誤排查與調整建議

問題 可能原因與解法
檔案無法讀取 檢查 File 節點設定、確認檔案類型正確
PDF 解析錯誤 安裝 PyPDF2 或 pdf-parse 模組
LLM 無回應 檢查 API Key、HTTP Request Body 格式
Webhook 空白回傳 確認 Response Mode 已設為「Last Node」

今日小結

  • 建立支援檔案上傳的 Gradio + n8n 自動化流程
  • n8n 可自動解析並分析 PDF、CSV 檔案內容
  • LLM Agent 可輸出結構化摘要與結論
  • 完成前端到後端的文件自動化分析流程

上一篇
Gradio + n8n:把 Agent 包裝成 Web App
下一篇
完整流程 Demo — Gradio + n8n + Gemini
系列文
30 天打造你的 AI Agent:LangChain × n8n 實戰30
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言