工作流(Workflow)—— 可视化 AI 应用编排

工作流平台让 AI 应用开发从代码编写转变为可视化编排,大大降低了开发门槛。


4.1 工作流平台对比

平台 定位 特点 适用场景 Stars
n8n 通用自动化 开源、400+ 节点、自托管 IT 自动化、数据管道 50k+
Dify AI 原生应用 RAG、Agent、工作流一体化 AI 应用开发 50k+
Flowise LLM 可视化 低代码、拖拽式 快速原型 35k+
LangFlow LangChain 可视化 与 LangChain 无缝集成 开发者友好 40k+

平台选型决策树

复制代码
┌─────────────────────────────────────────────────────────┐
│                  工作流平台选型                          │
├─────────────────────────────────────────────────────────┤
│                                                         │
│  主要需求是什么?                                        │
│       │                                                 │
│       ├── AI 应用开发 ──▶ 需要企业级功能?              │
│       │                      │                          │
│       │                      ├── 是 ──▶ Dify           │
│       │                      │                          │
│       │                      └── 否 ──▶ Flowise        │
│       │                                                 │
│       ├── 通用自动化 ──▶ n8n                           │
│       │                                                 │
│       └── LangChain 可视化 ──▶ LangFlow               │
│                                                         │
└─────────────────────────────────────────────────────────┘

4.2 Dify 深度解析

架构概览

复制代码
┌─────────────────────────────────────────────────────────┐
│                     Dify 架构                            │
├─────────────────────────────────────────────────────────┤
│                                                         │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐    │
│  │  工作流编排  │  │  知识库管理  │  │  应用管理   │    │
│  └─────────────┘  └─────────────┘  └─────────────┘    │
│         │               │                │             │
│         └───────────────┴────────────────┘             │
│                         │                               │
│  ┌──────────────────────▼──────────────────────┐       │
│  │              核心引擎                        │       │
│  │  • LLM 调度   • RAG Pipeline              │       │
│  │  • 工具调用   • 变量管理                  │       │
│  └─────────────────────────────────────────────┘       │
│                         │                               │
│  ┌──────────────────────▼──────────────────────┐       │
│  │              数据层                          │       │
│  │  PostgreSQL  │  Redis  │  Vector DB        │       │
│  └─────────────────────────────────────────────┘       │
└─────────────────────────────────────────────────────────┘

工作流节点类型

yaml 复制代码
节点类型:
  基础节点:
    - 开始节点: 工作流入口,定义输入变量
    - 结束节点: 工作流出口,定义输出格式

  LLM 节点:
    - 大模型调用: 调用 GPT/Claude/Gemini 等
    - 参数: model, prompt, temperature, max_tokens

  知识库节点:
    - 知识检索: 从向量库检索相关内容
    - 参数: dataset_id, query, top_k, score_threshold

  工具节点:
    - HTTP 请求: 调用外部 API
    - 代码执行: 运行 Python/JavaScript
    - 内置工具: 天气、搜索、计算器等

  逻辑节点:
    - 条件分支: if-else 判断
    - 迭代: 循环处理数组
    - 并行: 多任务同时执行

  变换节点:
    - 变量聚合: 合并多个变量
    - 模板转换: 格式化输出
    - 变量读取: 提取 JSON 字段

Dify 应用类型

类型 说明 适用场景
聊天助手 多轮对话应用 客服、咨询
文本生成 单次文本生成 内容创作、翻译
Agent 自主决策执行 复杂任务自动化
工作流 编排式应用 业务流程自动化

4.3 实战案例:智能合同审查工作流

业务场景

构建一个合同审查工作流,实现:

  1. 合同文本解析(PDF → 文本)
  2. 关键条款提取(LLM 分析)
  3. 风险点识别(知识库 + 规则)
  4. 生成审查报告(模板渲染)

工作流设计

markdown 复制代码
开始 ──▶ 文档解析 ──▶ 条款提取 ──▶ 知识检索 ──▶ 风险分析 ──▶ 报告生成 ──▶ 结束
                                            │
                                            ▼
                                        规则引擎

Dify 工作流 DSL 配置

yaml 复制代码
# contract_review_workflow.yaml
app:
  mode: workflow
  name: 智能合同审查

