乐于分享
好东西不私藏

Dify源码剖析

Dify源码剖析

本文档基于 Dify v1.13.0 源码分析生成

目录

  • • 1. 项目概述
  • • 2. 后端架构 (API)
    • • 2.1 分层架构
    • • 2.2 核心模块
    • • 2.3 异步任务
    • • 2.4 数据库模型
    • • 2.5 扩展系统
  • • 3. 前端架构 (Web)
    • • 3.1 技术栈
    • • 3.2 目录结构
    • • 3.3 状态管理
    • • 3.4 API 调用
  • • 4. 部署方案
    • • 4.1 Docker Compose 部署
    • • 4.2 中间件架构
    • • 4.3 环境配置
    • • 4.4 高可用部署
  • • 5. 关键设计模式

1. 项目概述

Dify 是一个开源的 LLM 应用开发平台,提供 AI 工作流、RAG 管道、Agent 能力、模型管理等功能。

技术组成

目录
技术栈
用途
/api
Python Flask + SQLAlchemy
后端 API
/web
Next.js + React + TypeScript
前端 Web 应用
/docker
Docker Compose
容器化部署

核心功能

  • • Workflow: 可视化 AI 工作流编排
  • • RAG Pipeline: 文档摄取、索引、检索全流程
  • • Agent: 基于 LLM Function Calling / ReAct 的智能代理
  • • Model Management: 支持 20+ 模型提供商
  • • LLMOps: 日志监控、性能分析、持续优化

2. 后端架构 (API)

2.1 分层架构

Controllers → Services → Core → Repositories → Models
职责
关键模块
Controllers
HTTP 请求处理、参数验证、权限检查
console/

web/service_api/files/
Services
业务逻辑编排
app_service

workflow_servicedataset_service
Core
核心领域逻辑
workflow/

agent/rag/model_runtime/tools/
Repositories
数据访问抽象层
SQLAlchemy 仓储
Models
ORM 模型定义
account

datasetworkflowmodel

2.2 核心模块

2.2.1 Workflow 引擎 (core/workflow/)

支持 32 种节点类型

类别
节点类型
LLM
LLM 调用
Agent
Agent 节点
Knowledge
Knowledge Retrieval、Knowledge Index
Logic
If-Else、Iteration、Loop
Data
Code、HTTP Request、Template Transform
Input/Output
Start、End、Variable Assigner、Parameter Extractor
Document
Document Extractor
Tools
Tool、Trigger Plugin/Schedule/Webhook
Operator
List Operator、Variable Aggregator

核心组件:

  • • WorkflowEntry – 工作流入口,调度 GraphEngine
  • • GraphEngine – 图执行引擎
  • • GraphEngine.layers – 日志层、限流层

2.2.2 Agent 模块 (core/agent/)

core/agent/
├── base_agent_runner.py     # Agent 运行器基类
├── cot_agent_runner.py      # Chain-of-Thought Agent
├── fc_agent_runner.py       # Function Calling Agent
├── cot_chat_agent_runner.py # CoT Chat Agent
├── cot_completion_agent_runner.py
├── strategy/                # Agent 策略
└── output_parser/          # 输出解析

2.2.3 RAG 模块 (core/rag/)

core/rag/
├── embedding/        # 向量化处理
├── extractor/        # 文档提取
├── index_processor/  # 索引处理
├── retrieval/        # 检索方法
├── rerank/           # 重排序
├── splitter/         # 文档分块
├── cleaner/          # 数据清洗
├── docstore/         # 文档存储
├── pipeline/         # RAG 管道
├── datasource/       # 数据源
└── models/           # RAG 模型

2.2.4 模型运行时 (core/model_runtime/)

支持的模型提供商:

model_providers/
├── openai/           # GPT-4, GPT-3.5
├── anthropic/        # Claude
├── azure_openai/     # Azure OpenAI
├── google/           # Gemini
├── huggingface/     # Llama, BERT
├── volcengine/      # 火山引擎
├── minimax/          #  Minimax
├── spark/            # 讯飞星火
├── fireworks/       # Fireworks AI
├── bedrock/         # AWS Bedrock
├── nvidia/          # NVIDIA NIM
└── ... (20+)

2.2.5 Tools 模块 (core/tools/)

core/tools/
├── tool_manager.py      # 工具管理器
├── tool_engine.py       # 工具引擎
├── builtin_tool/        # 内置工具 (50+)
├── custom_tool/         # 自定义工具
├── mcp_tool/            # MCP 协议工具
├── plugin_tool/         # 插件工具
└── workflow_as_tool/    # 工作流作为工具

2.3 异步任务

基于 Celery + Redis 实现后台任务:

