复制成功
请遵守本站许可
REPORT
Chapter_Post // Field_Report

Post_Ref: RL-DIFY-API

2026.05.29

Dify API集成完整指南

Echo HaoRan
Echo HaoRan
#技术手册
ANALYSIS

Dify API 集成完整指南#

概述#

Dify 的 API 让你将 AI 能力集成到现有应用程序中,而无需从零开始构建 AI 基础设施。你可以获得大型语言模型的全部功能,同时拥有创建自定义用户体验的灵活性。


为什么使用 Dify API#

核心优势#

优势说明
跳过后端复杂性直接从前端应用访问 LLM 能力,无需管理 AI 基础设施
可视化应用管理可视化设计和更新 AI 行为——更改会立即同步到所有 API 消费者
提供商灵活性在 AI 提供商之间切换并集中管理 API 密钥,无需更改代码

API 集成的工作原理#

PRTCL // PLAINTEXT
1. 构建应用
└─ 在 Dify Studio 中构建具有所需 AI 能力的应用
2. 生成 API 凭据
└─ 安全访问应用功能
3. 调用 API
└─ 从你的应用程序调用 API 获取 AI 驱动的响应
4. 用户交互
└─ 用户通过你的自定义界面交互,Dify 处理 AI 处理过程

功能继承#

你的 API 会自动继承 Dify 应用的所有功能:

  • 提示词
  • 知识库
  • 工具
  • 模型配置

API 访问设置#

访问 API 设置页面#

  1. 进入你的应用
  2. 在左侧边栏找到 API Access
  3. 进入 API 设置页面

创建 API 凭据#

步骤

  1. 点击 创建凭据
  2. 输入凭据名称(可选)
  3. 选择环境(开发、测试、生产)
  4. 点击 创建
  5. 保存生成的 API Key

重要提示

  • 永远不要在前端代码或客户端请求中暴露 API 密钥
  • 始终从后端调用 Dify API
  • 定期轮换密钥

查看 API 文档#

Dify 会自动生成针对你应用配置的完整 API 文档,包括:

  • 端点 URL
  • 请求方法
  • 请求参数
  • 响应格式
  • 示例代码

API 安全#

凭据管理#

最佳实践

PRTCL // YAML
凭据管理:
environment:
- name: "development"
api_key: "${DIFY_DEV_API_KEY}"
- name: "testing"
api_key: "${DIFY_TEST_API_KEY}"
- name: "production"
api_key: "${DIFY_PROD_API_KEY}"
lifecycle:
rotate: true
rotation_period: "90days"
revoke_unused: true

定期轮换

  • 每 90 天轮换一次密钥
  • 撤销未使用的凭据
  • 监控 API 使用情况

安全措施#

后端存储

PRTCL // PYTHON
# 使用环境变量存储 API 密钥
import os
DIFY_API_KEY = os.getenv("DIFY_API_KEY")

速率限制

PRTCL // PYTHON
from flask_limiter import Limiter
limiter = Limiter(
app=app,
key_func=get_remote_address,
default_limits=["100 per hour"]
)
@app.route("/api/chat")
@limiter.limit("20 per minute")
def chat():
pass

请求验证

PRTCL // PYTHON
def validate_request(request):
# 验证请求来源
if not verify_origin(request):
return False
# 验证请求格式
if not validate_format(request.json):
return False
return True

日志记录

PRTCL // PYTHON
import logging
logging.basicConfig(level=logging.INFO)
def log_api_call(endpoint, user_id, status):
logging.info(f"API Call: {endpoint} by {user_id} - Status: {status}")

文本生成应用 API#

端点信息#

URLPOST https://api.dify.ai/v1/completion-messages

请求参数#

参数类型必填说明
inputsobject应用输入变量
response_modestring响应模式:streaming, blocking
userstring用户标识
filesarray文件列表

cURL 示例#

PRTCL // BASH
Terminal window
curl --location --request POST 'https://api.dify.ai/v1/completion-messages' \
--header 'Authorization: Bearer ENTER-YOUR-SECRET-KEY' \
--header 'Content-Type: application/json' \
--data-raw '{
"inputs": {
"text": "Hello, how are you?"
},
"response_mode": "streaming",
"user": "abc-123"
}'

Python 示例#

PRTCL // PYTHON
import requests
import json
url = "https://api.dify.ai/v1/completion-messages"
headers = {
'Authorization': 'Bearer ENTER-YOUR-SECRET-KEY',
'Content-Type': 'application/json',
}
data = {
"inputs": {
"text": 'Hello, how are you?'
},
"response_mode": "streaming",
"user": "abc-123"
}
response = requests.post(url, headers=headers, data=json.dumps(data))
print(response.text)

响应格式#