workflow:
  graph:
    nodes:
      # 开始节点
      - id: start
        type: start
        data:
          variables:
            - variable: contract_file
              type: file
              label: 合同文件
              required: true
            - variable: contract_type
              type: select
              label: 合同类型
              options:
                - 销售合同
                - 服务合同
                - 劳动合同
                - 其他

      # 文档解析节点
      - id: document_parser
        type: code
        data:
          code_language: python3
          code: |
            import pdfplumber
            import json

            def main(contract_file):
                """解析合同文件"""
                text = ""
                with pdfplumber.open(contract_file) as pdf:
                    for page in pdf.pages:
                        text += page.extract_text() or ""

                return {
                    "content": text,
                    "page_count": len(pdf.pages)
                }
          variables:
            - variable: contract_file
              value_selector: ["start", "contract_file"]

      # 条款提取节点
      - id: clause_extractor
        type: llm
        data:
          model:
            provider: openai
            name: gpt-4
            completion_params:
              temperature: 0.1
              max_tokens: 4000
          prompt:
            type: template
            template: |
              你是一位资深法务专家,请分析以下合同文本,提取关键条款。

              合同类型:{{contract_type}}
              合同内容:
              {{document_content}}

              请以 JSON 格式输出以下条款:
              1. contract_parties: 合同双方信息
              2. contract_amount: 合同金额
              3. contract_period: 履行期限
              4. breach_clause: 违约条款
              5. dispute_resolution: 争议解决方式
              6. special_terms: 特殊条款

              输出格式:
              ```json
              {
                "contract_parties": {...},
                "contract_amount": {...},
                ...
              }
yaml 复制代码
      variables:
        - variable: contract_type
          value_selector: ["start", "contract_type"]
        - variable: document_content
          value_selector: ["document_parser", "content"]

  # 知识检索节点
  - id: knowledge_retrieval
    type: knowledge-retrieval
    data:
      dataset_ids: ["legal_knowledge_base_id"]
      query_selector: ["document_parser", "content"]
      retrieval_mode: hybrid  # 关键词 + 向量
      top_k: 5
      score_threshold: 0.7

  # 风险分析节点
  - id: risk_analyzer
    type: llm
    data:
      model:
        provider: openai
        name: gpt-4
      prompt:
        type: template
        template: |
          作为法律风险顾问,请基于以下信息分析合同风险。

          ## 提取的条款
          {{clauses}}

          ## 相关法律知识
          {{knowledge}}

          ## 合同类型
          {{contract_type}}

          请识别以下风险并评分(高/中/低):

          1. 法律合规风险
             - 评估依据
             - 风险等级
             - 建议措施

          2. 商业风险
             - 评估依据
             - 风险等级
             - 建议措施

          3. 操作风险
             - 评估依据
             - 风险等级
             - 建议措施

          输出为 JSON 格式。
      variables:
        - variable: clauses
          value_selector: ["clause_extractor", "text"]
        - variable: knowledge
          value_selector: ["knowledge_retrieval", "result"]
        - variable: contract_type
          value_selector: ["start", "contract_type"]

  # 报告生成节点
  - id: report_generator
    type: template-transform
    data:
      template: |
        # 合同审查报告

        ## 一、基本信息

        | 项目 | 内容 |
        |------|------|
        | 合同类型 | {{contract_type}} |
        | 页数 | {{page_count}} |
        | 审查时间 | {{current_time}} |

        ## 二、条款摘要

        {{clauses_summary}}

        ## 三、风险分析

        {{risk_analysis}}

        ## 四、审查建议

        {{recommendations}}

        ---
        *本报告由 AI 合同审查助手生成,仅供参考,不构成法律意见。*
      variables:
        - variable: contract_type
          value_selector: ["start", "contract_type"]
        - variable: page_count
          value_selector: ["document_parser", "page_count"]
        - variable: clauses_summary
          value_selector: ["clause_extractor", "text"]
        - variable: risk_analysis
          value_selector: ["risk_analyzer", "text"]

  # 结束节点
  - id: end
    type: end
    data:
      outputs:
        - variable: report
          value_selector: ["report_generator", "output"]

# 连接边
edges:
  - source: start
    target: document_parser
  - source: document_parser
    target: clause_extractor
  - source: clause_extractor
    target: knowledge_retrieval
  - source: knowledge_retrieval
    target: risk_analyzer
  - source: risk_analyzer
    target: report_generator
  - source: report_generator
    target: end
yaml 复制代码
---

## 4.4 n8n:通用自动化平台

### 核心优势

| 特性 | 说明 |
|------|------|
| **开源免费** | 可自托管,数据完全掌控 |
| **400+ 节点** | 覆盖主流 SaaS 服务 |
| **分支与合并** | 支持复杂逻辑流 |
| **错误处理** | 内置重试和异常处理 |
| **Webhook 触发** | 支持 API 触发 |

### 实战案例:自动化内容发布流程

┌─────────────────────────────────────────────────────────┐ │ 自动内容发布工作流 │ ├─────────────────────────────────────────────────────────┤ │ │ │ 定时触发 ──▶ AI 生成 ──▶ 图片生成 ──▶ 内容审核 │ │ │ │ │ ┌────────────┴────────┐ │ │ │ │ │ │ ▼ ▼ │ │ 发布成功 发布失败 │ │ │ │ │ │ ▼ ▼ │ │ 通知用户 错误日志 │ └─────────────────────────────────────────────────────────┘

swift 复制代码
### n8n 工作流配置

```json
{
  "name": "自动内容发布",
  "nodes": [
    {
      "name": "定时触发",
      "type": "n8n-nodes-base.scheduleTrigger",
      "position": [250, 300],
      "parameters": {
        "rule": {
          "interval": [{"field": "hours", "hoursInterval": 6}]
        }
      }
    },
    {
      "name": "生成主题",
      "type": "n8n-nodes-base.httpRequest",
      "position": [450, 300],
      "parameters": {
        "url": "https://api.openai.com/v1/chat/completions",
        "method": "POST",
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "openAiApi",
        "sendBody": true,
        "bodyParameters": {
          "parameters": [
            {"name": "model", "value": "gpt-4"},
            {"name": "messages", "value": "[{\"role\": \"user\", \"content\": \"生成一个AI领域的热点话题\"}]"}
          ]
        }
      }
    },
    {
      "name": "内容生成",
      "type": "n8n-nodes-base.httpRequest",
      "position": [650, 300],
      "parameters": {
        "url": "https://api.openai.com/v1/chat/completions",
        "method": "POST",
        "sendBody": true,
        "bodyParameters": {
          "parameters": [
            {"name": "model", "value": "gpt-4"},
            {"name": "messages", "value": "={{[{\"role\": \"system\", \"content\": \"你是内容创作专家\"}, {\"role\": \"user\", \"content\": $json.choices[0].message.content}]}"}"}
          ]
        }
      }
    },
    {
      "name": "图片生成",
      "type": "n8n-nodes-base.httpRequest",
      "position": [850, 300],
      "parameters": {
        "url": "https://api.openai.com/v1/images/generations",
        "method": "POST",
        "sendBody": true,
        "bodyParameters": {
          "parameters": [
            {"name": "prompt", "value": "={{$json.choices[0].message.content}}"},
            {"name": "size", "value": "1024x1024"}
          ]
        }
      }
    },
    {
      "name": "内容审核",
      "type": "n8n-nodes-base.httpRequest",
      "position": [1050, 300],
      "parameters": {
        "url": "https://api.openai.com/v1/moderations",
        "method": "POST",
        "sendBody": true,
        "bodyParameters": {
          "parameters": [
            {"name": "input", "value": "={{$json.choices[0].message.content}}"}
          ]
        }
      }
    },
    {
      "name": "条件判断",
      "type": "n8n-nodes-base.if",
      "position": [1250, 300],
      "parameters": {
        "conditions": {
          "boolean": [
            {"value1": "={{$json.results[0].flagged}}", "value2": false}
          ]
        }
      }
    },
    {
      "name": "发布内容",
      "type": "n8n-nodes-base.httpRequest",
      "position": [1450, 200],
      "parameters": {
        "url": "https://api.your-platform.com/publish",
        "method": "POST",
        "sendBody": true,
        "bodyParameters": {
          "parameters": [
            {"name": "title", "value": "AI 趋势洞察"},
            {"name": "content", "value": "={{$json.content}}"},
            {"name": "image", "value": "={{$json.image_url}}"}
          ]
        }
      }
    },
    {
      "name": "发送通知",
      "type": "n8n-nodes-base.slack",
      "position": [1650, 200],
      "parameters": {
        "channel": "#content-updates",
        "text": "内容发布成功!"
      }
    },
    {
      "name": "记录错误",
      "type": "n8n-nodes-base.httpRequest",
      "position": [1450, 400],
      "parameters": {
        "url": "https://api.logging-service.com/error",
        "method": "POST",
        "sendBody": true,
        "bodyParameters": {
          "parameters": [
            {"name": "error", "value": "内容审核不通过"},
            {"name": "timestamp", "value": "={{$now}}"}
          ]
        }
      }
    }
  ],
  "connections": {
    "定时触发": {"main": [[{"node": "生成主题", "type": "main", "index": 0}]]},
    "生成主题": {"main": [[{"node": "内容生成", "type": "main", "index": 0}]]},
    "内容生成": {"main": [[{"node": "图片生成", "type": "main", "index": 0}]]},
    "图片生成": {"main": [[{"node": "内容审核", "type": "main", "index": 0}]]},
    "内容审核": {"main": [[{"node": "条件判断", "type": "main", "index": 0}]]},
    "条件判断": {
      "main": [
        [{"node": "发布内容", "type": "main", "index": 0}],
        [{"node": "记录错误", "type": "main", "index": 0}]
      ]
    },
    "发布内容": {"main": [[{"node": "发送通知", "type": "main", "index": 0}]]}
  }
}

