Spaces:
Running
Running
File size: 15,667 Bytes
8275526 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 |
from flask import Blueprint, request, jsonify
import logging
from core.rag_pipeline import RAGPipeline
from core.embedding_model import get_embedding_model
from models.conversation_model import Conversation
from flask_jwt_extended import jwt_required, get_jwt_identity
import datetime
# Cấu hình logging
logger = logging.getLogger(__name__)
# Tạo blueprint
chat_routes = Blueprint('chat', __name__)
# Khởi tạo RAG Pipeline một lần duy nhất khi module được load
rag_pipeline = None
def get_rag_pipeline():
"""Singleton pattern để tránh khởi tạo lại RAG Pipeline"""
global rag_pipeline
if rag_pipeline is None:
logger.info("Khởi tạo RAG Pipeline lần đầu")
rag_pipeline = RAGPipeline()
return rag_pipeline
# Hàm tạo tiêu đề từ tin nhắn
def create_title_from_message(message, max_length=50):
"""Tạo tiêu đề cuộc trò chuyện từ tin nhắn đầu tiên của người dùng"""
message = message.strip().replace('\n', ' ')
if len(message) <= max_length:
return message
return message[:max_length-3] + "..."
@chat_routes.route('/chat', methods=['POST'])
@jwt_required()
def chat():
"""API endpoint để xử lý tin nhắn chat"""
try:
data = request.json
message = data.get('message')
age = data.get('age', 1)
conversation_id = data.get('conversation_id')
user_id = get_jwt_identity()
if not message:
return jsonify({
"success": False,
"error": "Vui lòng nhập tin nhắn"
}), 400
logger.info(f"Nhận tin nhắn từ user {user_id}: {message[:50]}...")
# Xử lý conversation
if conversation_id:
conversation = Conversation.find_by_id(conversation_id)
if not conversation or str(conversation.user_id) != user_id:
return jsonify({
"success": False,
"error": "Không tìm thấy cuộc trò chuyện"
}), 404
if len(conversation.messages) == 0:
final_title = create_title_from_message(message, 50)
conversation.title = final_title
logger.info(f"Cập nhật title cho conversation {conversation_id}: '{final_title}'")
else:
final_title = create_title_from_message(message, 50)
conversation = Conversation.create(
user_id=user_id,
title=final_title,
age_context=age
)
logger.info(f"Tạo conversation mới với title: '{final_title}'")
# Thêm tin nhắn của user
conversation.add_message("user", message)
# Sử dụng RAG Pipeline để generate response
pipeline = get_rag_pipeline()
# Generate response sử dụng RAG
logger.info("Bắt đầu generate response với RAG Pipeline")
response_data = pipeline.generate_response(message, age)
if response_data.get("success"):
bot_response = response_data.get("response", "Xin lỗi, tôi không thể trả lời câu hỏi này.")
sources = response_data.get("sources", [])
# Thêm tin nhắn bot vào conversation
conversation.add_message("bot", bot_response, sources=sources)
logger.info(f"Đã generate response thành công cho conversation {conversation.conversation_id}")
return jsonify({
"success": True,
"response": bot_response,
"sources": sources,
"conversation_id": str(conversation.conversation_id)
})
else:
error_msg = response_data.get("error", "Không thể tạo phản hồi")
logger.error(f"Lỗi generate response: {error_msg}")
return jsonify({
"success": False,
"error": error_msg
}), 500
except Exception as e:
logger.error(f"Lỗi xử lý chat: {str(e)}")
return jsonify({
"success": False,
"error": f"Lỗi máy chủ: {str(e)}"
}), 500
@chat_routes.route('/messages/<message_id>/edit', methods=['PUT'])
@jwt_required()
def edit_message(message_id):
"""API endpoint để chỉnh sửa tin nhắn"""
try:
data = request.json
new_content = data.get('content')
conversation_id = data.get('conversation_id')
age = data.get('age', 1)
user_id = get_jwt_identity()
if not new_content or not conversation_id:
return jsonify({
"success": False,
"error": "Thiếu thông tin cần thiết"
}), 400
logger.info(f"Edit message {message_id} in conversation {conversation_id}: {new_content[:50]}...")
# Tìm conversation
conversation = Conversation.find_by_id(conversation_id)
if not conversation or str(conversation.user_id) != user_id:
return jsonify({
"success": False,
"error": "Không tìm thấy cuộc trò chuyện"
}), 404
# Tìm message và kiểm tra quyền
message_found = False
for msg in conversation.messages:
if str(msg.get('_id', msg.get('id'))) == message_id:
if msg['role'] != 'user':
return jsonify({
"success": False,
"error": "Chỉ có thể chỉnh sửa tin nhắn của người dùng"
}), 400
message_found = True
break
if not message_found:
return jsonify({
"success": False,
"error": "Không tìm thấy tin nhắn"
}), 404
# Cập nhật tin nhắn và xóa tất cả tin nhắn sau nó
success, result_message = conversation.edit_message(message_id, new_content)
if not success:
return jsonify({
"success": False,
"error": result_message
}), 400
# Tạo phản hồi mới với RAG Pipeline
pipeline = get_rag_pipeline()
response_data = pipeline.generate_response(new_content, age)
if response_data.get("success"):
bot_response = response_data.get("response", "Xin lỗi, tôi không thể trả lời câu hỏi này.")
sources = response_data.get("sources", [])
# Thêm phản hồi bot mới
success, bot_message = conversation.regenerate_bot_response_after_edit(message_id, bot_response, sources)
if success:
# Trả về conversation đã cập nhật
updated_conversation = Conversation.find_by_id(conversation_id)
logger.info(f"Successfully edited message and generated new response")
return jsonify({
"success": True,
"message": "Đã chỉnh sửa tin nhắn và tạo phản hồi mới",
"conversation": updated_conversation.to_dict()
})
else:
return jsonify({
"success": False,
"error": bot_message
}), 500
else:
return jsonify({
"success": False,
"error": response_data.get("error", "Không thể tạo phản hồi mới")
}), 500
except Exception as e:
logger.error(f"Lỗi chỉnh sửa tin nhắn: {str(e)}")
return jsonify({
"success": False,
"error": f"Lỗi máy chủ: {str(e)}"
}), 500
@chat_routes.route('/messages/<message_id>/regenerate', methods=['POST'])
@jwt_required()
def regenerate_response(message_id):
"""API endpoint để tạo lại phản hồi"""
try:
data = request.json
conversation_id = data.get('conversation_id')
age = data.get('age', 1)
user_id = get_jwt_identity()
if not conversation_id:
return jsonify({
"success": False,
"error": "Thiếu conversation_id"
}), 400
logger.info(f"Regenerate response for message {message_id} in conversation {conversation_id}")
# Tìm conversation
conversation = Conversation.find_by_id(conversation_id)
if not conversation or str(conversation.user_id) != user_id:
return jsonify({
"success": False,
"error": "Không tìm thấy cuộc trò chuyện"
}), 404
# Tìm tin nhắn và tin nhắn user trước đó
user_message = None
for i, msg in enumerate(conversation.messages):
if str(msg.get('_id', msg.get('id'))) == message_id:
if msg['role'] != 'bot':
return jsonify({
"success": False,
"error": "Chỉ có thể regenerate phản hồi của bot"
}), 400
# Tìm tin nhắn user trước đó
if i > 0 and conversation.messages[i-1]['role'] == 'user':
user_message = conversation.messages[i-1]['content']
break
if not user_message:
return jsonify({
"success": False,
"error": "Không tìm thấy tin nhắn người dùng tương ứng"
}), 404
# Sử dụng RAG Pipeline để generate response mới
pipeline = get_rag_pipeline()
response_data = pipeline.generate_response(user_message, age)
if response_data.get("success"):
bot_response = response_data.get("response", "Xin lỗi, tôi không thể trả lời câu hỏi này.")
sources = response_data.get("sources", [])
success, result_message = conversation.regenerate_response(message_id, bot_response, sources)
if success:
# Trả về conversation đã cập nhật
updated_conversation = Conversation.find_by_id(conversation_id)
logger.info(f"Successfully regenerated response")
return jsonify({
"success": True,
"conversation": updated_conversation.to_dict()
})
else:
return jsonify({
"success": False,
"error": result_message
}), 400
else:
return jsonify({
"success": False,
"error": response_data.get("error", "Không thể tạo phản hồi mới")
}), 500
except Exception as e:
logger.error(f"Lỗi regenerate response: {str(e)}")
return jsonify({
"success": False,
"error": f"Lỗi máy chủ: {str(e)}"
}), 500
@chat_routes.route('/messages/<message_id>/versions/<int:version>', methods=['PUT'])
@jwt_required()
def switch_message_version(message_id, version):
"""API endpoint để chuyển đổi version của tin nhắn"""
try:
data = request.json
conversation_id = data.get('conversation_id')
user_id = get_jwt_identity()
if not conversation_id:
return jsonify({
"success": False,
"error": "Thiếu conversation_id"
}), 400
logger.info(f"Switching message {message_id} to version {version} in conversation {conversation_id}")
# Tìm conversation
conversation = Conversation.find_by_id(conversation_id)
if not conversation or str(conversation.user_id) != user_id:
return jsonify({
"success": False,
"error": "Không tìm thấy cuộc trò chuyện"
}), 404
# Debug: Log current conversation state before switch
logger.info(f"Before switch - Conversation has {len(conversation.messages)} messages")
for i, msg in enumerate(conversation.messages):
logger.info(f" Message {i}: {msg['role']} - {msg['content'][:30]}... (current_version: {msg.get('current_version', 1)})")
# Chuyển đổi version
success = conversation.switch_message_version(message_id, version)
if success:
# Reload conversation để đảm bảo có dữ liệu mới nhất
updated_conversation = Conversation.find_by_id(conversation_id)
# Debug: Log conversation state after switch
logger.info(f"After switch - Conversation has {len(updated_conversation.messages)} messages")
for i, msg in enumerate(updated_conversation.messages):
logger.info(f" Message {i}: {msg['role']} - {msg['content'][:30]}... (current_version: {msg.get('current_version', 1)})")
logger.info(f"Successfully switched message {message_id} to version {version}")
return jsonify({
"success": True,
"conversation": updated_conversation.to_dict()
})
else:
logger.error(f"Failed to switch message {message_id} to version {version}")
return jsonify({
"success": False,
"error": "Không thể chuyển đổi version"
}), 400
except Exception as e:
logger.error(f"Lỗi chuyển đổi version: {str(e)}")
return jsonify({
"success": False,
"error": f"Lỗi máy chủ: {str(e)}"
}), 500
@chat_routes.route('/messages/<message_id>', methods=['DELETE'])
@jwt_required()
def delete_message_and_following(message_id):
"""API endpoint để xóa tin nhắn và tất cả tin nhắn sau nó"""
try:
data = request.json
conversation_id = data.get('conversation_id')
user_id = get_jwt_identity()
if not conversation_id:
return jsonify({
"success": False,
"error": "Thiếu conversation_id"
}), 400
# Tìm conversation
conversation = Conversation.find_by_id(conversation_id)
if not conversation or str(conversation.user_id) != user_id:
return jsonify({
"success": False,
"error": "Không tìm thấy cuộc trò chuyện"
}), 404
# Xóa tin nhắn và các tin nhắn theo sau
success = conversation.delete_message_and_following(message_id)
if success:
updated_conversation = Conversation.find_by_id(conversation_id)
return jsonify({
"success": True,
"conversation": updated_conversation.to_dict()
})
else:
return jsonify({
"success": False,
"error": "Không thể xóa tin nhắn"
}), 400
except Exception as e:
logger.error(f"Lỗi xóa tin nhắn: {str(e)}")
return jsonify({
"success": False,
"error": f"Lỗi máy chủ: {str(e)}"
}), 500 |