PRTCL // JSON
{
"result": "Hello! I'm doing well, thank you for asking. How can I assist you today?",
"message_id": "550e8400-e29b-41d4-a716-446655440000",
"created_at": 1678901234,
"metadata": {
"usage": {
"prompt_tokens": 10,
"prompt_unit_price": "0.00001",
"prompt_price_unit": "1K tokens",
"prompt_price": "0.0001",
"completion_tokens": 20,
"completion_unit_price": "0.00002",
"completion_price_unit": "1K tokens",
"completion_price": "0.0004",
"total_tokens": 30,
"total_price": "0.0005",
"currency": "USD",
"latency": 1.5
}
}
}

对话应用 API#

端点信息#

URLPOST https://api.dify.ai/v1/chat-messages

conversation_id 的关键注意事项#

重要说明

  • API 不会共享 WebApp 创建的对话
  • 通过 API 创建的对话与在 WebApp 界面中创建的对话是隔离的

生成 conversation_id

PRTCL // PYTHON
# 开始新对话时,将 conversation_id 字段留空
data = {
"inputs": {},
"query": "Hello",
"response_mode": "streaming",
"user": "abc-123"
# conversation_id 不设置,系统将生成新的
}

在现有会话中处理 conversation_id

PRTCL // PYTHON
# 一旦生成 conversation_id,后续调用应包含此 ID
data = {
"inputs": {}, # 会被忽略
"query": "How are you?",
"response_mode": "streaming",
"conversation_id": "1c7e55fb-1ba2-4e10-81b5-30addcea2276",
"user": "abc-123"
}

管理动态变量

PRTCL // PYTHON
# 使用会话变量调整机器人行为
data = {
"query": "Change your language to Chinese",
"response_mode": "streaming",
"conversation_id": "1c7e55fb-1ba2-4e10-81b5-30addcea2276",
"user": "abc-123",
"variables": {
"language": "Chinese"
}
}

请求参数#

参数类型必填说明
inputsobject应用输入变量
querystring用户查询
response_modestring响应模式:streaming, blocking
conversation_idstring对话 ID
userstring用户标识
filesarray文件列表

cURL 示例#

PRTCL // BASH
Terminal window
curl --location --request POST 'https://api.dify.ai/v1/chat-messages' \
--header 'Authorization: Bearer ENTER-YOUR-SECRET-KEY' \
--header 'Content-Type: application/json' \
--data-raw '{
"inputs": {},
"query": "Hello",
"response_mode": "streaming",
"conversation_id": "1c7e55fb-1ba2-4e10-81b5-30addcea2276",
"user": "abc-123"
}'

Python 示例#

PRTCL // PYTHON
import requests
import json
url = 'https://api.dify.ai/v1/chat-messages'
headers = {
'Authorization': 'Bearer ENTER-YOUR-SECRET-KEY',
'Content-Type': 'application/json',
}
data = {
"inputs": {},
"query": "Hello",
"response_mode": "streaming",
"conversation_id": "1c7e55fb-1ba2-4e10-81b5-30addcea2276",
"user": "abc-123"
}
response = requests.post(url, headers=headers, data=json.dumps(data))
print(response.text)

响应格式#

PRTCL // JSON
{
"result": "Hello! I'm doing well, thank you for asking. How can I assist you today?",
"conversation_id": "1c7e55fb-1ba2-4e10-81b5-30addcea2276",
"message_id": "550e8400-e29b-41d4-a716-446655440001",
"created_at": 1678901234,
"metadata": {
"usage": {
"prompt_tokens": 15,
"prompt_unit_price": "0.00001",
"prompt_price_unit": "1K tokens",
"prompt_price": "0.00015",
"completion_tokens": 25,
"completion_unit_price": "0.00002",
"completion_price_unit": "1K tokens",
"completion_price": "0.0005",
"total_tokens": 40,
"total_price": "0.00065",
"currency": "USD",
"latency": 2.0
}
}
}

流式响应处理#

流式响应格式#

流式响应以 Server-Sent Events (SSE) 格式返回:

PRTCL // PLAINTEXT
data: {"event": "message", "task_id": "xxx", "id": "xxx", "answer": "Hello"}
data: {"event": "message", "task_id": "xxx", "id": "xxx", "answer": "Hello, how"}
data: {"event": "message", "task_id": "xxx", "id": "xxx", "answer": "Hello, how are"}
data: {"event": "message_end", "task_id": "xxx", "id": "xxx", "metadata": {...}}

Python 流式处理示例#

