245 lines
8.8 KiB
Python
245 lines
8.8 KiB
Python
|
|
"""
|
|
backend/app/api/chat.py
|
|
文件用途:定义聊天相关 API 路由
|
|
引用文件:flask, services.dify, decorators, models
|
|
逻辑关系:作为前端与 Dify 之间的 BFF 层,负责转发请求并流式返回结果
|
|
"""
|
|
from flask import Blueprint, request, Response, stream_with_context, jsonify, g, current_app
|
|
from sqlalchemy import func, desc
|
|
from app.services.dify import DifyService
|
|
from app.services.integration_api import IntegrationApiService
|
|
from app.decorators import require_agent_permission
|
|
from app.models import Agent, ChatLog, Feedback
|
|
from app import db
|
|
|
|
# 定义 Blueprint,用于在应用工厂中注册路由前缀 /api/chat
|
|
chat_bp = Blueprint('chat', __name__)
|
|
|
|
|
|
@chat_bp.route('/sessions', methods=['GET'])
|
|
@require_agent_permission
|
|
def get_chat_sessions():
|
|
"""
|
|
获取当前用户与当前 Agent 的历史会话列表
|
|
"""
|
|
user = getattr(g, 'current_user', None)
|
|
agent = getattr(g, 'current_agent', None)
|
|
|
|
if user is None or agent is None:
|
|
return jsonify({'error': 'Missing context'}), 500
|
|
|
|
# 聚合查询:按 conversation_id 分组,获取最新时间
|
|
# 注意:这里简化处理,直接取最新一条记录的 query 作为标题(或者第一条,取决于需求)
|
|
# 为了性能,这里我们取 max(created_at) 和 max(query) - 这只是一个近似值
|
|
# 更严谨的做法是先查出 conversation_ids,再查详情。
|
|
# 这里为了简单,我们假设 query 不为空
|
|
|
|
# 修正逻辑:先查出最近的 20 个 conversation_id
|
|
subquery = db.session.query(
|
|
ChatLog.conversation_id,
|
|
func.max(ChatLog.created_at).label('last_active')
|
|
).filter_by(
|
|
user_id=user.id,
|
|
agent_id=agent.id
|
|
).group_by(ChatLog.conversation_id).subquery()
|
|
|
|
# 联表查询获取详细信息,按时间倒序
|
|
results = db.session.query(
|
|
subquery.c.conversation_id,
|
|
subquery.c.last_active,
|
|
ChatLog.query
|
|
).join(
|
|
ChatLog,
|
|
(ChatLog.conversation_id == subquery.c.conversation_id) &
|
|
(ChatLog.created_at == subquery.c.last_active)
|
|
).order_by(desc(subquery.c.last_active)).limit(20).all()
|
|
|
|
sessions = []
|
|
for row in results:
|
|
if not row.conversation_id:
|
|
continue
|
|
sessions.append({
|
|
'id': 0, # 前端需要 id key
|
|
'conversation_id': row.conversation_id,
|
|
'title': row.query[:30] + ('...' if len(row.query) > 30 else '') if row.query else 'New Chat',
|
|
'created_at': row.last_active.isoformat()
|
|
})
|
|
|
|
return jsonify(sessions)
|
|
|
|
|
|
@chat_bp.route('/messages', methods=['GET'])
|
|
@require_agent_permission
|
|
def get_chat_messages():
|
|
"""
|
|
获取指定会话的消息记录
|
|
"""
|
|
conversation_id = request.args.get('conversation_id')
|
|
if not conversation_id:
|
|
return jsonify([])
|
|
|
|
logs = db.session.query(ChatLog).filter_by(
|
|
conversation_id=conversation_id
|
|
).order_by(ChatLog.created_at.asc()).all()
|
|
|
|
messages = []
|
|
for log in logs:
|
|
messages.append({'role': 'user', 'content': log.query})
|
|
messages.append({
|
|
'role': 'assistant',
|
|
'content': log.answer,
|
|
'retriever_resources': log.retriever_resources or [],
|
|
'attribution_parts': log.attribution_parts or []
|
|
})
|
|
|
|
return jsonify(messages)
|
|
|
|
|
|
@chat_bp.route('/completions', methods=['POST'])
|
|
@require_agent_permission
|
|
def chat_completions():
|
|
"""
|
|
SSE 流式聊天接口
|
|
用途:接收前端问题,调用 DifyService.stream_chat,并以 text/event-stream 形式返回
|
|
核心逻辑:
|
|
1. 从请求体中读取 query / agent_id / conversation_id
|
|
2. 通过装饰器已完成权限校验,并在 g 中注入 current_user / current_agent
|
|
3. 使用 Flask 的 stream_with_context 包裹生成器,实现流式推送
|
|
传入参数:
|
|
无(从 request.json 读取)
|
|
返回值:
|
|
Flask Response 对象,mimetype=text/event-stream
|
|
"""
|
|
# 解析 JSON 请求体
|
|
data = request.get_json() or {}
|
|
# 提取用户提问内容
|
|
query = data.get('query')
|
|
# 提取会话 ID(可选)
|
|
conversation_id = data.get('conversation_id')
|
|
|
|
# 从全局 g 中获取装饰器注入的用户和 Agent 对象
|
|
user = getattr(g, 'current_user', None)
|
|
agent = getattr(g, 'current_agent', None)
|
|
|
|
current_app.logger.info(
|
|
"[chat-api] /completions request user_id=%s agent_id=%s query_len=%s conversation_id=%s",
|
|
getattr(user, 'id', None),
|
|
getattr(agent, 'id', None),
|
|
len(query or ''),
|
|
conversation_id,
|
|
)
|
|
|
|
# 安全兜底:如果装饰器未正确注入,返回错误
|
|
if user is None or agent is None:
|
|
current_app.logger.error("[chat-api] missing user/agent context user=%s agent=%s", bool(user), bool(agent))
|
|
return jsonify({'error': 'Missing user or agent context'}), 500
|
|
|
|
# 返回 SSE 响应,mimetype 设为 text/event-stream
|
|
return Response(
|
|
stream_with_context(
|
|
DifyService.stream_chat(query, user.id, agent, conversation_id)
|
|
),
|
|
mimetype='text/event-stream',
|
|
headers={
|
|
'Cache-Control': 'no-cache',
|
|
'Content-Type': 'text/event-stream; charset=utf-8',
|
|
'Connection': 'keep-alive',
|
|
# 对于 Nginx 反向代理,需要关闭缓冲以支持实时流式传输
|
|
'X-Accel-Buffering': 'no'
|
|
}
|
|
)
|
|
|
|
|
|
@chat_bp.route('/feedback', methods=['POST'])
|
|
@require_agent_permission
|
|
def submit_feedback():
|
|
"""
|
|
提交对回答的评分与评论
|
|
用途:在对话结束后,由前端发送评分(1~5)和文字意见
|
|
核心逻辑:
|
|
1. 从请求体中读取 score/comment/conversation_id
|
|
2. 根据当前 user/agent 与 conversation_id 查找最近一条 ChatLog
|
|
3. 为该 ChatLog 创建或更新 Feedback 记录
|
|
"""
|
|
data = request.get_json() or {}
|
|
score = data.get('score')
|
|
comment = data.get('comment') or ''
|
|
conversation_id = data.get('conversation_id')
|
|
|
|
if not current_app.config.get('FEEDBACK_ENABLED', True):
|
|
return jsonify({'error': 'feedback is disabled'}), 403
|
|
|
|
if score is None:
|
|
return jsonify({'error': 'score is required'}), 400
|
|
|
|
try:
|
|
score_value = int(score)
|
|
except (TypeError, ValueError):
|
|
return jsonify({'error': 'score must be an integer'}), 400
|
|
|
|
if score_value < 1 or score_value > 5:
|
|
return jsonify({'error': 'score must be between 1 and 5'}), 400
|
|
|
|
user = getattr(g, 'current_user', None)
|
|
agent = getattr(g, 'current_agent', None)
|
|
if user is None or agent is None:
|
|
return jsonify({'error': 'Missing user or agent context'}), 500
|
|
|
|
# 构造查询:限定在当前用户和 Agent 范围内
|
|
query = ChatLog.query.filter_by(user_id=user.id, agent_id=agent.id)
|
|
if conversation_id:
|
|
query = query.filter_by(conversation_id=conversation_id)
|
|
|
|
# 取最新一条对话日志
|
|
chat_log = query.order_by(ChatLog.created_at.desc()).first()
|
|
if not chat_log:
|
|
return jsonify({'error': 'ChatLog not found'}), 404
|
|
|
|
# 如果已存在反馈,则更新;否则新建
|
|
if chat_log.feedback:
|
|
chat_log.feedback.score = score_value
|
|
chat_log.feedback.comment = comment
|
|
else:
|
|
fb = Feedback(
|
|
chat_log_id=chat_log.id,
|
|
score=score_value,
|
|
comment=comment,
|
|
)
|
|
db.session.add(fb)
|
|
|
|
db.session.commit()
|
|
return jsonify({'status': 'ok'})
|
|
|
|
|
|
@chat_bp.route('/source-file', methods=['GET'])
|
|
@require_agent_permission
|
|
def resolve_source_file():
|
|
"""
|
|
Resolve original source download URL by Dify dataset/document IDs.
|
|
"""
|
|
dataset_id = (request.args.get('dataset_id') or '').strip()
|
|
remote_document_id = (request.args.get('remote_document_id') or '').strip()
|
|
if not dataset_id or not remote_document_id:
|
|
current_app.logger.warning(
|
|
"[source-file] missing required params: dataset_id=%r remote_document_id_present=%s remote_document_id_preview=%r query_args=%s",
|
|
dataset_id,
|
|
bool(remote_document_id),
|
|
(remote_document_id[:8] + "...") if remote_document_id else "",
|
|
dict(request.args),
|
|
)
|
|
return jsonify({'error': 'dataset_id and remote_document_id are required'}), 400
|
|
|
|
payload = IntegrationApiService.lookup_file_by_dify(dataset_id, remote_document_id)
|
|
if not payload:
|
|
return jsonify({'error': 'source file mapping not found'}), 404
|
|
|
|
return jsonify({
|
|
'dataset_id': dataset_id,
|
|
'remote_document_id': remote_document_id,
|
|
'source_filename': payload.get('source_filename'),
|
|
'source_ext': payload.get('source_ext'),
|
|
'source_download_url': payload.get('source_download_url'),
|
|
'download_url_expires_at': payload.get('download_url_expires_at'),
|
|
})
|