🎨 开源LLMOps平台

Dify 完整教程

可视化构建企业级AI应用

🎨 可视化编排 🤖 Agent构建 📚 RAG集成 🔌 API服务

🎯 Dify 是什么?

Dify 是一个开源的LLMOps(大模型运维)平台, 让你无需编程即可可视化构建和部署AI应用。类似于AI界的"低代码平台", 通过拖拽式编排即可创建聊天机器人、AI工作流、知识库问答等应用。

核心定位:"生成式AI应用创新引擎",让AI应用开发从代码堆砌变成可视化搭积木。

✅ 核心优势

  • 零代码:可视化拖拽构建
  • 开源免费:MIT许可证
  • 支持私有化:可本地部署
  • 模型无关:支持100+模型
  • 企业级:权限、审计、监控完善

🎯 适用场景

  • • 企业知识库问答
  • • 智能客服系统
  • • 内容创作助手
  • • 数据分析Agent
  • • 业务流程自动化

📊 技术栈

  • 后端:Python + Flask
  • 前端:React + TypeScript
  • 数据库:PostgreSQL
  • 缓存:Redis
  • 向量库:Weaviate/Qdrant

📊 项目数据

38K+
GitHub Stars
100+
支持模型
10K+
企业用户
50+
集成工具

🚀 快速部署

🐳

Docker Compose 部署(推荐)

最简单
# 1. 克隆仓库
git clone https://github.com/langgenius/dify.git
cd dify/docker

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

# 3. 修改 .env 文件
# - 设置SECRET_KEY(随机字符串)
# - 配置数据库密码
# - 添加模型API Key(可选)

# 4. 启动服务
docker-compose up -d

# 5. 等待服务启动(约30秒)
docker-compose ps

# 6. 访问
# http://localhost/install
# 首次访问会进入初始化页面

默认端口:

  • • Web界面:http://localhost (Nginx)
  • • API服务:http://localhost/api
  • • PostgreSQL:5432
  • • Redis:6379
💻

源码部署(开发环境)

后端启动

# 1. 克隆仓库
git clone https://github.com/langgenius/dify.git
cd dify

# 2. 安装依赖
cd api
pip install -r requirements.txt

# 3. 配置环境变量
cp .env.example .env
# 编辑.env设置数据库等

# 4. 初始化数据库
flask db upgrade

# 5. 启动服务
flask run --host 0.0.0.0 --port 5001

前端启动

# 1. 进入前端目录
cd web

# 2. 安装依赖
npm install
# 或使用 pnpm install

# 3. 配置API地址
# 修改 .env.local
NEXT_PUBLIC_API_PREFIX=http://localhost:5001

# 4. 启动开发服务器
npm run dev

# 访问 http://localhost:3000
☁️

Dify Cloud(托管版本)

免费版

  • • 200次消息额度/月
  • • 1个团队成员
  • • 社区支持
  • • 适合个人学习

专业版

  • • 无限消息额度
  • • 10+团队成员
  • • 优先支持
  • • 适合企业使用

✨ 核心功能

💬 Chatbot(对话助手)

快速创建对话机器人,支持多轮对话、上下文记忆、个性化定制。

核心能力

  • • 对话记忆:自动管理上下文
  • • 变量插入:动态填充内容
  • • 开场白:自定义欢迎语
  • • 下一步建议:引导用户

应用场景

客服、销售、教育陪伴、心理咨询等

✍️ Text Generation(文本生成)

单次文本生成应用,适合内容创作、翻译、摘要等任务。

核心能力

  • • 批量处理:Excel导入导出
  • • 参数调优:温度、top_p等
  • • 输出验证:格式检查
  • • 模板复用:保存常用提示词

应用场景

文章生成、代码生成、翻译、摘要等

🔄 Workflow(工作流编排)⭐

可视化编排复杂AI工作流,支持条件判断、循环、并行等逻辑。

核心节点

  • • LLM节点:调用大模型
  • • 条件分支:if-else逻辑
  • • 代码执行:Python/JavaScript
  • • HTTP请求:调用外部API
  • • 知识检索:RAG查询
  • • 模板转换:数据格式化

应用场景

复杂业务流程自动化、多步骤数据处理

🤖 Agent(智能助手)

构建能自主决策和使用工具的AI Agent。

核心能力

  • • 工具调用:搜索、计算器、API等
  • • 多步推理:自动规划执行步骤
  • • 结果验证:检查输出正确性
  • • 自主决策:选择最优路径

