Dify组件详解与应用实战

Dify 组件详解与应用实战


一、组件概述

1.1 组件分类体系

Dify 提供了丰富的组件库,用于构建复杂的 AI 应用。组件按功能可分为以下几类:

类别 说明 组件数量
输入组件 接收用户输入 5+
LLM 组件 调用大语言模型 3+
工具组件 调用外部服务 10+
逻辑组件 控制流程逻辑 5+
输出组件 返回结果给用户 5+
知识库组件 管理和检索知识 3+

1.2 组件架构

复制代码
┌─────────────────────────────────────────────────────────────┐
│                    Dify 组件架构                            │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│    ┌─────────────┐    ┌─────────────┐    ┌─────────────┐   │
│    │  输入组件    │───→│  处理组件    │───→│  输出组件    │   │
│    │  (Input)     │    │  (Process)   │    │  (Output)    │   │
│    └─────────────┘    └──────┬──────┘    └─────────────┘   │
│                              │                              │
│         ┌────────────────────┼────────────────────┐         │
│         ↓                    ↓                    ↓         │
│    ┌─────────────┐    ┌─────────────┐    ┌─────────────┐   │
│    │   LLM 组件   │    │   工具组件   │    │   知识库组件 │   │
│    │  (LLM)       │    │  (Tools)     │    │  (Knowledge)│   │
│    └─────────────┘    └─────────────┘    └─────────────┘   │
│                              │                              │
│                              ↓                              │
│    ┌─────────────────────────────────────────────────────┐  │
│    │                   逻辑组件                            │  │
│    │         (Logic: Condition, Loop, Branch)             │  │
│    └─────────────────────────────────────────────────────┘  │
│                                                             │
└─────────────────────────────────────────────────────────────┘

二、输入组件

2.1 文本输入组件

功能:接收用户文本输入

配置参数

参数 类型 默认值 说明
label string "输入" 显示标签
placeholder string "请输入..." 占位提示
required boolean false 是否必填
max_length integer 0 最大长度(0 为不限)

使用场景

  • 用户提问
  • 搜索查询
  • 命令输入

工作流示例

复制代码
文本输入 → LLM 节点 → 文本输出

2.2 文件上传组件

功能:接收用户上传的文件

配置参数

参数 类型 默认值 说明
label string "上传文件" 显示标签
accepted_types array "\*" 允许的文件类型
max_size integer 10 最大文件大小(MB)
multiple boolean false 是否允许多选

支持的文件类型

类型 扩展名 说明
文本 .txt, .md 纯文本文件
文档 .docx, .pdf 办公文档
表格 .xlsx, .csv 电子表格
图片 .jpg, .png, .gif 图片文件

使用场景

  • 文档分析
  • 图片识别
  • 数据导入

代码示例

python 复制代码
def process_uploaded_file(file):
    # 获取文件内容
    content = file.read()
    
    # 根据文件类型处理
    if file.endswith('.pdf'):
        return extract_text_from_pdf(content)
    elif file.endswith('.csv'):
        return parse_csv(content)
    elif file.endswith('.md'):
        return content.decode('utf-8')

2.3 下拉选择组件

功能:提供选项列表供用户选择

配置参数

参数 类型 默认值 说明
label string "选择" 显示标签
options array \[\] 选项列表
default_value string "" 默认值
allow_multiple boolean false 是否多选

选项格式

json 复制代码
[
  {"label": "选项1", "value": "value1"},
  {"label": "选项2", "value": "value2"}
]

使用场景

  • 选择模型
  • 选择语言
  • 选择分类

2.4 日期选择组件

功能:选择日期或日期范围

配置参数

参数 类型 默认值 说明
label string "选择日期" 显示标签
type string "single" single/date_range
default_value string "" 默认日期
min_date string "" 最小日期
max_date string "" 最大日期

使用场景

  • 数据筛选
  • 报告生成
  • 时间范围查询

2.5 变量输入组件

功能:接收动态变量值

配置参数

参数 类型 默认值 说明
variable_name string "" 变量名称
type string "string" string/number/boolean
default_value any "" 默认值

使用场景

  • API 参数传递
  • 动态配置
  • 条件判断

三、LLM 组件

3.1 对话组件(Chat Completion)

功能:调用大模型进行对话生成

配置参数

参数 类型 默认值 说明
model string "gpt-4o" 模型名称
temperature float 0.7 温度参数
max_tokens integer 4096 最大输出长度
system_prompt string "" 系统提示词
user_prompt string "" 用户提示词模板