tasks/
├── document_indexing_task.py      # 文档索引
├── batch_create_segment_to_index_task.py
├── clean_dataset_task.py
├── async_workflow_tasks.py        # 异步工作流
├── workflow_execution_tasks.py    # 工作流执行
├── workflow_schedule_tasks.py     # 定时工作流
├── mail_*.py                      # 邮件任务
└── annotation/                    # 标注任务

2.4 数据库模型

使用 SQLAlchemy + PostgreSQL,核心模型:

账户租户系统 (models/account.py)

classAccount(UserMixin, TypeBase):
    __tablename__ = "accounts"
id: Mapped[str]
    name: Mapped[str]
    email: Mapped[str]
    password: Mapped[str | None]
    avatar: Mapped[str | None]
    timezone: Mapped[str | None]
    status: Mapped[str]
    role: TenantAccountRole | None

classTenant(TypeBase):
"""租户/工作空间"""

classTenantAccountRole(enum.StrEnum):
    OWNER = "owner"
    ADMIN = "admin"
    EDITOR = "editor"
    NORMAL = "normal"
    DATASET_OPERATOR = "dataset_operator"

知识库 (models/dataset.py)

classDataset(Base):
    __tablename__ = "datasets"
id: Mapped[str]
    tenant_id: Mapped[str]
    name: Mapped[str]
    description: Mapped[str]
    permission: Mapped[str]  # DatasetPermissionEnum
    indexing_technique: Mapped[str]  # high_quality/economy
    retrieval_model: Mapped[AdjustedJSON]
    embedding_model: Mapped[str]
    embedding_model_provider: Mapped[str]

classDocument(Base):
"""文档"""

classDocumentSegment(Base):
"""文档段落"""

classEmbedding(Base):
"""嵌入向量记录"""

应用对话 (models/model.py)

classApp(Base):
    __tablename__ = "apps"
id: Mapped[str]
    tenant_id: Mapped[str]
    name: Mapped[str]
    mode: Mapped[str]  # AppMode

classAppMode(enum.StrEnum):
    COMPLETION = "completion"
    CHAT = "chat"
    ADVANCED_CHAT = "advanced-chat"
    AGENT_CHAT = "agent-chat"
    WORKFLOW = "workflow"

classMessage(Base):
"""消息"""

classConversation(Base):
"""对话"""

工作流 (models/workflow.py)

classWorkflowType(StrEnum):
    WORKFLOW = "workflow"
    CHAT = "chat"
    RAG_PIPELINE = "rag-pipeline"

classWorkflow(Base):
    __tablename__ = "workflows"
id: Mapped[str]
    tenant_id: Mapped[str]
    app_id: Mapped[str]
type: Mapped[str]  # WorkflowType
    version: Mapped[str]
    graph: Mapped[str]  # JSON graph config

classWorkflowRun(Base):
"""工作流运行记录"""

classWorkflowNodeExecutionModel(Base):
"""节点执行记录"""

2.5 扩展系统

通过 Flask 扩展机制初始化 (extensions/):

extensions = [
    ext_timezone,        # 时区
    ext_logging,         # 日志
    ext_orjson,          # JSON 序列化
    ext_database,        # SQLAlchemy
    ext_migrate,         # Alembic 数据库迁移
    ext_redis,           # Redis 缓存/消息队列
    ext_storage,         # 文件存储
    ext_celery,          # Celery 异步任务
    ext_login,           # Flask-Login 认证
    ext_mail,            # 邮件
    ext_sentry,          # Sentry 错误追踪
    ext_blueprints,      # 注册路由蓝图
    ext_commands,        # CLI 命令
    ext_otel,            # OpenTelemetry 可观测性
]

3. 前端架构 (Web)

3.1 技术栈

类别
技术
框架
Next.js 16.1.5 (App Router)
UI
React 19.2.4 + Tailwind CSS 3.4.19
状态管理
Zustand 5.0.9 + Jotai 2.16.1 + TanStack Query 5.90.5
HTTP
Ky 1.12.0
表单
@tanstack/react-form 1.23.7
路由
nuqs 2.8.6 (URL 状态管理)
图标
@remixicon/react 4.7.0
国际化
i18next 25.7.3 + react-i18next 16.5.0 (25 种语言)

3.2 目录结构

