61 lines
2.3 KiB
Python
61 lines
2.3 KiB
Python
"""
|
|
api/chat/feedback.py
|
|
|
|
用途:处理用户对聊天回答的评分与文字反馈。
|
|
依赖:chat.shared、ChatLog、Feedback、chat_bp。
|
|
逻辑:定位当前用户和 Agent 的最近一条会话日志,创建或更新对应反馈记录。
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
from .shared import * # noqa: F403
|
|
from . import chat_bp
|
|
|
|
|
|
@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):
|
|
raise ForbiddenError('feedback is disabled')
|
|
if score is None:
|
|
raise ValidationError('score is required')
|
|
try:
|
|
score_value = int(score)
|
|
except (TypeError, ValueError):
|
|
raise ValidationError('score must be an integer')
|
|
if score_value < 1 or score_value > 5:
|
|
raise ValidationError('score must be between 1 and 5')
|
|
user = getattr(g, 'current_user', None)
|
|
agent = getattr(g, 'current_agent', None)
|
|
if user is None or agent is None:
|
|
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Missing user or agent context', http_status=500)
|
|
chat_logs_query = db.session.query(ChatLog).filter_by(user_id=user.id, agent_id=agent.id)
|
|
if conversation_id:
|
|
chat_logs_query = chat_logs_query.filter(
|
|
or_(ChatLog.session_id == conversation_id, ChatLog.conversation_id == conversation_id)
|
|
)
|
|
|
|
# 取最新一条对话日志
|
|
chat_log = chat_logs_query.order_by(ChatLog.created_at.desc()).first()
|
|
if not chat_log:
|
|
raise NotFoundError('ChatLog not found')
|
|
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'})
|