参数详解

参数 取值范围 说明
temperature 0-2 控制输出随机性,0 最确定,2 最随机
max_tokens 1-32768 限制输出长度
top_p 0-1 核采样,较小值更聚焦
frequency_penalty -2-2 降低重复内容概率
presence_penalty -2-2 增加新话题概率

使用示例

yaml 复制代码
llm_node:
  model: "gpt-4o"
  temperature: 0.7
  max_tokens: 4096
  system_prompt: |
    你是一位专业的数据分析助手。
    请分析用户提供的数据并给出专业建议。
  user_prompt: |
    用户数据:{{user_input}}
    请输出详细的分析报告。

3.2 文本生成组件(Completion)

功能:调用大模型进行文本补全

配置参数

参数 类型 默认值 说明
model string "text-davinci-003" 模型名称
prompt string "" 提示词
temperature float 0.7 温度参数
max_tokens integer 2048 最大输出长度

使用场景

  • 文本续写
  • 代码补全
  • 摘要生成

代码示例

python 复制代码
def generate_text(prompt):
    response = client.completions.create(
        model="text-davinci-003",
        prompt=prompt,
        temperature=0.7,
        max_tokens=2048
    )
    return response.choices[0].text

3.3 嵌入组件(Embedding)

功能:将文本转换为向量表示

配置参数

参数 类型 默认值 说明
model string "text-embedding-3-small" 嵌入模型
input string "" 输入文本
encoding_format string "float" 编码格式

使用场景

  • 文本相似度计算
  • 知识库检索
  • 聚类分析

代码示例

python 复制代码
def get_embedding(text):
    response = client.embeddings.create(
        model="text-embedding-3-small",
        input=text
    )
    return response.data[0].embedding

四、工具组件

4.1 HTTP 请求组件

功能:发送 HTTP 请求到外部 API

配置参数

参数 类型 默认值 说明
method string "GET" 请求方法
url string "" 请求地址
headers object {} 请求头
body string "" 请求体
query_params object {} 查询参数

支持的方法

方法 说明 适用场景
GET 获取数据 查询信息
POST 创建数据 提交表单
PUT 更新数据 全量更新
DELETE 删除数据 删除资源

使用示例

yaml 复制代码
http_node:
  method: "GET"
  url: "https://api.example.com/users"
  headers:
    Authorization: "Bearer {{api_key}}"
  query_params:
    page: "{{page_number}}"
    limit: "10"

4.2 数据库查询组件

功能:查询关系型数据库

支持的数据库

数据库 说明 驱动
PostgreSQL 开源关系型数据库 psycopg2
MySQL 流行关系型数据库 mysql-connector
SQLite 轻量级嵌入式数据库 sqlite3
SQL Server 微软数据库 pyodbc

配置参数

参数 类型 默认值 说明
connection string "" 数据库连接名
query string "" SQL 查询语句
parameters array \[\] 查询参数

使用示例

yaml 复制代码
database_node:
  connection: "sales_db"
  query: |
    SELECT * FROM orders 
    WHERE order_date >= '{{start_date}}' 
    AND status = 'completed'
  parameters: ["{{start_date}}"]

SQL 注入防护

python 复制代码
def safe_query(connection, query, params):
    # 使用参数化查询防止 SQL 注入
    cursor = connection.cursor()
    cursor.execute(query, params)
    return cursor.fetchall()

4.3 Python 代码组件

功能:执行自定义 Python 代码

配置参数

参数 类型 默认值 说明
code string "" Python 代码
inputs object {} 输入变量
outputs object {} 输出变量

代码模板

python 复制代码
# 输入变量
user_input = "{{user_input}}"
data = "{{data}}"

# 处理逻辑
result = process_data(user_input, data)

# 输出结果
outputs["result"] = result
outputs["status"] = "success"

使用场景

  • 数据处理
  • 自定义算法
  • API 集成

安全注意事项

  1. 避免执行用户输入的代码
  2. 限制文件系统访问
  3. 设置执行超时时间
  4. 限制网络访问

4.4 计算器组件

功能:执行数学计算

配置参数

参数 类型 默认值 说明
expression string "" 数学表达式

支持的运算

运算 符号 示例
加法 + 1 + 2
减法 - 10 - 5
乘法 * 3 * 4
除法 / 20 / 4
幂运算 ^ 2 ^ 3
括号 () (1 + 2) * 3

使用示例

yaml 复制代码
calculator_node:
  expression: "({{price}} * {{quantity}}) * (1 - {{discount}})"

