386 lines
8.1 KiB
Markdown
386 lines
8.1 KiB
Markdown
# Dify API 集成指南
|
||
|
||
> 西安云美电子科技有限公司 - 企业知识库
|
||
> 版本:v1.0 | 创建时间:2026-06-06
|
||
|
||
---
|
||
|
||
## 1. 概述
|
||
|
||
Dify 提供完整的 RESTful API,支持将知识库对话能力集成到企业微信、钉钉、自建系统等渠道。本文档涵盖最常用的 API 接口及集成示例。
|
||
|
||
**Base URL**: `http://<dify-host>/v1`
|
||
|
||
---
|
||
|
||
## 2. 认证方式
|
||
|
||
所有 API 请求需在 Header 中携带 API Key:
|
||
|
||
```
|
||
Authorization: Bearer app-<your-api-key>
|
||
```
|
||
|
||
**获取 API Key**:Dify 控制台 → 应用 → API 访问 → 创建 API Key
|
||
|
||
---
|
||
|
||
## 3. 对话接口
|
||
|
||
### 3.1 发送对话消息
|
||
|
||
```
|
||
POST /v1/chat-messages
|
||
```
|
||
|
||
**请求参数**
|
||
|
||
| 参数 | 类型 | 必填 | 说明 |
|
||
|------|------|:----:|------|
|
||
| query | string | ✅ | 用户输入的问题 |
|
||
| inputs | object | ❌ | 额外输入参数 |
|
||
| response_mode | string | ✅ | `blocking`(阻塞)或 `streaming`(流式) |
|
||
| conversation_id | string | ❌ | 对话 ID,首次对话不传,后续传入上一次返回的 ID |
|
||
| user | string | ✅ | 用户标识 |
|
||
| files | array | ❌ | 上传文件列表 |
|
||
|
||
**阻塞模式请求示例**
|
||
|
||
```bash
|
||
curl -X POST 'http://<dify-host>/v1/chat-messages' \
|
||
-H 'Authorization: Bearer app-<api-key>' \
|
||
-H 'Content-Type: application/json' \
|
||
-d '{
|
||
"query": "差旅报销标准是什么?",
|
||
"inputs": {},
|
||
"response_mode": "blocking",
|
||
"user": "zhangsan"
|
||
}'
|
||
```
|
||
|
||
**阻塞模式响应**
|
||
|
||
```json
|
||
{
|
||
"task_id": "xxx",
|
||
"message_id": "xxx",
|
||
"conversation_id": "xxx",
|
||
"answer": "根据《差旅管理制度》第三章:\n\n1. 住宿标准:一线城市 500 元/晚...\n2. 交通标准:高铁二等座...",
|
||
"created_at": 1717632000
|
||
}
|
||
```
|
||
|
||
**流式模式响应(SSE)**
|
||
|
||
```
|
||
data: {"event": "message", "message_id": "xxx", "conversation_id": "xxx", "answer": "根据", ...}
|
||
data: {"event": "message", "message_id": "xxx", "conversation_id": "xxx", "answer": "根据《", ...}
|
||
data: {"event": "message_end", ...}
|
||
```
|
||
|
||
### 3.2 获取对话历史
|
||
|
||
```
|
||
GET /v1/messages?conversation_id=<id>&user=<user>
|
||
```
|
||
|
||
**响应**
|
||
|
||
```json
|
||
{
|
||
"limit": 20,
|
||
"has_more": false,
|
||
"data": [
|
||
{
|
||
"id": "xxx",
|
||
"query": "差旅报销标准",
|
||
"answer": "根据《差旅管理制度》...",
|
||
"created_at": 1717632000
|
||
}
|
||
]
|
||
}
|
||
```
|
||
|
||
### 3.3 获取对话列表
|
||
|
||
```
|
||
GET /v1/conversations?user=<user>&last_id=<id>&limit=20&sort_by=-updated_at
|
||
```
|
||
|
||
### 3.4 重命名对话
|
||
|
||
```
|
||
PATCH /v1/conversations/<conversation_id>/name
|
||
```
|
||
|
||
```json
|
||
{
|
||
"name": "报销相关问题"
|
||
}
|
||
```
|
||
|
||
### 3.5 删除对话
|
||
|
||
```
|
||
DELETE /v1/conversations/<conversation_id>
|
||
```
|
||
|
||
---
|
||
|
||
## 4. 知识库管理接口
|
||
|
||
### 4.1 创建知识库
|
||
|
||
```
|
||
POST /v1/datasets
|
||
```
|
||
|
||
```json
|
||
{
|
||
"name": "KB-RULE-制度流程",
|
||
"description": "公司各类管理制度和审批流程文档"
|
||
}
|
||
```
|
||
|
||
### 4.2 获取知识库列表
|
||
|
||
```
|
||
GET /v1/datasets?page=1&page_size=20
|
||
```
|
||
|
||
### 4.3 上传文档到知识库
|
||
|
||
**步骤一:创建上传任务**
|
||
|
||
```
|
||
POST /v1/datasets/<dataset_id>/document/create-by-file
|
||
Content-Type: multipart/form-data
|
||
```
|
||
|
||
| 参数 | 类型 | 必填 | 说明 |
|
||
|------|------|:----:|------|
|
||
| file | file | ✅ | 文档文件(PDF/Word/TXT/Markdown/Excel) |
|
||
| indexing_technique | string | ✅ | `high_quality`(高质量)或 `economy`(经济) |
|
||
| process_rule | object | ❌ | 分段规则 |
|
||
|
||
**分段规则示例**
|
||
|
||
```json
|
||
{
|
||
"mode": "automatic",
|
||
"rules": {
|
||
"pre_processing_rules": [
|
||
{"id": "remove_extra_spaces", "enabled": true},
|
||
{"id": "remove_urls_emails", "enabled": false}
|
||
],
|
||
"segmentation": {
|
||
"max_segmentation_tokens_length": 500,
|
||
"overlap_tokens_length": 50,
|
||
"separator": ["\n", "\n\n", "。", "!", "?", ";"]
|
||
}
|
||
}
|
||
}
|
||
```
|
||
|
||
**步骤二:查询上传进度**
|
||
|
||
```
|
||
GET /v1/datasets/<dataset_id>/documents/<document_id>/indexing-status
|
||
```
|
||
|
||
### 4.4 通过文本创建文档
|
||
|
||
```
|
||
POST /v1/datasets/<dataset_id>/document/create-by-text
|
||
```
|
||
|
||
```json
|
||
{
|
||
"name": "报销流程说明",
|
||
"text": "## 报销流程\n\n1. 填写报销单...\n2. 部门审批...\n3. 财务审核...",
|
||
"indexing_technique": "high_quality",
|
||
"process_rule": {
|
||
"mode": "automatic"
|
||
}
|
||
}
|
||
```
|
||
|
||
### 4.5 获取知识库文档列表
|
||
|
||
```
|
||
GET /v1/datasets/<dataset_id>/documents?page=1&page_size=20
|
||
```
|
||
|
||
### 4.6 删除文档
|
||
|
||
```
|
||
DELETE /v1/datasets/<dataset_id>/documents/<document_id>
|
||
```
|
||
|
||
---
|
||
|
||
## 5. 集成示例
|
||
|
||
### 5.1 Python 集成示例
|
||
|
||
```python
|
||
import requests
|
||
|
||
DIFY_BASE_URL = "http://<dify-host>/v1"
|
||
API_KEY = "app-<your-api-key>"
|
||
|
||
def chat(query: str, user: str = "default", conversation_id: str = None):
|
||
"""发送对话消息"""
|
||
headers = {
|
||
"Authorization": f"Bearer {API_KEY}",
|
||
"Content-Type": "application/json"
|
||
}
|
||
data = {
|
||
"query": query,
|
||
"inputs": {},
|
||
"response_mode": "blocking",
|
||
"user": user,
|
||
}
|
||
if conversation_id:
|
||
data["conversation_id"] = conversation_id
|
||
|
||
resp = requests.post(
|
||
f"{DIFY_BASE_URL}/chat-messages",
|
||
headers=headers,
|
||
json=data,
|
||
timeout=30
|
||
)
|
||
result = resp.json()
|
||
return {
|
||
"answer": result.get("answer", ""),
|
||
"conversation_id": result.get("conversation_id", ""),
|
||
"message_id": result.get("message_id", ""),
|
||
}
|
||
|
||
# 使用示例
|
||
result = chat("差旅报销标准是什么?", user="zhangsan")
|
||
print(result["answer"])
|
||
```
|
||
|
||
### 5.2 企业微信 Webhook 集成
|
||
|
||
```python
|
||
from flask import Flask, request, jsonify
|
||
import requests
|
||
|
||
app = Flask(__name__)
|
||
|
||
DIFY_API_KEY = "app-<your-api-key>"
|
||
DIFY_BASE_URL = "http://<dify-host>/v1"
|
||
|
||
@app.route("/wecom/webhook", methods=["POST"])
|
||
def wecom_webhook():
|
||
"""企业微信消息回调"""
|
||
data = request.json
|
||
user_query = data.get("Content", "")
|
||
user_id = data.get("FromUserName", "unknown")
|
||
|
||
# 调用 Dify API
|
||
resp = requests.post(
|
||
f"{DIFY_BASE_URL}/chat-messages",
|
||
headers={"Authorization": f"Bearer {DIFY_API_KEY}"},
|
||
json={
|
||
"query": user_query,
|
||
"response_mode": "blocking",
|
||
"user": user_id,
|
||
},
|
||
timeout=30
|
||
)
|
||
answer = resp.json().get("answer", "暂无回复")
|
||
|
||
# 返回企业微信消息格式
|
||
return jsonify({
|
||
"msgtype": "text",
|
||
"text": {"content": answer}
|
||
})
|
||
|
||
if __name__ == "__main__":
|
||
app.run(host="0.0.0.0", port=5000)
|
||
```
|
||
|
||
### 5.3 Node.js 集成示例
|
||
|
||
```javascript
|
||
const axios = require('axios');
|
||
|
||
const DIFY_BASE_URL = 'http://<dify-host>/v1';
|
||
const API_KEY = 'app-<your-api-key>';
|
||
|
||
async function chat(query, user = 'default') {
|
||
const { data } = await axios.post(
|
||
`${DIFY_BASE_URL}/chat-messages`,
|
||
{
|
||
query,
|
||
inputs: {},
|
||
response_mode: 'blocking',
|
||
user,
|
||
},
|
||
{
|
||
headers: {
|
||
'Authorization': `Bearer ${API_KEY}`,
|
||
'Content-Type': 'application/json',
|
||
},
|
||
timeout: 30000,
|
||
}
|
||
);
|
||
return {
|
||
answer: data.answer,
|
||
conversationId: data.conversation_id,
|
||
};
|
||
}
|
||
|
||
// 使用示例
|
||
chat('差旅报销标准是什么?', 'zhangsan')
|
||
.then(result => console.log(result.answer));
|
||
```
|
||
|
||
---
|
||
|
||
## 6. 错误处理
|
||
|
||
| HTTP 状态码 | 说明 | 处理建议 |
|
||
|:-----------:|------|---------|
|
||
| 400 | 请求参数错误 | 检查请求体格式 |
|
||
| 401 | API Key 无效 | 检查 Authorization Header |
|
||
| 403 | 无权限访问 | 检查 API Key 权限配置 |
|
||
| 429 | 请求频率超限 | 添加请求间隔/重试机制 |
|
||
| 500 | 服务端内部错误 | 查看 Dify 服务日志 |
|
||
|
||
**建议的重试策略**:
|
||
|
||
```python
|
||
import time
|
||
|
||
def chat_with_retry(query, max_retries=3, retry_delay=2):
|
||
for attempt in range(max_retries):
|
||
try:
|
||
return chat(query)
|
||
except requests.exceptions.Timeout:
|
||
if attempt == max_retries - 1:
|
||
raise
|
||
time.sleep(retry_delay * (attempt + 1))
|
||
except requests.exceptions.HTTPError as e:
|
||
if e.response.status_code == 429:
|
||
time.sleep(retry_delay * (attempt + 1))
|
||
else:
|
||
raise
|
||
```
|
||
|
||
---
|
||
|
||
## 7. API 速率限制
|
||
|
||
| 计划类型 | 限制 |
|
||
|----------|------|
|
||
| 自部署版 | 无官方限制,受服务器资源约束 |
|
||
| 建议配置 | 单用户 ≥ 60 次/分钟 |
|
||
|
||
---
|
||
|
||
_最后更新: 2026-06-06_
|