内置工具

  • • Google搜索、维基百科
  • • 天气查询、股票查询
  • • 计算器、日期时间
  • • 可自定义API工具

📚 Knowledge Base(知识库)

上传文档构建企业知识库,支持RAG问答。

支持格式

  • • 文档:PDF、Word、TXT、Markdown
  • • 网页:URL爬取、Sitemap
  • • 结构化:CSV、Excel
  • • 代码:Python、Java、Go等

高级特性

  • • 智能分段:自动chunk优化
  • • 多向量召回:提高准确率
  • • 重排序:ReRank精排
  • • 引用标注:显示来源

📝 Prompt编排器

可视化Prompt工程,支持变量、条件、Few-shot等高级技巧。

特性

  • • 变量系统:动态内容插入
  • • 上下文管理:记忆窗口控制
  • • Few-shot:示例管理
  • • 版本管理:Prompt版本控制

🔄 Workflow 可视化编排

智能文档分析Workflow示例

流程图

1. 开始
接收用户上传的文档
2. 文档解析
提取文本内容
3. LLM分析
提取关键信息、主题、摘要
4. 条件判断
根据文档类型分流
5. 生成报告
结构化输出分析结果

可用节点类型

LLM节点:调用大模型生成内容
知识检索:从知识库查询
条件分支:if-else逻辑
代码执行:Python/JS代码
HTTP请求:调用外部API
变量聚合:数据合并

高级功能

  • 循环节点:批量处理数据
  • 并行节点:多任务同时执行
  • 错误处理:异常捕获和降级
  • 变量传递:节点间数据流转
  • 调试模式:实时查看中间结果

实战案例:智能简历筛选

# Workflow配置(JSON格式)
{
  "nodes": [
    {
      "id": "start",
      "type": "start",
      "data": {
        "variables": ["resume_text"]
      }
    },
    {
      "id": "extract",
      "type": "llm",
      "data": {
        "model": "deepseek-chat",
        "prompt": "从简历中提取:姓名、工作年限、技能、教育背景\n\n简历:{resume_text}",
        "output_format": "json"
      }
    },
    {
      "id": "evaluate",
      "type": "code",
      "data": {
        "code": "score = calculate_match_score(extracted_data, job_requirements)"
      }
    },
    {
      "id": "branch",
      "type": "if-else",
      "data": {
        "condition": "score >= 80",
        "true_branch": "recommend",
        "false_branch": "reject"
      }
    },
    {
      "id": "recommend",
      "type": "llm",
      "data": {
        "prompt": "生成面试邀请邮件"
      }
    }
  ]
}

🤖 Agent 构建指南

Agent 配置步骤

1. 设置指令

你是一个数据分析专家。

能力:
1. 数据查询和分析
2. 可视化图表生成
3. 趋势预测

使用工具完成任务。

2. 添加工具

  • • Google搜索
  • • Python代码执行
  • • 数据库查询API
  • • 图表生成工具

3. 测试优化

  • • 运行测试用例
  • • 查看推理过程
  • • 优化工具选择
  • • 调整温度参数

自定义工具开发

# Python工具示例
from typing import Any

class WeatherTool:
    """天气查询工具"""
    
    @property
    def name(self) -> str:
        return "get_weather"
    
    @property
    def description(self) -> str:
        return "获取指定城市的天气信息"
    
    @property
    def parameters(self) -> dict:
        return {
            "type": "object",
            "properties": {
                "city": {
                    "type": "string",
                    "description": "城市名称,如:北京"
                }
            },
            "required": ["city"]
        }
    
    def _run(self, city: str) -> str:
        """执行工具"""
        # 调用天气API
        weather_data = fetch_weather(city)
        
        return f"{city}今天{weather_data['weather']},温度{weather_data['temp']}℃"

# 注册工具到Dify
# 在Dify后台"工具"页面添加

🔌 API 集成指南

Python SDK调用

# 安装SDK
pip install dify-client

# 使用SDK
from dify_client import ChatClient

client = ChatClient(
    api_key="app-your-api-key",  # 在Dify应用设置中获取
    base_url="http://localhost/v1"
)

# 发送消息
response = client.create_chat_message(
    inputs={},  # 应用变量
    query="什么是深度学习?",
    user="user-123",  # 用户ID
    response_mode="blocking"  # blocking或streaming
)