4.5 日期处理组件

功能:处理日期和时间

配置参数

参数 类型 默认值 说明
operation string "format" 操作类型
input_date string "" 输入日期
format string "YYYY-MM-DD" 输出格式
offset integer 0 日期偏移(天)

支持的操作

操作 说明 示例
format 格式化日期 2024-01-01
add_days 添加天数 +7 天
subtract_days 减去天数 -7 天
diff_days 计算天数差 两个日期之间
now 获取当前时间 当前日期时间

使用示例

yaml 复制代码
date_node:
  operation: "add_days"
  input_date: "{{order_date}}"
  offset: 7
  format: "YYYY-MM-DD"

4.6 JSON 处理组件

功能:处理 JSON 数据

配置参数

参数 类型 默认值 说明
operation string "parse" 操作类型
input string "" 输入数据
path string "" JSON 路径

支持的操作

操作 说明 示例
parse 解析 JSON 字符串 '{"key": "value"}' → {"key": "value"}
stringify 序列化为字符串 {"key": "value"} → '{"key": "value"}'
get 获取指定路径的值 $.data.items0.name
set 设置指定路径的值 $.data.items0.name = "new"
merge 合并两个 JSON {a:1} + {b:2} = {a:1, b:2}

使用示例

yaml 复制代码
json_node:
  operation: "get"
  input: "{{api_response}}"
  path: "$.data.users[0].name"

4.7 字符串处理组件

功能:处理文本字符串

配置参数

参数 类型 默认值 说明
operation string "concat" 操作类型
input string "" 输入字符串
pattern string "" 正则表达式

支持的操作

操作 说明 示例
concat 拼接字符串 "hello" + "world"
split 分割字符串 "a,b,c" → "a","b","c"
replace 替换字符串 "apple" → "orange"
trim 去除首尾空格 " text " → "text"
regex_match 正则匹配 验证邮箱格式
regex_replace 正则替换 提取数字

使用示例

yaml 复制代码
string_node:
  operation: "regex_match"
  input: "{{email}}"
  pattern: "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$"

五、逻辑组件

5.1 条件判断组件

功能:根据条件执行不同分支

配置参数

参数 类型 默认值 说明
condition string "" 条件表达式
true_branch string "" 条件为真时执行
false_branch string "" 条件为假时执行

支持的比较运算符

运算符 说明 示例
== 等于 {{age}} == 18
!= 不等于 {{status}} != "completed"
> 大于 {{score}} > 90
< 小于 {{price}} < 100
>= 大于等于 {{count}} >= 10
<= 小于等于 {{rating}} <= 5
contains 包含 {{text}} contains "keyword"
empty 为空 {{value}} empty

使用示例

yaml 复制代码
condition_node:
  condition: "{{user_role}} == 'admin'"
  true_branch: "admin_workflow"
  false_branch: "user_workflow"

5.2 循环组件

功能:重复执行指定逻辑

配置参数

参数 类型 默认值 说明
iterable string "" 可迭代对象
loop_variable string "item" 循环变量名
max_iterations integer 100 最大迭代次数

使用场景

  • 批量处理数据
  • 遍历列表
  • 分页查询

使用示例

yaml 复制代码
loop_node:
  iterable: "{{user_list}}"
  loop_variable: "user"
  max_iterations: 50

5.3 分支组件

功能:根据多个条件执行不同分支

配置参数

参数 类型 默认值 说明
cases array \[\] 条件分支列表
default_case string "" 默认分支

使用示例

yaml 复制代码
branch_node:
  cases:
    - condition: "{{category}} == 'tech'"
      branch: "tech_workflow"
    - condition: "{{category}} == 'finance'"
      branch: "finance_workflow"
    - condition: "{{category}} == 'health'"
      branch: "health_workflow"
  default_case: "default_workflow"

5.4 并行组件

功能:并行执行多个任务

配置参数

参数 类型 默认值 说明
tasks array \[\] 并行任务列表
wait_all boolean true 是否等待全部完成

使用场景

  • 同时调用多个 API
  • 并行处理多个文件
  • 并发查询多个数据源

使用示例

yaml 复制代码
parallel_node:
  tasks:
    - task: "fetch_user_data"
    - task: "fetch_product_data"
    - task: "fetch_order_data"
  wait_all: true

5.5 延迟组件

功能:延迟执行后续逻辑

配置参数

参数 类型 默认值 说明
duration integer 1 延迟时间(秒)

使用场景

  • 限流控制
  • 等待外部系统
  • 定时任务