web/
├── app/                    # Next.js App Router 页面
│   ├── (commonLayout)/    # 主布局(apps, datasets, explore)
│   ├── (shareLayout)/     # 共享应用布局
│   ├── datasets/          # 知识库模块页面
│   ├── account/           # 账户设置页面
│   ├── signin/            # 登录页面
│   ├── signup/            # 注册页面
│   └── components/        # React 组件
│       ├── base/          # 109 个基础 UI 组件
│       ├── app/           # 应用配置组件
│       ├── apps/          # 应用相关组件
│       ├── datasets/       # 知识库组件
│       ├── workflow/      # 工作流画布和节点 (41 项)
│       ├── header/        # 头部导航
│       └── tools/         # 工具相关组件
├── service/               # API 服务层 (56 文件)
│   ├── base.ts            # Ky HTTP 客户端封装
│   ├── fetch.ts           # Fetch 工具函数
│   ├── apps.ts            # 应用 API
│   ├── datasets.ts         # 知识库 API
│   └── use-*.ts           # TanStack Query Hooks
├── context/               # React Context
│   ├── provider-context.tsx   # 全局 Provider 状态
│   ├── app-context.tsx        # 应用级 Context
│   ├── modal-context.tsx      # 模态框管理
│   └── i18n.ts                 # 国际化 Context
├── i18n/                  # 国际化文件 (25 种语言)
│   ├── en-US/
│   ├── zh-Hans/
│   └── ... (25 个语言包)
├── hooks/                # 自定义 React Hooks
├── models/               # TypeScript 类型模型
├── types/                # 类型定义
├── utils/                # 工具函数
├── config/               # 环境配置
├── themes/               # 主题配置
└── constants/            # 常量定义

3.3 状态管理

采用三层架构

层级
技术
用途
服务端状态
TanStack Query
数据获取、缓存、轮询
全局客户端状态
Zustand
用户偏好、UI 状态
原子状态
Jotai
高性能细粒度状态选择

TanStack Query 使用示例

// service/use-apps.ts
exportconstuseAppList = (paramsAppListParams) => {
return useQuery<AppListResponse>({
queryKeyappListKey(normalizedParams),
queryFn() => get<AppListResponse>(`/apps`, { params: normalizedParams }),
  })
}

exportconstuseAppDetail = (appIDstring) => {
return useQuery<App>({
queryKey: [NAME_SPACE'detail', appID],
queryFn() => get<App>(`/apps/${appID}`),
enabled: !!appID,
  })
}

Zustand 全局状态示例

// context/modal-context.tsx
exportconst useModalContext = create<ModalContextState>((set) => ({
modalContext: {},
setModalContext(payload) =>set((state) => ({
modalContext: { ...state.modalContext, ...payload }
  })),
}))

3.4 API 调用

HTTP 客户端架构

service/fetch.ts    # Ky 底层封装
    ↓
service/base.ts    # get/post/put/delete 封装
    ↓
