## 一、环境准备(新手友好版)
### 1.1 系统要求
- **操作系统**:Ubuntu 20.04 /macOS Monterey /Windows 10 (WSL2推荐)
- **内存**:至少8GB (运行大模型需16GB )
- **存储空间**:至少20GB可用空间
### 1.2 必要软件安装
#### Linux/macOS:
```bash
# 安装基础依赖
sudo apt update && sudo apt install -y git python3.11 python3.11-venv python3.11-dev build-essential
# 安装Node.js (使用nvm)
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
source ~/.bashrc
nvm install 18
nvm use 18
# 安装PostgreSQL和Redis
sudo apt install -y postgresql postgresql-contrib redis
```
#### Windows (WSL2):
```powershell
wsl --install -d Ubuntu
# 在Ubuntu子系统中执行上述Linux命令
```
### 1.3 数据库配置
```bash
sudo -u postgres psql
CREATE USER dify WITH PASSWORD 'dify_password';
CREATE dataBASE dify_db;
GRANT ALL PRIVILEGES ON DATABASE dify_db TO dify;
q
# 启动Redis
sudo systemctl enable redis-server && sudo systemctl start redis-server
```
## 二、项目部署与运行
### 2.1 获取源代码
```bash
git clone https://github.com/langgenius/dify.git
cd dify
```
### 2.2 后端配置
```bash
cd api
# 创建虚拟环境
python3.11 -m venv venv
source venv/bin/activate
# 安装依赖
pip install -U pip wheel setuptools
pip install -r requirements.txt
# 配置环境变量
cp .env.example .env
nano .env # 使用文本编辑器修改
```
**.env 关键配置示例**:
```ini
# 数据库配置
DATABASE_URL=postgresql://dify:dify_password@localhost:5432/dify_db
# Redis配置
REDIS_HOST=localhost
REDIS_PORT=6379
# 开发模式设置
DEBUG=true
DEV_MODE=true
# 初始管理员账号
SUPERADMIN_EMAIL=admin@example.com
SUPERADMIN_PASSWORD=admin123
```
### 2.3 前端配置
```bash
cd /web
# 安装依赖
npm install
# 配置环境变量
cp .env.example .env.local
nano .env.local # 使用文本编辑器修改
```
**.env.local 配置示例**:
```ini
VITE_APP_ENV=development
```
### 2.4 初始化数据库
```bash
cd /api
FLASK db upgrade
```
### 2.5 启动项目
```bash
# 启动后端 (在api目录)
flask run --port 5001
# 启动前端 (在web目录)
npm run dev
```
### 2.6 访问应用
- 使用初始管理员账号登录:`admin@example.com` / `admin123`
## 三、开发环境调试技巧
### 3.1 常用开发命令
```bash
# 后端热重载 (安装watchdog后)
pip install watchdog
flask run --reload --port 5001
# 前端热重载 (默认已启用)
npm run dev
# 运行单元测试
cd api
pytest tests/
# 代码格式化
cd web
npm run lint # 前端
cd /api
black . # 后端python
```
### 3.2 调试配置 (VS Code)
**.vscode/launch.json**:
```json
{
"version": "0.2.0",
"configurations": [
{
"name": "Python: Flask",
"type": "python",
"request": "launch",
"module": "flask",
"env": {
"FLASK_APP": "main:app",
"FLASK_ENV": "development"
},
"args": ["run", "--port=5001", "--no-debugger"],
"jinja": true
},
{
"name": "Frontend",
"type": "chrome",
"request": "launch",
"webRoot": "${workspaceFolder}/web"
}
]
}
```
## 四、二次开发实战案例
### 4.1 自定义工具集成(天气查询API)
**文件位置**:`api/services/tool/weather_tool.py`
```python
import requests
from core.tools.tool_manager import ToolManager
class WeatherTool:
name = "get_weather"
description = "获取指定城市的当前天气情况"
parameters = {
"type": "object",
"properties": {
"city": {
"type": "string",
"description": "城市名称,如:北京"
}
},
"required": ["city"]
}
def __init__(self, api_key: str):
self.api_key = api_key
def run(self, params: dict) -> str:
city = params.get('city', '北京')
url = f"https://api.weatherapi.com/v1/current.jsonkey={self.api_key}&q={city}&lang=zh"
response = requests.get(url)
if response.status_code == 200:
data = response.json()
current = data['current']
return (
f"{city}当前天气:{current['condition']['text']}n"
f"温度:{current['temp_c']}°Cn"
f"湿度:{current['humidity']}%n"
f"风速:{current['wind_kph']}km/h"
)
return f"获取{city}天气失败,请稍后再试"
# 注册工具
ToolManager.register_tool(
WeatherTool(api_key="your_weather_api_key"),
namespace="custom"
)
```
### 4.2 添加前端工作流节点
**文件位置**:`web/src/components/workflow/nodes/CustomWeatherNode.vue`
```vue
<template>
<div class="custom-weather-node">
<div class="node-header">
<span class="icon"><WeatherIcon /></span>
<span class="title">天气查询</span>
</div>
<div class="node-body">
<el-form-item label="城市">
<el-input v-model="city" placeholder="输入城市名称" />
</el-form-item>
</div>
</div>
</template>
<script setup>
import { ref } from 'vue'
import WeatherIcon from '@/assets/icons/weather.svgcomponent'
const city = ref('北京')
defineExpose({
getData: () => ({ city: city.value }),
validate: () => city.value
})
</script>
<style scoped>
.custom-weather-node {
border: 1px solid #4CAF50;
border-radius: 8px;
padding: 12px;
background: #f0fff4;
}
.node-header {
display: flex;
align-items: center;
margin-bottom: 10px;
}
.icon {
margin-right: 8px;
}
.title {
font-weight: bold;
color: #2E7D32;
}
</style>
```
**注册节点**:`web/src/components/workflow/nodes/index.js`
```js
import CustomWeatherNode from './CustomWeatherNode.vue'
export const nodeComponents = {
// .其他节点
'customWeatherNode': CustomWeatherNode
}
export const nodeTemplates = [
// .其他模板
{
type: 'customWeatherNode',
name: '天气查询',
desc: '获取指定城市的天气信息',
icon: 'weather',
category: 'custom'
}
]
```
### 4.3 扩展用户模型(添加手机号字段)
**文件位置**:`api/models/account.py`
```python
class Account(db.Model, UserMixin, TimestampMixin):
__tablename__ = 'accounts'
id = db.Column(UUID, primary_key=True, default=uuid.uuid4, unique=True, nullable=False)
# .原有字段
# 添加手机号字段
phone = db.Column(db.String(20), nullable=True, index=True)
# 添加索引
__table_args__ = (
db.Index('ix_accounts_phone', 'phone'),
)
```
**执行数据库迁移**:
```bash
flask db migrate -m "add_phone_to_account"
flask db upgrade
```
## 五、生产环境部署
### 5.1 使用docker部署
```bash
# 构建Docker镜像
docker-compose build
# 启动服务
docker-compose up -d
# 查看日志
docker-compose logs -f
```
### 5.2 Nginx配置示例
```nginx
server {
listen 80;
server_name dify.example.com;
location / {
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_CACHE_bypass $http_upgrade;
}
location /api {
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
```
### 5.3 性能优化建议
1. **启用缓存**:
```python
# .env 配置
CACHE_TYPE=RedisCache
CACHE_REDIS_URL=redis://localhost:6379/1
```
2. **启用Gunicorn**:
```bash
gunicorn -w 4 -k uvicorn.workers.UvicornWorker main:app
```
3. **前端优化**:
```bash
cd web
npm run build
# 使用Nginx直接服务静态文件
```
## 六、调试与故障排除
### 6.1 常见问题解决
| 问题 | 解决方法 |
|------|----------|
| 数据库连接失败 | 检查`.env`中的`DATABASE_URL`格式:`postgresql://user:pass@host:port/dbname` |
| 前端无法连接API | 确认`VITE_API_BASE_URL`正确,检查CORS设置 |
| 工具执行失败 | 查看API日志,检查工具参数格式 |
| 迁移失败 | 运行`flask db stamp head`重置迁移状态 |
### 6.2 日志查看
```bash
# 后端日志
tail -f api/logs/app.log
# 前端错误
浏览器开发者工具 > Console 面板
# Docker日志
docker-compose logs -f web api
```
## 七、进阶开发资源
### 7.1 核心目录结构
```
dify/
├── api/ # 后端核心
│ ├── core/ # 业务逻辑
│ │ ├── model_runtime/ # 模型接入
│ │ ├── dataset/ # 知识库处理
│ │ └── tools/ # 工具系统
│ ├── services/ # 应用服务
│ │ ├── workflow/ # 工作流引擎
│ │ └── dataset/ # 知识库服务
│ ├── models/ # 数据库模型
│ └── main.py # 入口文件
├── web/ # 前端
│ ├── src/
│ │ ├── views/ # 页面组件
│ │ ├── store/ # 状态管理(Pinia)
│ │ └── styles/ # 样式文件
└── docker-compose.yml # Docker配置
```
### 7.2 推荐学习资源
1. [官方文档](https://docs.dify.ai/v/zh-hans/)
2. [REST API参考](https://api.dify.ai/v1/docs)
3. [前端组件库](https://element-plus.org/) (Element Plus)
4. [FastAPI文档](https://fastapi.tiangolo.com/)
## 八、最佳实践建议
1. **版本控制**:为定制功能创建单独的分支
```bash
git checkout -b feature/custom-weather-tool
```
2. **配置管理**:将敏感信息存储在环境变量中,不要提交到仓库
3. **模块化开发**:
- 新工具创建在`api/core/tools/custom/`目录
- 新节点创建在`web/src/components/workflow/nodes/custom/`目录
4. **定期同步上游**:
```bash
git remote add upstream https://github.com/langgenius/dify.git
git fetch upstream
git merge upstream/main
```
5. **性能监控**:
```bash
# 安装监控工具
pip install prometheus-client
# 在main.py中添加
from prometheus_client import make_asgi_app, Counter
metrics_app = make_asgi_app()
app.mount("/metrics", metrics_app)
```
通过本指南,您应该能够顺利完成Dify的本地环境搭建、基础开发和生产部署。建议从小的定制功能开始,逐步深入理解系统架构后再进行重大修改。遇到问题时,可查阅官方文档或在GitHub社区寻求帮助。
生活中的难题,我们要相信自己可以解决,看完本文,相信你对 有了一定的了解,也知道它应该怎么处理。如果你还想了解软件二次开发的其他信息,可以点击集么律网其他栏目。