六、输出组件

6.1 文本输出组件

功能:返回文本结果给用户

配置参数

参数 类型 默认值 说明
content string "" 输出内容
format string "plain" plain/markdown/html

使用示例

yaml 复制代码
text_output_node:
  content: "分析完成!\n\n{{analysis_result}}"
  format: "markdown"

6.2 文件输出组件

功能:生成并返回文件

配置参数

参数 类型 默认值 说明
content string "" 文件内容
filename string "output.txt" 文件名
content_type string "text/plain" MIME 类型

支持的文件类型

类型 MIME 说明
文本 text/plain 纯文本
JSON application/json JSON 数据
CSV text/csv 表格数据
PDF application/pdf PDF 文档

使用示例

yaml 复制代码
file_output_node:
  content: "{{report_content}}"
  filename: "analysis_report_{{date}}.pdf"
  content_type: "application/pdf"

6.3 JSON 输出组件

功能:返回 JSON 格式结果

配置参数

参数 类型 默认值 说明
data object {} JSON 数据

使用示例

yaml 复制代码
json_output_node:
  data:
    status: "success"
    result: "{{analysis_result}}"
    timestamp: "{{current_time}}"

6.4 重定向组件

功能:重定向到另一个应用或 URL

配置参数

参数 类型 默认值 说明
url string "" 目标 URL
method string "GET" 请求方法
params object {} 查询参数

使用场景

  • 跳转登录页
  • 链接到外部系统
  • 重定向到其他应用

6.5 结束组件

功能:结束工作流执行

配置参数

参数 类型 默认值 说明
status string "success" success/failed
message string "" 结束消息

使用示例

yaml 复制代码
end_node:
  status: "success"
  message: "任务已完成"

七、知识库组件

7.1 知识库检索组件

功能:从知识库中检索相关知识

配置参数

参数 类型 默认值 说明
knowledge_base string "" 知识库名称
query string "" 检索查询
top_k integer 3 返回数量
score_threshold float 0.7 分数阈值

使用示例

yaml 复制代码
knowledge_retrieval_node:
  knowledge_base: "company_policy"
  query: "{{user_question}}"
  top_k: 5
  score_threshold: 0.6

RAG 流程

复制代码
用户查询 → 知识库检索 → 构建 Prompt → LLM 生成 → 返回结果

7.2 文档上传组件

功能:上传文档到知识库

配置参数

参数 类型 默认值 说明
knowledge_base string "" 目标知识库
file object {} 上传的文件
chunk_size integer 500 分段大小

使用场景

  • 批量导入文档
  • 动态更新知识库
  • 增量添加内容

7.3 知识统计组件

功能:获取知识库统计信息

配置参数

参数 类型 默认值 说明
knowledge_base string "" 知识库名称

返回数据

字段 说明 示例
document_count 文档数量 100
chunk_count 分段数量 500
total_tokens 总 Token 数 1,000,000
update_time 最后更新时间 2024-01-01

八、组件组合实战

8.1 实战场景 1:客户服务机器人

需求:根据用户问题类型,路由到不同处理流程

工作流设计

复制代码
文本输入 → 意图识别 → [条件判断]
                        ├── 产品咨询 → 知识库检索 → LLM回答 → 文本输出
                        ├── 订单查询 → HTTP请求 → JSON处理 → 文本输出
                        └── 投诉处理 → Python代码 → 数据库写入 → 文本输出

组件配置

yaml 复制代码
# 意图识别
intent_recognition:
  type: llm
  model: "gpt-4o"
  system_prompt: |
    请识别用户问题的意图,返回以下之一:
    - product_question
    - order_query
    - complaint

# 条件判断
condition:
  type: condition
  condition: "{{intent}} == 'product_question'"
  true_branch: "product_flow"
  false_branch: "other_flow"

# 知识库检索
knowledge_retrieval:
  type: knowledge_retrieval
  knowledge_base: "product_kb"
  query: "{{user_input}}"
  top_k: 3

# HTTP 请求
http_request:
  type: http
  method: "GET"
  url: "https://api.example.com/orders/{{order_id}}"
  headers:
    Authorization: "Bearer {{api_key}}"

# Python 代码
python_code:
  type: python
  code: |
    # 记录投诉
    complaint_data = {
        "user_id": "{{user_id}}",
        "content": "{{complaint_content}}",
        "timestamp": "{{current_time}}"
    }
    # 写入数据库
    db.insert("complaints", complaint_data)
    outputs["result"] = "投诉已记录"

