139 lines
5.7 KiB
Python
139 lines
5.7 KiB
Python
|
|
"""
|
|
backend/app/services/dify.py
|
|
文件用途:Dify API 集成服务
|
|
引用文件:requests, json, models, config
|
|
逻辑关系:负责与 Dify 平台进行 HTTP 通信,处理 SSE 流式响应,并记录审计日志
|
|
"""
|
|
import requests
|
|
import json
|
|
import time
|
|
from flask import current_app
|
|
from app.models import ChatLog, db
|
|
from app.config import Config
|
|
|
|
class DifyService:
|
|
"""
|
|
Dify 服务类
|
|
用途:封装与 Dify API 的交互逻辑
|
|
"""
|
|
|
|
@staticmethod
|
|
def stream_chat(query: str, user_id: int, agent, conversation_id: str = None):
|
|
"""
|
|
生成器函数:向 Dify 发起请求并流式返回
|
|
用途:处理 /v1/chat-messages 接口的流式响应
|
|
核心逻辑:
|
|
1. 构造请求头与 Payload
|
|
2. 使用 requests.post(stream=True) 发起请求
|
|
3. 逐行读取 SSE 数据
|
|
4. 解析 'data: ' 开头的行,透传给前端
|
|
5. 在 'message_end' 事件中记录完整日志到数据库
|
|
参数:
|
|
query: 用户提问内容
|
|
user_id: 当前用户 ID
|
|
agent: Agent 模型对象,包含 API Key
|
|
conversation_id: 会话 ID (可选)
|
|
输出:
|
|
Yields SSE 格式字符串 "data: {...}\n\n"
|
|
"""
|
|
# 使用 Agent 自定义的 API Base URL,若未配置则使用全局配置
|
|
base_url = agent.api_base_url if agent.api_base_url else Config.DIFY_API_BASE
|
|
# 移除末尾斜杠以避免双斜杠问题
|
|
base_url = base_url.rstrip('/')
|
|
url = f"{base_url}/chat-messages"
|
|
|
|
headers = {
|
|
'Authorization': f'Bearer {agent.dify_api_key}',
|
|
'Content-Type': 'application/json'
|
|
}
|
|
payload = {
|
|
"inputs": {},
|
|
"query": query,
|
|
"response_mode": "streaming",
|
|
"conversation_id": conversation_id,
|
|
"user": str(user_id)
|
|
}
|
|
|
|
# 记录开始时间,用于计算耗时
|
|
start_time = time.time()
|
|
# 用于收集流式片段拼接完整回答
|
|
full_answer = []
|
|
|
|
try:
|
|
# stream=True 关键参数,建立长连接
|
|
# 设置连接超时为 5 秒,读取超时为 60 秒
|
|
with requests.post(url, headers=headers, json=payload, stream=True, timeout=(5, 60)) as response:
|
|
response.raise_for_status()
|
|
|
|
# 逐行迭代响应内容
|
|
for line in response.iter_lines():
|
|
if line:
|
|
decoded_line = line.decode('utf-8')
|
|
# 识别 SSE 数据行
|
|
if decoded_line.startswith('data: '):
|
|
json_str = decoded_line[6:]
|
|
try:
|
|
data = json.loads(json_str)
|
|
event = data.get('event')
|
|
|
|
# 核心:将 Dify 的原始数据透传给前端
|
|
yield f"data: {json_str}\n\n"
|
|
|
|
# 收集完整回答用于日志
|
|
if event == 'message':
|
|
full_answer.append(data.get('answer', ''))
|
|
elif event == 'message_end':
|
|
# 对话结束,记录日志
|
|
latency = int((time.time() - start_time) * 1000)
|
|
metadata = data.get('metadata', {})
|
|
usage = metadata.get('usage', {})
|
|
|
|
# 显式使用应用上下文
|
|
with current_app.app_context():
|
|
DifyService._log_chat(
|
|
user_id=user_id,
|
|
agent_id=agent.id,
|
|
conversation_id=data.get('conversation_id') or conversation_id,
|
|
query=query,
|
|
answer="".join(full_answer),
|
|
tokens=usage.get('total_tokens', 0),
|
|
latency=latency
|
|
)
|
|
|
|
except json.JSONDecodeError:
|
|
continue
|
|
else:
|
|
# 处理 keep-alive 等其他行
|
|
pass
|
|
|
|
except requests.exceptions.RequestException as e:
|
|
# 异常处理:返回标准错误格式给前端
|
|
error_msg = json.dumps({"event": "error", "message": str(e)})
|
|
yield f"data: {error_msg}\n\n"
|
|
|
|
@staticmethod
|
|
def _log_chat(user_id, agent_id, conversation_id, query, answer, tokens, latency):
|
|
"""
|
|
内部方法:写入数据库日志
|
|
用途:将对话详情持久化到 ChatLog 表
|
|
"""
|
|
try:
|
|
# 确保在应用上下文中
|
|
chat_log = ChatLog(
|
|
user_id=user_id,
|
|
agent_id=agent_id,
|
|
conversation_id=conversation_id,
|
|
query=query,
|
|
answer=answer,
|
|
tokens_used=tokens or 0,
|
|
latency=latency or 0
|
|
)
|
|
db.session.add(chat_log)
|
|
db.session.commit()
|
|
except Exception as e:
|
|
# Re-acquire logger from current_app as it might be detached
|
|
if current_app:
|
|
current_app.logger.error(f"Failed to log chat: {e}")
|
|
db.session.rollback()
|