4.5 平台部署指南

Dify 私有化部署

bash 复制代码
# 克隆仓库
git clone https://github.com/langgenius/dify.git
cd dify/docker

# 复制环境变量
cp .env.example .env

# 启动服务
docker compose up -d

# 查看状态
docker compose ps

# 访问 http://localhost

n8n 私有化部署

方式一:Docker 快速部署

bash 复制代码
docker run -it --rm \
  --name n8n \
  -p 5678:5678 \
  -v ~/.n8n:/home/node/.n8n \
  -e N8N_BASIC_AUTH_ACTIVE=true \
  -e N8N_BASIC_AUTH_USER=admin \
  -e N8N_BASIC_AUTH_PASSWORD=your_password \
  n8nio/n8n

方式二:Docker Compose 部署

yaml 复制代码
# docker-compose.yml
version: "3.8"

services:
  n8n:
    image: n8nio/n8n
    ports:
      - "5678:5678"
    volumes:
      - ./n8n-data:/home/node/.n8n
    environment:
      - N8N_BASIC_AUTH_ACTIVE=true
      - N8N_BASIC_AUTH_USER=admin
      - N8N_BASIC_AUTH_PASSWORD=secure_password
      - N8N_HOST=0.0.0.0
      - N8N_PORT=5678
      - WEBHOOK_URL=https://your-domain.com/
    restart: unless-stopped

  postgres:
    image: postgres:15
    environment:
      - POSTGRES_USER=n8n
      - POSTGRES_PASSWORD=n8n_password
      - POSTGRES_DB=n8n
    volumes:
      - ./postgres-data:/var/lib/postgresql/data
    restart: unless-stopped