8.2 实战场景 2:数据分析报告生成器

需求:上传 CSV 文件,分析数据并生成报告

工作流设计

复制代码
文件上传 → Python代码解析 → LLM分析 → 文件输出

组件配置

yaml 复制代码
# 文件上传
file_upload:
  type: file_upload
  accepted_types: ["csv"]
  max_size: 10

# Python 代码解析
data_parser:
  type: python
  code: |
    import csv
    import io
    
    # 解析 CSV
    csv_content = "{{file_content}}"
    reader = csv.DictReader(io.StringIO(csv_content))
    data = list(reader)
    
    # 统计信息
    total_rows = len(data)
    columns = list(data[0].keys())
    
    outputs["data"] = str(data[:10])  # 取前 10 行
    outputs["summary"] = f"共 {total_rows} 行,{len(columns)} 列"

# LLM 分析
data_analysis:
  type: llm
  model: "gpt-4o"
  system_prompt: |
    你是一位专业的数据分析师。
    请分析以下数据并生成详细的分析报告。
  user_prompt: |
    数据摘要:{{summary}}
    
    数据样本:{{data}}
    
    请生成包含以下内容的报告:
    1. 数据概况
    2. 关键发现
    3. 可视化建议
    4. 改进建议

# 文件输出
report_output:
  type: file_output
  content: "{{analysis_result}}"
  filename: "data_analysis_report_{{date}}.md"
  content_type: "text/markdown"

8.3 实战场景 3:多步骤表单处理

需求:收集用户信息,验证后保存到数据库

工作流设计

复制代码
文本输入(姓名) → 文本输入(邮箱) → 验证 → [条件判断]
                                            ├── 验证成功 → 数据库写入 → 成功输出
                                            └── 验证失败 → 失败输出

组件配置

yaml 复制代码
# 邮箱验证
email_validation:
  type: string
  operation: "regex_match"
  input: "{{email}}"
  pattern: "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$"

# 条件判断
validation_check:
  type: condition
  condition: "{{validation_result}} == true"
  true_branch: "save_flow"
  false_branch: "error_flow"

# 数据库写入
database_write:
  type: database
  connection: "user_db"
  query: |
    INSERT INTO users (name, email, created_at)
    VALUES ('{{name}}', '{{email}}', '{{current_time}}')

# 成功输出
success_output:
  type: text_output
  content: "注册成功!欢迎 {{name}}!"
  format: "markdown"

# 失败输出
error_output:
  type: text_output
  content: "邮箱格式不正确,请重新输入。"
  format: "plain"

九、组件最佳实践

9.1 组件选择指南

场景 推荐组件 理由
简单问答 文本输入 + LLM + 文本输出 快速实现
文档分析 文件上传 + Python + LLM 灵活处理
API 集成 HTTP 请求 + JSON 处理 标准化集成
数据查询 数据库查询 + 条件判断 结构化数据
复杂流程 工作流 + 多个组件 灵活编排

9.2 性能优化技巧

  1. 缓存重复查询:使用缓存组件减少重复计算
  2. 异步处理:对于耗时任务使用异步组件
  3. 批量操作:合并多个小查询为批量查询
  4. 模型选择:根据需求选择合适的模型

9.3 错误处理策略

方法

  1. 添加错误捕获:使用条件判断检查错误状态
  2. 设置默认值:为关键变量设置默认值
  3. 日志记录:记录关键步骤的执行日志
  4. 优雅降级:主流程失败时使用备用方案

代码示例

yaml 复制代码
error_handling:
  type: condition
  condition: "{{api_response.status}} == 'error'"
  true_branch: "fallback_flow"
  false_branch: "success_flow"

fallback:
  type: llm
  model: "gpt-3.5-turbo"
  system_prompt: "请基于通用知识回答用户问题"
  user_prompt: "{{user_input}}"

十、总结

核心要点

  1. 组件分类:输入、LLM、工具、逻辑、输出、知识库
  2. 组件特性:每个组件都有特定的配置参数和使用场景
  3. 组件组合:通过工作流编排实现复杂业务逻辑
  4. 最佳实践:合理选择组件,优化性能,处理错误

学习路径

复制代码
基础组件(输入/输出)→ LLM 组件 → 工具组件 → 
逻辑组件 → 知识库组件 → 复杂流程编排

下一步建议

  1. 熟悉每个组件的功能和配置
  2. 尝试构建简单的工作流
  3. 实践复杂场景的组件组合
  4. 学习性能优化和错误处理技巧