print(response.answer)

REST API直接调用

对话消息API

import requests

url = "http://localhost/v1/chat-messages"

headers = {
    "Authorization": "Bearer app-xxx",
    "Content-Type": "application/json"
}

data = {
    "inputs": {},
    "query": "你好",
    "user": "user-123",
    "response_mode": "blocking"
}

response = requests.post(url, headers=headers, json=data)
result = response.json()

print(result['answer'])

流式输出

data = {
    "inputs": {},
    "query": "讲个故事",
    "user": "user-123",
    "response_mode": "streaming"
}

with requests.post(url, headers=headers, json=data, stream=True) as r:
    for line in r.iter_lines():
        if line:
            data = json.loads(line.decode('utf-8').replace('data: ', ''))
            if data['event'] == 'message':
                print(data['answer'], end='', flush=True)

Workflow API调用

# 运行工作流
url = "http://localhost/v1/workflows/run"

data = {
    "inputs": {
        "resume_text": "张三,5年Python开发经验...",
        "job_requirements": "3年以上Python经验..."
    },
    "user": "user-123",
    "response_mode": "blocking"
}

response = requests.post(url, headers=headers, json=data)
result = response.json()

# 获取输出
print("推荐度:", result['data']['outputs']['recommendation_score'])
print("分析报告:", result['data']['outputs']['report'])

🛠️ 二次开发指南

项目结构

dify/
├── api/                    # 后端服务
│   ├── controllers/        # API控制器
│   ├── core/              # 核心业务逻辑
│   │   ├── agent/         # Agent引擎
│   │   ├── workflow/      # 工作流引擎
│   │   └── rag/           # RAG实现
│   ├── models/            # 数据模型
│   ├── services/          # 业务服务
│   └── extensions/        # 扩展(向量库等)
├── web/                   # 前端界面
│   ├── app/               # Next.js应用
│   ├── components/        # React组件
│   └── i18n/             # 国际化
└── docker/                # Docker配置

核心模块

  • core/agent

    Agent推理引擎

  • core/workflow

    Workflow执行引擎

  • core/rag

    RAG检索增强

  • core/model_runtime

    模型适配层

添加自定义模型提供商

# api/core/model_runtime/model_providers/my_llm/my_llm.py
from core.model_runtime.entities.llm_entities import LLMResult
from core.model_runtime.model_providers import ModelProvider

class MyLLMProvider(ModelProvider):
    def _invoke(self, model: str, credentials: dict, 
                prompt_messages: list, **kwargs) -> LLMResult:
        """调用自定义LLM API"""
        
        # 1. 构建请求
        api_url = credentials['api_endpoint']
        api_key = credentials['api_key']
        
        payload = {
            "model": model,
            "messages": prompt_messages,
            "temperature": kwargs.get('temperature', 0.7)
        }
        
        # 2. 发送请求
        response = requests.post(
            api_url,
            headers={"Authorization": f"Bearer {api_key}"},
            json=payload
        )
        
        # 3. 解析响应
        result = response.json()
        
        return LLMResult(
            message=result['choices'][0]['message'],
            usage=result['usage']
        )

# 配置文件:my_llm.yaml
provider: my_llm
label:
  zh_Hans: 我的LLM
  en_US: My LLM
supported_model_types:
  - llm
configurate_methods:
  - predefined-model
provider_credential_schema:
  credential_form_schemas:
    - variable: api_key
      type: secret-input
      required: true
      label:
        zh_Hans: API Key

开发自定义工具

# api/core/tools/provider/my_tools/tools/search.py
from core.tools.entities.tool_entities import ToolInvokeMessage
from core.tools.tool.builtin_tool import BuiltinTool

class SearchTool(BuiltinTool):
    def _invoke(self, user_id: str, tool_parameters: dict) -> list[ToolInvokeMessage]:
        """
        工具执行逻辑
        
        Args:
            user_id: 用户ID
            tool_parameters: 工具参数
        
        Returns:
            执行结果消息列表
        """
        query = tool_parameters.get('query', '')
        
        # 执行搜索
        results = self._search(query)
        
        # 格式化结果
        formatted = "\n".join([
            f"{i+1}. {r['title']}: {r['snippet']}"
            for i, r in enumerate(results[:5])
        ])
        
        return [
            self.create_text_message(formatted)
        ]
    
    def _search(self, query: str) -> list:
        """实际搜索逻辑"""
        # 调用搜索API
        pass

