目標:讓 Agent 能自動接收並分析上傳的 PDF 或 CSV 檔案。
概念:
pip install pandas PyPDF2 requests gradio
使用 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()
Webhook 節點
/file-agent
Read Binary File 節點
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) } }];
HTTP Request 節點
Function 節點(整理結果)
Webhook Response
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 沒有回應")
const csv = require('csv-parse/sync');
const records = csv.parse($binary.data, { columns: true });
return [{ json: { text: JSON.stringify(records) } }];
上傳 PDF 或 CSV 測試檔案至 Gradio
驗證 n8n 節點執行順序:
確認 Gradio 回傳的文字結果包含摘要或分析內容
若使用 PDF,可檢查內容是否被正確提取
問題 | 可能原因與解法 |
---|---|
檔案無法讀取 | 檢查 File 節點設定、確認檔案類型正確 |
PDF 解析錯誤 | 安裝 PyPDF2 或 pdf-parse 模組 |
LLM 無回應 | 檢查 API Key、HTTP Request Body 格式 |
Webhook 空白回傳 | 確認 Response Mode 已設為「Last Node」 |