PRTCL // PYTHON
import requests
import json
def stream_chat():
url = 'https://api.dify.ai/v1/chat-messages'
headers = {
'Authorization': 'Bearer ENTER-YOUR-SECRET-KEY',
'Content-Type': 'application/json',
}
data = {
"inputs": {},
"query": "Tell me a story",
"response_mode": "streaming",
"user": "abc-123"
}
response = requests.post(url, headers=headers, json=data, stream=True)
for line in response.iter_lines():
if line:
line = line.decode('utf-8')
if line.startswith('data: '):
data = json.loads(line[6:])
if data.get('event') == 'message':
print(data.get('answer'), end='', flush=True)
elif data.get('event') == 'message_end':
print('\n\nResponse completed!')
print(f"Metadata: {data.get('metadata')}")
stream_chat()

JavaScript 流式处理示例#

PRTCL // JAVASCRIPT
async function streamChat() {
const response = await fetch('https://api.dify.ai/v1/chat-messages', {
method: 'POST',
headers: {
'Authorization': 'Bearer ENTER-YOUR-SECRET-KEY',
'Content-Type': 'application/json',
},
body: JSON.stringify({
inputs: {},
query: "Tell me a story",
response_mode: "streaming",
user: "abc-123"
})
});
const reader = response.body.getReader();
const decoder = new TextDecoder();
while (true) {
const { done, value } = await reader.read();
if (done) break;
const chunk = decoder.decode(value);
const lines = chunk.split('\n');
for (const line of lines) {
if (line.startsWith('data: ')) {
const data = JSON.parse(line.substring(6));
if (data.event === 'message') {
process.stdout.write(data.answer);
} else if (data.event === 'message_end') {
console.log('\n\nResponse completed!');
console.log('Metadata:', data.metadata);
}
}
}
}
}
streamChat();

错误处理#

常见错误代码#

错误代码说明解决方案
401未授权检查 API 密钥
429速率限制减少请求频率
500服务器错误稍后重试
400请求错误检查请求参数

错误处理示例#

PRTCL // PYTHON
import requests
from requests.exceptions import RequestException
def chat_with_retry(url, headers, data, max_retries=3):
for attempt in range(max_retries):
try:
response = requests.post(url, headers=headers, json=data)
response.raise_for_status()
return response.json()
except RequestException as e:
if response.status_code == 429:
wait_time = 2 ** attempt # 指数退避
time.sleep(wait_time)
continue
elif response.status_code >= 500:
if attempt < max_retries - 1:
time.sleep(wait_time)
continue
raise e
return None

最佳实践#

性能优化#

批量请求

PRTCL // PYTHON
def batch_chat(messages):
# 批量处理多个请求
results = []
for message in messages:
result = chat_with_retry(url, headers, {
"inputs": {},
"query": message,
"response_mode": "blocking",
"user": "abc-123"
})
results.append(result)
return results

缓存响应

PRTCL // PYTHON
from functools import lru_cache
@lru_cache(maxsize=100)
def cached_chat(query):
return chat_with_retry(url, headers, {
"inputs": {},
"query": query,
"response_mode": "blocking",
"user": "abc-123"
})

监控和日志#

监控 API 使用

PRTCL // PYTHON
import logging
def log_api_call(endpoint, status, response_time):
logging.info(f"API: {endpoint} | Status: {status} | Time: {response_time}ms")
def monitor_chat():
start_time = time.time()
response = chat_with_retry(url, headers, data)
response_time = (time.time() - start_time) * 1000
log_api_call('chat', response.status_code, response_time)
return response

测试策略#

单元测试

PRTCL // PYTHON
import unittest
class TestDifyAPI(unittest.TestCase):
def test_chat(self):
response = chat_with_retry(url, headers, {
"inputs": {},
"query": "Hello",
"response_mode": "blocking",
"user": "test"
})
self.assertIsNotNone(response)
self.assertIn('result', response)

集成测试

PRTCL // PYTHON
def test_conversation_flow():
# 开始对话
response1 = chat_with_retry(url, headers, {
"inputs": {},
"query": "Hello",
"response_mode": "blocking",
"user": "test"
})
conversation_id = response1['conversation_id']
# 继续对话
response2 = chat_with_retry(url, headers, {
"inputs": {},
"query": "How are you?",
"response_mode": "blocking",
"conversation_id": conversation_id,
"user": "test"
})
self.assertIsNotNone(response2)

资源链接#


最后更新: 2026-03-12 作者: EchoHaoRan

R P
Rhine Lab Pioneer Division
Auth_Verified: 2026.05.29
// END OF POST

订阅

通过 RSS 订阅本站,新文章发布时第一时间收到通知。

Follow
Classified
Chapter_06
Protocol_Ref: CC-BY-NC-SA-4.0

Dify API集成完整指南

Author: CHONGXIReleased: 2026.05.29

Licensed under CC BY-NC-SA 4.0

评论

© 2025-2026 EchoSpace
Powered by Astro & echohaoran Non-Collaborative_Entity // Protocol_V.4.21