作者:PySuper | 来源:zhengxingtao.com
日期:2026-10-15
目录
1. n8n 是什么
2. n8n 的 AI 节点生态
3. 确定性编排 vs 非确定性推理
4. 实战1:AI驱动的客服工单处理流程
5. 实战2:n8n + MCP 集成
6. AI Agent 节点深入
7. n8n 与专用 Agent 框架的协作
8. 自托管部署
9. 生产场景
10. 踩坑记录
11. 总结
1. n8n 是什么
n8n(发音 "n-eight-n")是一个开源的工作流自动化工具,核心思路是拖拽式节点编排——把不同的应用和服务通过可视化方式连接起来,实现流程自动化。
plaintext
┌────────────────────────────────────────────────────────────┐
│ n8n 核心概念 │
├────────────────────────────────────────────────────────────┤
│ │
│ 工作流 (Workflow) │
│ ├─ 由多个节点连接而成的自动化流程 │
│ ├─ 有明确的触发器(Webhook / 定时 / 事件) │
│ └─ 数据在节点间流动和变换 │
│ │
│ 节点 (Node) │
│ ├─ 触发器节点:Webhook、Cron、Email、Slack Event │
│ ├─ 操作节点:HTTP Request、数据库、文件操作 │
│ ├─ 逻辑节点:IF、Switch、Merge、Split │
│ └─ AI 节点:OpenAI、AI Agent、Vector Store │
│ │
│ 连接 (Connection) │
│ ├─ 节点之间的数据管道 │
│ ├─ 支持条件分支(IF 节点输出 true/false 两条路径) │
│ └─ 支持并行执行(一个节点的输出连到多个节点) │
│ │
│ 执行 (Execution) │
│ ├─ 每次工作流运行就是一个执行记录 │
│ ├─ 可以查看每个节点的输入/输出 │
│ └─ 失败的执行可以手动重试 │
│ │
└────────────────────────────────────────────────────────────┘
1.1 n8n vs Zapier vs Make
表格
据 n8n 官网(https://n8n.io/ai/),n8n 在 2025 年获得了 6000 万美元融资,估值数亿美元。核心差异化在于开源 + AI 原生 + MCP 支持。
2. n8n 的 AI 节点生态
n8n 从 2024 年开始集成 AI 能力,到 2026 年已经形成了完整的 AI 节点体系:
plaintext
┌───────────────────────────────────────────────────────────┐
│ n8n AI 节点体系 │
├───────────────────────────────────────────────────────────┤
│ │
│ ┌─────────────────────────────────────────────────┐ │
│ │ LLM 节点 (大模型调用) │ │
│ │ ├─ OpenAI (GPT-4o, GPT-5) │ │
│ │ ├─ Anthropic Claude (Sonnet, Opus) │ │
│ │ ├─ Google Gemini │ │
│ │ ├─ Ollama (本地模型) │ │
│ │ └─ Azure OpenAI │ │
│ └─────────────────────────────────────────────────┘ │
│ │
│ ┌─────────────────────────────────────────────────┐ │
│ │ AI Agent 节点 (智能体) │ │
│ │ ├─ ReAct Agent (推理+行动循环) │ │
│ │ ├─ Conversational Agent (对话型) │ │
│ │ ├─ Tools Agent (工具调用型) │ │
│ │ └─ 自定义 Agent │ │
│ └─────────────────────────────────────────────────┘ │
│ │
│ ┌─────────────────────────────────────────────────┐ │
│ │ Vector Store 节点 (向量存储) │ │
│ │ ├─ PostgreSQL + pgvector │ │
│ │ ├─ Pinecone │ │
│ │ ├─ Qdrant │ │
│ │ ├─ Chroma │ │
│ │ └─ Supabase │ │
│ └─────────────────────────────────────────────────┘ │
│ │
│ ┌─────────────────────────────────────────────────┐ │
│ │ MCP 节点 (Model Context Protocol) │ │
│ │ ├─ MCP Server Trigger (暴露工作流为MCP工具) │ │
│ │ ├─ MCP Client (调用外部MCP Server) │ │
│ │ └─ 支持 HTTP Streamable + SSE 传输 │ │
│ └─────────────────────────────────────────────────┘ │
│ │
│ ┌─────────────────────────────────────────────────┐ │
│ │ 辅助节点 │ │
│ │ ├─ Embedding (文本向量化) │ │
│ │ ├─ Text Splitter (文本分块) │ │
│ │ ├─ Output Parser (输出解析) │ │
│ │ └─ Memory (对话记忆) │ │
│ └─────────────────────────────────────────────────┘ │
│ │
└───────────────────────────────────────────────────────────┘
3. 确定性编排 vs 非确定性推理
理解 n8n 和 Agent 框架的根本区别,关键在于确定性 vs 非确定性:
plaintext
┌────────────────────────────────────────────────────────────┐
│ 确定性编排 (n8n) vs 非确定性推理 (Agent 框架) │
├────────────────────────────────────────────────────────────┤
│ │
│ n8n: 确定性流程编排 │
│ ┌─────┐ ┌─────┐ ┌─────┐ ┌─────┐ │
│ │接收 │──>│分类 │──>│处理 │──>│通知 │ │
│ │邮件 │ │IF节点│ │分支 │ │Slack │ │
│ └─────┘ └─────┘ └─────┘ └─────┘ │
│ │
│ 特点: │
│ ├─ 路径确定:IF 条件 → 固定分支 │
│ ├─ 可预测:相同输入,相同输出 │
│ ├─ 易调试:每个节点的输入/输出都可见 │
│ └─ 可靠:一个节点失败,不会影响其他分支 │
│ │
│ Agent: 非确定性推理执行 │
│ ┌──────────────────────────────────────┐ │
│ │ AI Agent │ │
│ │ 输入: "处理这封客户邮件" │ │
│ │ │ │
│ │ Agent 自己决定: │ │
│ │ ├─ 调用什么工具? │ │
│ │ ├─ 走哪条路径? │ │
│ │ ├─ 需要几步完成? │ │
│ │ └─ 输出什么结果? │ │
│ └──────────────────────────────────────┘ │
│ │
│ 特点: │
│ ├─ 路径不确定:Agent 根据推理决定走哪条路 │
│ ├─ 不可预测:相同输入可能不同输出 │
│ ├─ 难调试:推理链路不透明 │
│ └─ 有风险:可能产生幻觉、错误决策 │
│ │
│ 最佳实践:混合使用 │
│ ├─ 确定性流程用 n8n 编排 │
│ ├─ 非确定性推理用 Agent 处理 │
│ └─ n8n 做整体流程控制,Agent 做局部智能决策 │
│ │
└────────────────────────────────────────────────────────────┘
核心洞察: n8n 不应该试图替代 Agent 框架,而是应该做 Agent 的"流程管家"——确定性流程由 n8n 控制,推理决策交给 Agent。
4. 实战1:AI驱动的客服工单处理流程
4.1 业务场景
电商客服每天处理数千条用户咨询,需要:
自动分类工单类型
常见问题自动回复
需要人工处理的自动转派
订单相关问题自动查询状态
4.2 工作流架构
plaintext
┌──────────────────────────────────────────────────────────────┐
│ AI 客服工单处理工作流 │
├──────────────────────────────────────────────────────────────┤
│ │
│ ┌──────────┐ │
│ │ Webhook │ 接收用户消息 │
│ │ (触发器) │ │
│ └────┬─────┘ │
│ │ │
│ ┌────▼──────────┐ │
│ │ AI Agent 节点 │ 意图识别 + 智能决策 │
│ │ (OpenAI GPT) │ │
│ └────┬──────────┘ │
│ │ │
│ ┌────▼─────┐ │
│ │ Switch │ 按意图分类 │
│ │ 节点 │ │
│ └─┬──┬──┬─┘ │
│ │ │ │ │
│ │ │ └──────────────┐ │
│ │ │ │ │
│ │ │ ┌──────▼──────┐ │
│ │ │ │ 创建工单 │ 转人工 │
│ │ │ │ + 通知Slack │ │
│ │ │ └─────────────┘ │
│ │ │ │
│ │ └────────────┐ │
│ │ │ │
│ │ ┌──────▼──────┐ │
│ │ │ 查询订单 │ 调用 ERP API │
│ │ │ HTTP请求 │ │
│ │ └──────┬──────┘ │
│ │ │ │
│ │ ┌──────▼──────┐ │
│ │ │ AI生成回复 │ 基于订单信息生成回复 │
│ │ └──────┬──────┘ │
│ │ │ │
│ │ │ │
│ └──────┐ │ │
│ │ │ │
│ ┌──────▼──────┐ │ │
│ │ RAG检索 │ │ 向量检索知识库 │
│ │ + AI生成回复│ │ │
│ └──────┬──────┘ │ │
│ │ │ │
│ ┌──────▼────────▼──┐ │
│ │ 发送回复 │ 统一回复用户 │
│ │ (邮件/Slack/API) │ │
│ └──────────────────┘ │
│ │
└──────────────────────────────────────────────────────────────┘
4.3 实现
步骤1:Webhook 触发器
json
{
"name": "接收客服消息",
"type": "n8n-nodes-base.webhook",
"parameters": {
"httpMethod": "POST",
"path": "customer-service",
"responseMode": "responseNode",
"options": {
"rawBody": false
}
}
}
python
# Webhook 接收的数据格式
{
"user_id": "u_12345",
"message": "我的订单 ORD-20260905 怎么还没发货?已经5天了",
"channel": "web_chat",
"session_id": "sess_abc"
}
步骤2:AI Agent 节点(意图识别)
json
{
"name": "意图识别",
"type": "@n8n/n8n-nodes-langchain.agent",
"parameters": {
"agent": "conversationalAgent",
"systemMessage": "你是一个客服意图识别助手。分析用户消息,返回以下JSON格式:\n\n{\"intent\": \"FAQ|ORDER|RETURN|TRANSFER\", \"confidence\": 0.95, \"entities\": {}}\n\n意图类型:\n- FAQ: 常见问题(产品咨询、使用方法、售后政策)\n- ORDER: 订单问题(查询状态、物流跟踪、退款进度)\n- RETURN: 退货/换货请求\n- TRANSFER: 需要人工处理的复杂问题\n\n只返回JSON,不要其他文字。",
"options": {
"temperature": 0.1
}
}
}
步骤3:Switch 分支
json
{
"name": "按意图分发",
"type": "n8n-nodes-base.switch",
"parameters": {
"dataType": "string",
"value1": "={{ JSON.parse($json.output).intent }}",
"rules": {
"rules": [
{
"value2": "FAQ",
"output": 0
},
{
"value2": "ORDER",
"output": 1
},
{
"value2": "RETURN",
"output": 2
},
{
"value2": "TRANSFER",
"output": 3
}
]
},
"fallbackOutput": 3
}
}
步骤4:FAQ 分支 - RAG 检索 + AI 回复
json
{
"name": "检索知识库",
"type": "@n8n/n8n-nodes-langchain.vectorStore",
"parameters": {
"operation": "retrieve",
"vectorStore": "postgres",
"postgres": {
"tableName": "knowledge_base",
"columns": {
"id": "id",
"content": "content",
"embedding": "embedding"
}
},
"options": {
"topK": 3,
"scoreThreshold": 0.75
}
}
}
json
{
"name": "生成FAQ回复",
"type": "@n8n/n8n-nodes-langchain.chainLlm",
"parameters": {
"prompt": "基于以下知识库内容回答用户问题。如果知识库中没有答案,说'我需要转接人工客服'。\n\n知识库内容:\n{{ $json.documents.map(d => d.content).join('\\n\\n') }}\n\n用户问题:{{ $('接收客服消息').item.json.message }}\n\n请用友好、专业的语气回答。",
"options": {
"temperature": 0.3
}
}
}
步骤5:ORDER 分支 - 查询订单
json
{
"name": "查询订单状态",
"type": "n8n-nodes-base.httpRequest",
"parameters": {
"method": "GET",
"url": "https://api.internal.company.com/orders/{{ JSON.parse($('意图识别').item.json.output).entities.order_id }}",
"authentication": "predefinedCredentialType",
"nodeCredentialType": "httpHeaderAuth",
"options": {
"timeout": 5000
}
}
}
步骤6:统一回复
json
{
"name": "发送回复",
"type": "n8n-nodes-base.httpRequest",
"parameters": {
"method": "POST",
"url": "https://api.internal.company.com/chat/reply",
"sendBody": true,
"bodyParameters": {
"parameters": [
{
"name": "user_id",
"value": "={{ $('接收客服消息').item.json.user_id }}"
},
{
"name": "message",
"value": "={{ $json.reply || $json.output }}"
},
{
"name": "session_id",
"value": "={{ $('接收客服消息').item.json.session_id }}"
}
]
}
}
}
4.4 用 n8n JSON 定义完整工作流
json
{
"name": "AI客服工单处理",
"nodes": [
{
"parameters": {
"httpMethod": "POST",
"path": "customer-service",
"responseMode": "lastNode"
},
"name": "接收客服消息",
"type": "n8n-nodes-base.webhook",
"position": [200, 300]
},
{
"parameters": {
"agent": "conversationalAgent",
"systemMessage": "意图识别助手。返回JSON: {\"intent\": \"FAQ|ORDER|RETURN|TRANSFER\", \"confidence\": 0.95, \"entities\": {}}"
},
"name": "意图识别",
"type": "@n8n/n8n-nodes-langchain.agent",
"position": [450, 300]
},
{
"parameters": {
"dataType": "string",
"value1": "={{ JSON.parse($json.output).intent }}",
"rules": {
"rules": [
{"value2": "FAQ", "output": 0},
{"value2": "ORDER", "output": 1},
{"value2": "RETURN", "output": 2},
{"value2": "TRANSFER", "output": 3}
]
},
"fallbackOutput": 3
},
"name": "按意图分发",
"type": "n8n-nodes-base.switch",
"position": [700, 300]
}
],
"connections": {
"接收客服消息": {
"main": [[{"node": "意图识别", "type": "main", "index": 0}]]
},
"意图识别": {
"main": [[{"node": "按意图分发", "type": "main", "index": 0}]]
}
}
}
5. 实战2:n8n + MCP 集成
据《Build Your First AI MCP Server with n8n》(https://n8n.blog/build-your-first-ai-mcp-server-with-n8n/),n8n 可以同时作为 MCP Server 和 MCP Client 使用:
5.1 n8n 作为 MCP Server
把 n8n 工作流暴露为 MCP 工具,让外部 AI Agent 可以调用:
plaintext
┌──────────────────────────────────────────────────────────┐
│ n8n 作为 MCP Server │
├──────────────────────────────────────────────────────────┤
│ │
│ 外部 AI Agent (Claude Code / Cursor / 任意) │
│ │ │
│ │ MCP 协议 (HTTP Streamable) │
│ ▼ │
│ ┌──────────────────┐ │
│ │ MCP Trigger 节点 │ 暴露为 MCP 工具 │
│ │ (Production URL) │ │
│ └────────┬─────────┘ │
│ │ │
│ ┌────────▼─────────┐ │
│ │ n8n 工作流逻辑 │ 你的业务逻辑 │
│ │ ├─ 数据库查询 │ │
│ │ ├─ API 调用 │ │
│ │ ├─ 文件处理 │ │
│ │ └─ 通知发送 │ │
│ └────────┬─────────┘ │
│ │ │
│ ┌────────▼─────────┐ │
│ │ 返回结构化结果 │ MCP 响应 │
│ └──────────────────┘ │
│ │
│ 安全优势: │
│ ├─ Agent 看不到你的 API Key 和凭证 │
│ ├─ Agent 只能调用你暴露的特定工具 │
│ └─ 所有调用都有审计日志 │
│ │
└──────────────────────────────────────────────────────────┘
创建 MCP Server 工作流
json
{
"name": "MCP Server - 用户管理工具",
"nodes": [
{
"parameters": {
"path": "user-mgmt-mcp",
"transport": "httpStream"
},
"name": "MCP Trigger",
"type": "@n8n/n8n-nodes-langchain.mcpTrigger",
"position": [200, 300]
},
{
"parameters": {
"rules": {
"rules": [
{
"operation": "equals",
"value1": "={{ $json.tool }}",
"value2": "search_users"
},
{
"operation": "equals",
"value1": "={{ $json.tool }}",
"value2": "get_user_details"
},
{
"operation": "equals",
"value1": "={{ $json.tool }}",
"value2": "update_user_status"
}
]
}
},
"name": "路由工具请求",
"type": "n8n-nodes-base.switch",
"position": [450, 300]
},
{
"parameters": {
"operation": "executeQuery",
"query": "SELECT id, name, email, status FROM users WHERE name ILIKE '%{{ $json.arguments.name }}%' LIMIT 10"
},
"name": "搜索用户",
"type": "n8n-nodes-base.postgres",
"position": [700, 200]
},
{
"parameters": {
"operation": "executeQuery",
"query": "SELECT * FROM users WHERE id = '{{ $json.arguments.user_id }}'"
},
"name": "获取用户详情",
"type": "n8n-nodes-base.postgres",
"position": [700, 400]
},
{
"parameters": {
"operation": "executeQuery",
"query": "UPDATE users SET status = '{{ $json.arguments.status }}' WHERE id = '{{ $json.arguments.user_id }}' RETURNING *"
},
"name": "更新用户状态",
"type": "n8n-nodes-base.postgres",
"position": [700, 600]
}
]
}
在 Claude Code 中使用 n8n MCP Server
bash
# ~/.claude/mcp_servers.json
{
"mcpServers": {
"user-management": {
"url": "https://n8n.company.com/webhook/user-mgmt-mcp",
"transport": "httpStream"
}
}
}
# 在 Claude Code 中
> 查找叫张三的用户
🔧 MCP: user-management.search_users({"name": "张三"})
| id | name | email | status |
|-----|------|----------------|---------|
| 42 | 张三 | zhang@test.com | active |
> 把张三的状态改为 inactive
🔧 MCP: user-management.update_user_status({"user_id": "42", "status": "inactive"})
✅ 用户张三状态已更新为 inactive
5.2 n8n 作为 MCP Client
n8n 的 AI Agent 节点可以调用外部 MCP Server 的工具:
plaintext
┌──────────────────────────────────────────────────────────┐
│ n8n AI Agent 调用外部 MCP Server │
├──────────────────────────────────────────────────────────┤
│ │
│ ┌──────────┐ ┌───────────┐ ┌───────────────┐ │
│ │ Webhook │────>│ AI Agent │────>│ MCP Client │ │
│ │ 触发器 │ │ 节点 │ │ 工具节点 │ │
│ └──────────┘ └───────────┘ └───────┬───────┘ │
│ │ │
│ MCP 协议 (HTTP Streamable) │
│ │ │
│ ┌──────────▼────────┐ │
│ │ 外部 MCP Server │ │
│ │ ├─ Brave Search │ │
│ │ ├─ GitHub │ │
│ │ ├─ Slack │ │
│ │ └─ 自定义工具 │ │
│ └───────────────────┘ │
│ │
└──────────────────────────────────────────────────────────┘
配置 MCP Client 节点
bash
# 安装 n8n MCP Client 社区节点
# 在 n8n 界面:Settings → Community Nodes → Install
# 包名:n8n-nodes-mcp-client
# 或通过环境变量安装
export N8N_COMMUNITY_PACKAGES_ALLOW_TOOL_USAGE=true
json
{
"name": "AI Agent + MCP",
"nodes": [
{
"parameters": {
"httpMethod": "POST",
"path": "ai-mcp-agent"
},
"name": "Webhook",
"type": "n8n-nodes-base.webhook",
"position": [200, 300]
},
{
"parameters": {
"agent": "toolsAgent",
"systemMessage": "你是一个研究助手,可以搜索互联网、查询 GitHub、发送 Slack 消息。",
"tools": {
"toolNames": ["MCP Client"],
"toolDescriptions": "使用 MCP 工具搜索信息和执行操作"
}
},
"name": "AI Agent",
"type": "@n8n/n8n-nodes-langchain.agent",
"position": [450, 300]
},
{
"parameters": {
"operation": "executeTool",
"serverUrl": "https://mcp.brave.com/sse",
"toolName": "brave_web_search",
"toolArguments": "={{ $json.arguments }}"
},
"name": "MCP Client - Brave Search",
"type": "n8n-nodes-mcp-client",
"position": [700, 200]
},
{
"parameters": {
"operation": "executeTool",
"serverUrl": "https://mcp.github.com/sse",
"toolName": "search_repositories",
"toolArguments": "={{ $json.arguments }}"
},
"name": "MCP Client - GitHub",
"type": "n8n-nodes-mcp-client",
"position": [700, 400]
}
]
}
6. AI Agent 节点深入
6.1 ReAct 循环
n8n 的 AI Agent 节点实现了 ReAct(Reasoning + Acting)循环:
plaintext
┌──────────────────────────────────────────────────────────┐
│ ReAct 循环 │
├──────────────────────────────────────────────────────────┤
│ │
│ ┌─────────────┐ │
│ │ 用户输入 │ │
│ └──────┬──────┘ │
│ │ │
│ ┌────▼────┐ │
│ │ Thought │ Agent 思考:我需要什么信息? │
│ └────┬────┘ │
│ │ │
│ ┌────▼────┐ │
│ │ Action │ Agent 选择工具并执行 │
│ └────┬────┘ │
│ │ │
│ ┌────▼────┐ │
│ │Observation│ 工具返回结果 │
│ └────┬────┘ │
│ │ │
│ ┌────▼────┐ │
│ │ Thought │ Agent 继续思考:信息够了吗? │
│ └────┬────┘ │
│ │ │
│ ├─── 信息不够 ──> 回到 Action,调用更多工具 │
│ │ │
│ └─── 信息够了 ──> 生成最终回答 │
│ │ │
│ ┌────▼──────┐ │
│ │ 最终回答 │ │
│ └───────────┘ │
│ │
│ 最多循环次数:可配置(默认 10 次) │
│ │
└──────────────────────────────────────────────────────────┘
6.2 工具调用
n8n AI Agent 可以使用多种类型的工具:
plaintext
┌──────────────────────────────────────────────────────────┐
│ AI Agent 可用工具类型 │
├──────────────────────────────────────────────────────────┤
│ │
│ 1. 内置 n8n 节点作为工具 │
│ ├─ HTTP Request → 让 Agent 调用任何 REST API │
│ ├─ PostgreSQL → 让 Agent 查询数据库 │
│ ├─ Code Node → 让 Agent 执行 JS/Python 代码 │
│ └─ 任何 n8n 节点都可以被 Agent 调用 │
│ │
│ 2. 自定义工具工作流 │
│ ├─ 创建子工作流,实现特定业务逻辑 │
│ ├─ 通过 "Execute Workflow" 节点作为工具暴露 │
│ └─ Agent 只看到工具的描述和参数,不看到内部逻辑 │
│ │
│ 3. MCP 工具 │
│ ├─ 连接外部 MCP Server │
│ ├─ 自动发现可用工具 │
│ └─ 调用 MCP 工具获取信息或执行操作 │
│ │
│ 4. 前端工具 (CopilotKit) │
│ ├─ 通过 AG-UI 协议暴露前端组件 │
│ ├─ Agent 可以触发 UI 更新 │
│ └─ 支持 Human-in-the-Loop 审批 │
│ │
└──────────────────────────────────────────────────────────┘
6.3 记忆管理
n8n AI Agent 的记忆是局限的——默认情况下,每次工作流执行都是无状态的。要实现跨执行的记忆,需要额外配置:
json
{
"name": "带记忆的AI Agent",
"nodes": [
{
"parameters": {
"agent": "conversationalAgent",
"systemMessage": "你是一个有记忆的客服助手。",
"memory": {
"type": "postgres",
"sessionKey": "={{ $json.session_id }}",
"tableName": "chat_memory"
}
},
"name": "AI Agent",
"type": "@n8n/n8n-nodes-langchain.agent"
}
]
}
plaintext
┌──────────────────────────────────────────────────────────┐
│ 记忆管理策略 │
├──────────────────────────────────────────────────────────┤
│ │
│ 无记忆(默认) │
│ ├─ 每次执行独立 │
│ ├─ 适合:一次性任务(分类、提取、生成) │
│ └─ 缺点:多轮对话无法保持上下文 │
│ │
│ 会话记忆(Conversational Memory) │
│ ├─ 用 session_id 关联对话历史 │
│ ├─ 存储在 PostgreSQL / Redis 中 │
│ ├─ 适合:多轮客服对话 │
│ └─ 注意:对话过长会超出上下文窗口 │
│ │
│ 摘要记忆(Summary Memory) │
│ ├─ 每轮对话后生成摘要 │
│ ├─ 用摘要替代完整历史 │
│ ├─ 适合:长对话场景 │
│ └─ 注意:摘要会丢失细节 │
│ │
│ 向量记忆(Vector Store Memory) │
│ ├─ 对话历史存入向量数据库 │
│ ├─ 检索相关记忆片段 │
│ ├─ 适合:大规模知识回忆 │
│ └─ 注意:延迟较高 │
│ │
└──────────────────────────────────────────────────────────┘
7. n8n 与专用 Agent 框架的协作
n8n 不是 Agent 框架的替代品,而是协作伙伴。最佳实践是n8n 做确定性流程编排,Agent 框架做推理决策:
plaintext
┌────────────────────────────────────────────────────────────┐
│ n8n + Agent 框架协作架构 │
├────────────────────────────────────────────────────────────┤
│ │
│ ┌──────────────────────────────────────────────┐ │
│ │ n8n (确定性编排层) │ │
│ │ ├─ Webhook 接收请求 │ │
│ │ ├─ 数据预处理(格式化、校验、清洗) │ │
│ │ ├─ 流程控制(分支、循环、超时) │ │
│ │ ├─ 错误处理(重试、降级、通知) │ │
│ │ ├─ 结果后处理(格式化、存储、通知) │ │
│ │ └─ 审计日志 │ │
│ └──────────────┬───────────────────────────────┘ │
│ │ │
│ 需要推理决策时调用 │
│ │ │
│ ┌──────────────▼───────────────────────────────┐ │
│ │ Agent 框架 (推理层) │ │
│ │ ├─ LangGraph Agent: 复杂推理、多步骤任务 │ │
│ │ ├─ CrewAI: 多 Agent 协作 │ │
│ │ ├─ Claude Code: 代码生成/修改 │ │
│ │ └─ 自定义 Agent: 垂直领域专用 │ │
│ └──────────────────────────────────────────────┘ │
│ │
│ 通信方式: │
│ ├─ n8n HTTP Request → Agent API 端点 │
│ ├─ n8n MCP Client → MCP Server (Agent 暴露) │
│ └─ n8n Webhook ← Agent 回调 │
│ │
└────────────────────────────────────────────────────────────┘
7.1 n8n + LangGraph 协作示例
json
{
"name": "n8n + LangGraph 协作",
"nodes": [
{
"parameters": {
"httpMethod": "POST",
"path": "research-pipeline"
},
"name": "接收研究请求",
"type": "n8n-nodes-base.webhook"
},
{
"parameters": {
"method": "POST",
"url": "http://langgraph-agent:8000/api/copilotkit",
"sendBody": true,
"bodyParameters": {
"parameters": [
{"name": "thread_id", "value": "={{ $json.session_id }}"},
{"name": "messages", "value": "=[{\"role\": \"user\", \"content\": \"{{ $json.query }}\"}]"}
]
}
},
"name": "调用LangGraph Agent",
"type": "n8n-nodes-base.httpRequest"
},
{
"parameters": {
"conditions": {
"string": [{
"value1": "={{ $json.status }}",
"operation": "equals",
"value2": "completed"
}]
}
},
"name": "检查结果",
"type": "n8n-nodes-base.if"
},
{
"parameters": {
"method": "POST",
"url": "https://hooks.slack.com/services/xxx",
"sendBody": true,
"bodyParameters": {
"parameters": [
{"name": "text", "value": "研究完成:={{ $('调用LangGraph Agent').item.json.result }}"}
]
}
},
"name": "通知Slack",
"type": "n8n-nodes-base.httpRequest"
}
]
}
8. 自托管部署
8.1 Docker Compose 部署
yaml
# docker-compose.yml
version: '3.8'
services:
postgres:
image: postgres:16
environment:
POSTGRES_DB: n8n
POSTGRES_USER: n8n
POSTGRES_PASSWORD: ${DB_PASSWORD}
volumes:
- postgres_data:/var/lib/postgresql/data
- ./init.sql:/docker-entrypoint-initdb.d/init.sql
ports:
- "5432:5432"
healthcheck:
test: ["CMD-SHELL", "pg_isready -U n8n"]
interval: 10s
timeout: 5s
retries: 5
# 启用 pgvector 扩展(向量搜索支持)
# init.sql 内容:
# CREATE EXTENSION IF NOT EXISTS vector;
redis:
image: redis:7-alpine
command: redis-server --requirepass ${REDIS_PASSWORD}
volumes:
- redis_data:/data
ports:
- "6379:6379"
n8n:
image: n8nio/n8n:2.6.3
environment:
# 基础配置
- DB_TYPE=postgresdb
- DB_POSTGRESDB_HOST=postgres
- DB_POSTGRESDB_PORT=5432
- DB_POSTGRESDB_DATABASE=n8n
- DB_POSTGRESDB_USER=n8n
- DB_POSTGRESDB_PASSWORD=${DB_PASSWORD}
# Redis 队列(高并发)
- QUEUE_BULL_REDIS_HOST=redis
- QUEUE_BULL_REDIS_PASSWORD=${REDIS_PASSWORD}
- EXECUTIONS_MODE=queue
# AI 相关配置
- N8N_COMMUNITY_PACKAGES_ALLOW_TOOL_USAGE=true
- N8N_AI_OPENAI_API_KEY=${OPENAI_API_KEY}
# 安全配置
- N8N_BASIC_AUTH_ACTIVE=true
- N8N_BASIC_AUTH_USER=admin
- N8N_BASIC_AUTH_PASSWORD=${ADMIN_PASSWORD}
# 性能配置
- EXECUTIONS_TIMEOUT=3600
- EXECUTIONS_TIMEOUT_MAX=7200
- GENERIC_TIMEZONE=Asia/Shanghai
volumes:
- n8n_data:/home/node/.n8n
ports:
- "5678:5678"
depends_on:
postgres:
condition: service_healthy
redis:
condition: service_started
# n8n Worker(处理队列任务)
n8n-worker:
image: n8nio/n8n:2.6.3
command: worker
environment:
- DB_TYPE=postgresdb
- DB_POSTGRESDB_HOST=postgres
- DB_POSTGRESDB_PORT=5432
- DB_POSTGRESDB_DATABASE=n8n
- DB_POSTGRESDB_USER=n8n
- DB_POSTGRESDB_PASSWORD=${DB_PASSWORD}
- QUEUE_BULL_REDIS_HOST=redis
- QUEUE_BULL_REDIS_PASSWORD=${REDIS_PASSWORD}
- N8N_COMMUNITY_PACKAGES_ALLOW_TOOL_USAGE=true
volumes:
- n8n_data:/home/node/.n8n
depends_on:
- postgres
- redis
volumes:
postgres_data:
redis_data:
n8n_data:
8.2 初始化数据库
sql
-- init.sql
-- 启用 pgvector 扩展(用于向量搜索/RAG)
CREATE EXTENSION IF NOT EXISTS vector;
-- 创建知识库表
CREATE TABLE IF NOT EXISTS knowledge_base (
id SERIAL PRIMARY KEY,
content TEXT NOT NULL,
embedding vector(1536), -- OpenAI text-embedding-3-small 维度
category VARCHAR(100),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
-- 创建向量索引(IVFFlat,适合中等规模数据)
CREATE INDEX IF NOT EXISTS kb_embedding_idx
ON knowledge_base USING ivfflat (embedding vector_cosine_ops)
WITH (lists = 100);
-- 创建对话记忆表
CREATE TABLE IF NOT EXISTS chat_memory (
id SERIAL PRIMARY KEY,
session_id VARCHAR(255) NOT NULL,
role VARCHAR(50) NOT NULL,
content TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS chat_memory_session_idx
ON chat_memory (session_id, created_at);
8.3 监控配置
yaml
# 在 docker-compose.yml 中添加监控服务
prometheus:
image: prom/prometheus
volumes:
- ./prometheus.yml:/etc/prometheus/prometheus.yml
ports:
- "9090:9090"
grafana:
image: grafana/grafana
ports:
- "3000:3000"
environment:
- GF_SECURITY_ADMIN_PASSWORD=${GRAFANA_PASSWORD}
yaml
# prometheus.yml
global:
scrape_interval: 15s
scrape_configs:
- job_name: 'n8n'
static_configs:
- targets: ['n8n:5678']
metrics_path: /metrics
9. 生产场景
9.1 数据 ETL + AI 分析
plaintext
┌──────────────────────────────────────────────────────────┐
│ 场景:每日销售数据 ETL + AI 分析报告 │
├──────────────────────────────────────────────────────────┤
│ │
│ Cron (每天 8:00) │
│ │ │
│ ▼ │
│ 从 ERP 系统拉取销售数据 (HTTP Request) │
│ │ │
│ ▼ │
│ 数据清洗和转换 (Code Node - Python) │
│ ├─ 去重、格式化、异常值处理 │
│ └─ 存入 PostgreSQL │
│ │ │
│ ▼ │
│ AI 分析 (OpenAI Node) │
│ ├─ 趋势分析 │
│ ├─ 异常检测 │
│ └─ 预测建议 │
│ │ │
│ ▼ │
│ 生成报告 (Code Node) │
│ ├─ Markdown 格式报告 │
│ └─ 关键指标摘要 │
│ │ │
│ ▼ │
│ 分发 (并行) │
│ ├─ 发送邮件给管理层 │
│ ├─ 更新 Notion 文档 │
│ └─ 发送 Slack 摘要 │
│ │
│ n8n 负责:数据拉取、清洗、分发(确定性流程) │
│ AI 负责:趋势分析、异常检测、预测(非确定性推理) │
│ │
└──────────────────────────────────────────────────────────┘
9.2 多系统联动
plaintext
┌──────────────────────────────────────────────────────────┐
│ 场景:新员工入职自动化 │
├──────────────────────────────────────────────────────────┤
│ │
│ HR 系统 Webhook → 员工入职事件 │
│ │ │
│ ▼ │
│ n8n 编排(确定性流程): │
│ ├─ 创建企业邮箱 (Google Workspace API) │
│ ├─ 创建 Slack 账号 + 加入频道 │
│ ├─ 创建 GitHub 账号 + 加入组织 │
│ ├─ 分配 Jira 权限 │
│ ├─ 创建 VPN 凭证 │
│ └─ 发送欢迎邮件 │
│ │ │
│ ▼ │
│ AI 增强(非确定性推理): │
│ ├─ 根据部门生成个性化 Onboarding 指南 │
│ ├─ 推荐相关培训课程 │
│ └─ 生成常见问题 FAQ │
│ │ │
│ ▼ │
│ 通知 HR 系统入职完成 │
│ │
└──────────────────────────────────────────────────────────┘
9.3 定时报告生成
plaintext
┌──────────────────────────────────────────────────────────┐
│ 场景:周度项目进度报告 │
├──────────────────────────────────────────────────────────┤
│ │
│ Cron (每周一 9:00) │
│ │ │
│ ▼ │
│ 收集数据(并行): │
│ ├─ GitHub: 本周 PR 数量、代码行数 │
│ ├─ Jira: 本周完成/进行中的任务 │
│ ├─ Slack: 关键讨论摘要 │
│ └─ CI/CD: 部署次数和成功率 │
│ │ │
│ ▼ │
│ Merge 数据 │
│ │ │
│ ▼ │
│ AI 生成报告: │
│ ├─ 进度总结 │
│ ├─ 风险提示 │
│ ├─ 下周建议 │
│ └─ 格式化为 Markdown │
│ │ │
│ ▼ │
│ 分发: │
│ ├─ 更新 Confluence 页面 │
│ ├─ 发送邮件给项目干系人 │
│ └─ Slack 通知 │
│ │
└──────────────────────────────────────────────────────────┘
10. 踩坑记录
坑1:AI Agent 节点的上下文窗口限制
问题: n8n 的 AI Agent 节点默认上下文窗口有限,长对话容易截断。
plaintext
症状:
- 多轮对话后 Agent "忘记"之前的上下文
- 复杂任务步骤超过 10 轮后被截断
- 工具调用的结果太长导致 token 溢出
解决方案:
1. 配置 Summary Memory,对话过长时自动摘要
2. 限制工具返回结果的长度
3. 在 system prompt 中明确告知 Agent 上下文限制
4. 拆分复杂任务为多个工作流
坑2:Vector Store 节点的维度不匹配
问题: pgvector 表的向量维度和 Embedding 模型输出的维度不一致。
sql
-- ❌ 错误:表定义 1536 维,但用了 1024 维的模型
CREATE TABLE knowledge_base (
embedding vector(1536) -- 但 voyage-3 输出 1024 维
);
-- ✅ 正确:确保维度一致
-- 如果用 OpenAI text-embedding-3-small: 1536 维
-- 如果用 voyage-3: 1024 维
-- 如果用 BGE-M3: 1024 维
-- 修改表结构
ALTER TABLE knowledge_base
ALTER COLUMN embedding TYPE vector(1024);
坑3:MCP Server Trigger 的 Production URL 问题
问题: MCP Trigger 节点的 Production URL 只在工作流激活后才生成,开发时无法测试。
plaintext
解决方案:
1. 先保存工作流(不激活)
2. 在 n8n 界面点击 "Test workflow"
3. 使用测试模式的 Webhook URL 进行调试
4. 调试完成后激活工作流
5. 复制 Production URL 配置给 MCP Client
注意:测试 URL 和 Production URL 不同!
测试 URL: https://n8n.example.com/webhook-test/user-mgmt-mcp
生产 URL: https://n8n.example.com/webhook/user-mgmt-mcp
坑4:工作流执行超时
问题: AI Agent 节点执行时间过长,超过 n8n 默认超时时间。
yaml
# docker-compose.yml 修改超时配置
environment:
- EXECUTIONS_TIMEOUT=3600 # 单次执行最大 1 小时
- EXECUTIONS_TIMEOUT_MAX=7200 # 绝对最大 2 小时
json
// 在工作流设置中也可以配置
{
"settings": {
"executionTimeout": 1800, // 此工作流超时 30 分钟
"saveManualExecutions": true,
"saveDataErrorExecution": "all"
}
}
坑5:AI Agent 的不可预测输出
问题: AI Agent 的输出格式不稳定,导致下游节点解析失败。
plaintext
症状:
- Agent 应该返回 JSON,但有时返回自然语言
- Switch 节点匹配不到 Agent 的意图输出
- 下游节点收到非预期格式的数据
解决方案:
1. 使用 Output Parser 节点强制 Agent 输出 JSON
2. 在 system prompt 中明确格式要求:
"你必须且只能返回以下 JSON 格式:{\"intent\": \"...\", \"data\": {...}}"
3. 在 Agent 和下游节点之间加一个 Code 节点做格式校验和修复
4. 增加重试逻辑(如果 Agent 输出格式不对,重新调用)
json
{
"name": "格式校验",
"type": "n8n-nodes-base.code",
"parameters": {
"language": "javaScript",
"jsCode": "const output = $input.first().json;\n\ntry {\n // 尝试解析 JSON\n if (typeof output.text === 'string') {\n const parsed = JSON.parse(output.text);\n return { json: parsed };\n }\n return { json: output };\n} catch (e) {\n // 解析失败,返回默认值\n return { json: { intent: 'TRANSFER', confidence: 0, raw: output.text } };\n}"
}
}
坑6:PostgreSQL 连接数耗尽
问题: 大量工作流并行执行时,PostgreSQL 连接数不够。
sql
-- 检查当前连接数
SELECT count(*) FROM pg_stat_activity;
-- 修改最大连接数
ALTER SYSTEM SET max_connections = 200;
yaml
# n8n 配置数据库连接池
environment:
- DB_POSTGRESDB_POOL_SIZE=20 # 连接池大小
坑7:n8n 社区节点兼容性
问题: n8n-nodes-mcp-client 等社区节点升级后不兼容。
plaintext
解决方案:
1. 锁定社区节点版本
2. 升级前在测试环境验证
3. 关注 n8n 社区公告
# 安装指定版本
# Settings → Community Nodes → Install
# 指定版本号:n8n-nodes-mcp-client@1.2.3
11. 总结
n8n + AI 的核心价值
确定性 + 非确定性的最佳组合:n8n 做流程编排,AI 做推理决策
MCP 双向集成:既可以暴露工具给外部 Agent,也可以调用外部 MCP Server
开源 + 自托管:数据不出你的网络,满足合规要求
低门槛 + 高灵活:拖拽式构建,需要时可以写代码
n8n 不擅长的事
复杂 Agent 推理:n8n 的 AI Agent 不如 LangGraph/CrewAI 灵活
长时间运行的任务:超时限制,不如独立 Agent 服务稳定
精细的 Agent 控制:没有 checkpoint、没有流式中间结果、没有 agent-to-agent 通信
高并发场景:单实例 n8n 处理并发有限,需要 worker 模式
什么时候用 n8n,什么时候用 Agent 框架?
表格
最终建议: n8n 是 AI Agent 的"流程管家",不是 Agent 本身。把确定性流程交给 n8n,把推理决策交给 Agent,两者协作才是正道。
n8n 不是要替代 Agent 框架,而是要做 Agent 的流程基础设施。确定性编排用 n8n,非确定性推理用 Agent,这才是 2026 年自动化系统的正确打开方式。
——PySuper | zhengxingtao.com
参考链接:
评论区