# 工具配置:search.yaml
identity:
  name: web_search
  author: Your Name
  label:
    zh_Hans: 网页搜索
    en_US: Web Search
description:
  zh_Hans: 在互联网上搜索信息
  en_US: Search information on the web
parameters:
  - name: query
    type: string
    required: true
    label:
      zh_Hans: 搜索关键词
    human_description:
      zh_Hans: 要搜索的内容

前端界面定制

# web/app/components/custom-chat/index.tsx
import { FC } from 'react'
import { ChatMessage } from '@/types/app'

interface CustomChatProps {
  messages: ChatMessage[]
  onSend: (message: string) => void
}

export const CustomChat: FC<CustomChatProps> = (props) => {
  const {messages, onSend} = props;
  
  return (
    <div className="flex flex-col h-screen">
      {/* 消息列表 */}
      <div className="flex-1 overflow-y-auto p-4">
        {messages.map((msg, idx) => {
          const alignClass = msg.role === 'user' ? 'text-right' : 'text-left';
          return (
            <div key={idx} className={alignClass}>
              <div className="inline-block max-w-md px-4 py-2 rounded-lg bg-gray-100">
                {msg.content}
              </div>
            </div>
          );
        })}
      </div>
      
      {/* 输入框 */}
      <div className="border-t p-4">
        <input
          type="text"
          onKeyPress={(e) => {
            if (e.key === 'Enter') {
              onSend(e.target.value);
              e.target.value = '';
            }
          }}
          className="w-full px-4 py-2 border rounded-lg"
          placeholder="输入消息..."
        />
      </div>
    </div>
  );
}

🎓 进阶使用技巧

⚡ 性能优化

  • 1.
    缓存配置

    Redis缓存对话历史和检索结果

  • 2.
    向量库优化

    使用Qdrant/Milvus提升检索速度

  • 3.
    异步处理

    Celery队列处理耗时任务

🔒 安全加固

  • 1.
    API认证

    为每个应用生成独立API Key

  • 2.
    权限控制

    RBAC角色权限管理

  • 3.
    内容审核

    敏感词过滤和内容审核

🔌 扩展集成

# 集成企业数据源
# api/extensions/ext_database.py

from extensions.ext_database import db

class EnterpriseDataSource:
    """企业数据源扩展"""
    
    def query(self, sql: str) -> list:
        """查询企业数据库"""
        # 连接企业数据库
        results = db.session.execute(sql)
        return results.fetchall()

# 在Workflow中使用
# 通过Code节点调用

📊 监控告警

# 接入Prometheus
# docker-compose.yml 添加

prometheus:
  image: prom/prometheus
  ports:
    - "9090:9090"
  volumes:
    - ./prometheus.yml:/etc/prometheus/prometheus.yml

# 在代码中埋点
from prometheus_client import Counter, Histogram

chat_requests = Counter('chat_requests_total', 'Total chat requests')
response_time = Histogram('response_time_seconds', 'Response time')

@response_time.time()
def handle_chat(query):
    chat_requests.inc()
    # 处理聊天...

🎯 企业部署最佳实践

架构部署

  • • 使用K8s编排容器
  • • 负载均衡(Nginx/ALB)
  • • 数据库主从复制
  • • Redis集群模式

数据安全

  • • 数据库加密存储
  • • API Key定期轮换
  • • 审计日志完整
  • • 定期备份数据

运维监控

  • • Prometheus+Grafana监控
  • • 日志聚合(ELK)
  • • 告警通知(钉钉/企微)
  • • 链路追踪(Jaeger)

📚 学习资源

🎯 Dify vs 其他方案

对比项 Dify LangChain 纯代码
开发难度 ⭐ 低(可视化) ⭐⭐ 中等 ⭐⭐⭐ 高
开发速度 ⚡ 分钟级 ⚡⚡ 小时级 ⚡⚡⚡ 天级
灵活性 ⭐⭐ 中等 ⭐⭐⭐ 高 ⭐⭐⭐⭐ 最高
企业功能 ✓ 完善 需自建 需自建

🎯 选择Dify的理由

让AI应用开发像搭积木一样简单

🎨

可视化

零代码开发

快速

分钟级上线

🏢

企业级

功能完善

📖

开源

MIT许可证

"Build your AI app in minutes, not weeks" - Dify Team