Flowise 部署

bash 复制代码
# 方式一:NPM 安装
npm install -g flowise
npx flowise start

# 方式二:Docker 部署
docker run -d \
  --name flowise \
  -p 3000:3000 \
  -v ~/.flowise:/root/.flowise \
  flowiseai/flowise

4.6 工作流最佳实践

1. 模块化设计

复制代码
✅ 好的设计
工作流/
├── 子流程1: 数据预处理
├── 子流程2: 核心处理
└── 子流程3: 结果输出

❌ 不好的设计
一个巨大的工作流包含所有逻辑

2. 错误处理策略

yaml 复制代码
error_handling:
  retry_policy:
    max_retries: 3
    retry_delay: 5s
    exponential_backoff: true

  fallback:
    - condition: "api_timeout"
      action: "use_cached_result"
    - condition: "rate_limit"
      action: "queue_for_later"
    - condition: "unknown_error"
      action: "notify_admin"

3. 性能优化

yaml 复制代码
optimization:
  parallel_execution: true  # 并行执行独立节点
  caching:
    enabled: true
    ttl: 3600  # 1小时缓存

  resource_limits:
    max_execution_time: 300  # 5分钟超时
    max_memory: 512MB

4.7 GitHub 项目推荐

项目 描述 链接
Dify AI 应用开发平台 github.com/langgenius/...
n8n 工作流自动化 github.com/n8n-io/n8n
Flowise LLM 可视化构建 github.com/FlowiseAI/F...
LangFlow LangChain 可视化 github.com/langflow-ai...
RAGFlow RAG 引擎 github.com/infiniflow/...
AnythingLLM 一体化 AI 助手 github.com/Mintplex-La...

下一篇: Coze 零代码平台


欢迎关注的我的公众号《码上未来》,一起交流AI前沿技术!

添加我微信 return_not_null 进群聊AI

相关推荐
码以致用15 分钟前
用 DeepAgents 自动分析表格数据,一键生成图表与报告
人工智能·ai编程
PRINT!2 小时前
个人财富全景管理系统 AssetMe【内容均为AI制作】
spring boot·信息可视化·ai编程
peterfei2 小时前
我给 CLI 加了个「长期记忆」,1200 行代码让 AI 记住你的所有偏好
ai编程
Niubility2 小时前
AI 让一个人干一家公司?现实卡在 Vibe Coding 这一关
ai编程·claude·vibecoding
刀法如飞2 小时前
Rust数组去重的20种实现方式,AI时代用不同思路解决问题
人工智能·算法·ai编程
喜欢打篮球的普通人3 小时前
claude code 基础分享
ai编程
w1wi3 小时前
【Vibe Coding】TCP/UDP包篡改重放工具
人工智能·网络协议·tcp/ip·ai·udp·ai编程
程序新视界5 小时前
Claude Code的一次真实项目实践体验
ai编程·claude
sg_knight5 小时前
第一次用 OpenClaw,我让它 3 分钟写了个小工具
算法·llm·agent·ai编程·openclaw
甲维斯5 小时前
98%命中率!Claude+Opus4.7也太强了吧!
人工智能·ai编程