service/*.ts       # 业务 API (apps.ts, datasets.ts, etc.)

核心方法

// service/base.ts
exportconst get = <T>(urlstring, options = {}, otherOptions?: IOtherOptions) => {
return request<T>(url, Object.assign({}, options, { method'GET' }), otherOptions)
}

exportconst post = <T>(urlstring, options = {}, otherOptions?: IOtherOptions) => {
return request<T>(url, Object.assign({}, options, { method'POST' }), otherOptions)
}

SSE 流式响应

// service/base.ts
exportconsthandleStream = (responseResponseonDataIOnData, ...) => {
const reader = response.body?.getReader()
// 解析 SSE 格式: "data: {...}" 行
  lines.forEach((message) => {
if (message.startsWith('data: ')) {
      bufferObj = JSON.parse(message.substring(6))
if (bufferObj.event === 'message'onData(...)
elseif (bufferObj.event === 'workflow_started'onWorkflowStarted(...)
    }
  })
}

文件上传

// XHR 封装,支持上传进度
exportconstupload = async (optionsUploadOptions, ...) => {
returnnewPromise((resolve, reject) => {
const xhr = newXMLHttpRequest()
    xhr.open('POST', url)
    xhr.withCredentials = true
    xhr.upload.onprogress = options.onprogress
    xhr.onreadystatechange = () => {
if (xhr.readyState === 4 && xhr.status === 201)
resolve(xhr.response)
    }
    xhr.send(options.data)
  })
}

API 服务模块

文件
service/apps.ts
应用 CRUD 和统计
service/datasets.ts
知识库管理
service/common.ts
通用 API
service/workflow.ts
工作流操作
service/tools.ts
工具管理
service/share.ts
共享应用访问
service/billing.ts
计费和订阅

3.5 国际化

配置

// i18n-config/language.ts
exportconstLanguagesSupportedLocale[] = languages
  .filter(item => item.supported)
  .map(item => item.value)
// 支持 25 种语言

使用方式

// 在组件中
const { t } = useTranslation('common')
return<div>{t('name')}</div>

// 指定命名空间
const { t } = useTranslation('app')
return<div>{t('createApp')}</div>

4. 部署方案

4.1 Docker Compose 部署

cd docker
cp .env.example .env
# 根据需要编辑 .env 配置
docker compose up -d

访问 http://localhost/install 进行初始化配置。

4.2 中间件架构

┌─────────────────────────────────────────────────────────────┐
│                        Nginx                                │
│              (反向代理 + SSL 终止 + 静态资源)                 │
├─────────────────────────────────────────────────────────────┤
│  ┌─────────┐  ┌─────────┐  ┌─────────┐  ┌─────────────┐     │
│  │  API    │  │  Web    │  │ Worker  │  │   Celery    │     │
│  │(Flask)  │  │(Next.js)│  │(Celery) │  │ (Beat/Flower)│    │
│  └────┬────┘  └─────────┘  └────┬────┘  └──────┬──────┘     │
│       │                         │             │             │
│  ┌────▼─────────────────────────▼─────────────▼────┐        │
│  │                  PostgreSQL                     │        │
│  │            (主数据库 + 向量插件)                  │        │
│  └──────────────────────┬────────────────────────┘        │
│                         │                                   │
│  ┌──────────────────────▼────────────────────────┐       │
│  │                     Redis                       │       │
│  │         (缓存 + Celery Broker)                  │       │
│  └────────────────────────────────────────────────┘       │
│                                                            │
│  ┌────────────────────────────────────────────────┐        │
│  │              向量数据库 (可切换)                    │        │
│  │  Weaviate / Milvus / OpenSearch / Chroma / ...   │        │
│  └────────────────────────────────────────────────┘        │
│                                                            │
│  ┌────────────────────────────────────────────────┐        │
│  │              对象存储 (可切换)                     │        │
│  │     Local / S3 / Azure Blob / Google Storage    │        │
│  └────────────────────────────────────────────────┘        │
└─────────────────────────────────────────────────────────────┘

4.3 环境配置

通过 .env 文件配置:

通用配置

变量
说明
CONSOLE_API_URL
控制台 API 地址
SERVICE_API_URL
服务 API 地址
APP_WEB_URL
前端应用地址
FILES_URL
文件下载基础 URL
SECRET_KEY
会话加密密钥

数据库

变量
说明
DB_USERNAME
PostgreSQL 用户名
DB_PASSWORD
PostgreSQL 密码
DB_HOST
PostgreSQL 主机
DB_PORT
PostgreSQL 端口
DB_DATABASE
数据库名称

Redis

变量
说明
REDIS_HOST
Redis 主机
REDIS_PORT
Redis 端口
REDIS_PASSWORD
Redis 密码

向量数据库

变量
说明
VECTOR_STORE
向量库类型 (weaviate/milvus/opensearch/chroma)
WEAVIATE_ENDPOINT
Weaviate 端点
MILVUS_URI
Milvus URI

存储

变量
说明
STORAGE_TYPE
存储类型 (local/s3/azure/google)
S3_BUCKET_NAME
S3 桶名
AZURE_BLOB_ACCOUNT_NAME
Azure Blob 账户

SSL

Certbot 自动续期,参考 docker/certbot/README.md 配置。

4.4 高可用部署

Kubernetes

方案
来源
Helm Chart
douban/charts
Helm Chart
BorisPolonsky/dify-helm
Helm Chart
magicsong/ai-charts
YAML
Winson-030/dify-kubernetes
YAML
Zhoneym/DifyAI-Kubernetes

Terraform

平台
来源
Azure Global
nikawang/dify-azure-terraform
Google Cloud
DeNA/dify-google-cloud-terraform

AWS CDK

方案
来源
EKS
aws-samples/solution-for-deploying-dify-on-aws
ECS
aws-samples/dify-self-hosted-on-aws

其他云平台

  • • Alibaba Cloud Computing Nest – 一键部署
  • • Alibaba Cloud Data Management – 一键部署
  • • Azure AKS – Ruiruiz30/Dify-helm-chart-AKS

5. 关键设计模式

模式
应用场景
示例
工厂模式
服务和仓储创建
DifyAPIRepositoryFactory.create_api_workflow_node_execution_repository()
仓储模式
数据访问抽象
ApiWorkflowRunRepository
策略模式
Agent 多态实现
CoTAgentRunner

 vs FCAgentRunner
责任链模式
Workflow 节点执行
GraphEngine

 链式调度
贫血模型
Services 层设计
AppService

WorkflowService 只负责业务编排

架构特点

  1. 1. 分层清晰: Controller → Service → Core 职责分明
  2. 2. 领域驱动: Core 层封装完整领域逻辑
  3. 3. 存储分离: 通过 Repository 抽象支持多种存储后端
  4. 4. 异步解耦: Celery + Redis 实现后台任务
  5. 5. 可观测性: OpenTelemetry 支持

附录

  • • 官方文档: https://docs.dify.ai
  • • GitHub: https://github.com/langgenius/dify
  • • 社区 Discord: https://discord.gg/FngNHpbcY7