Update services/chat_service.py
Browse files- services/chat_service.py +56 -29
services/chat_service.py
CHANGED
|
@@ -12,58 +12,85 @@ class ChatService:
|
|
| 12 |
self.tts_service = tts_service
|
| 13 |
self.multilingual_manager = rag_system.multilingual_manager
|
| 14 |
|
| 15 |
-
def respond(self, message: str,chat_history: List[Tuple[str, str]]) -> tuple:
|
| 16 |
"""Tạo phản hồi cho tin nhắn đầu vào dựa trên lịch sử trò chuyện và ngôn ngữ."""
|
| 17 |
if chat_history is None:
|
| 18 |
chat_history = []
|
| 19 |
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
messages = []
|
| 24 |
-
for user_msg, assistant_msg in chat_history:
|
| 25 |
-
messages.append({"role": "user", "content": user_msg})
|
| 26 |
-
messages.append({"role": "assistant", "content": assistant_msg})
|
| 27 |
-
messages.append({"role": "user", "content": message})
|
| 28 |
|
| 29 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
rag_results = self.rag_system.semantic_search(message, top_k=3)
|
| 31 |
context_text = ""
|
| 32 |
if rag_results:
|
| 33 |
-
context_text = "\n
|
| 34 |
|
|
|
|
| 35 |
if language == 'vi':
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
|
|
|
|
|
|
| 40 |
else:
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
messages_with_context = [system_message] + messages
|
| 46 |
|
|
|
|
| 47 |
completion = self.groq_client.chat.completions.create(
|
| 48 |
model=llm_model,
|
| 49 |
messages=messages_with_context,
|
| 50 |
max_tokens=512,
|
| 51 |
temperature=0.7,
|
| 52 |
)
|
| 53 |
-
|
|
|
|
|
|
|
| 54 |
|
|
|
|
| 55 |
chat_history.append((message, assistant_message))
|
| 56 |
|
|
|
|
| 57 |
tts_audio_path = None
|
| 58 |
if assistant_message and not assistant_message.startswith("Error"):
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
except Exception as e:
|
| 63 |
-
|
| 64 |
-
chat_history.append((message,
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
def clear_chat_history(self, chat_history: List[Tuple[str,str]]) -> tuple:
|
| 68 |
-
"""Xóa lịch sử trò chuyện
|
| 69 |
-
return [],[]
|
|
|
|
| 12 |
self.tts_service = tts_service
|
| 13 |
self.multilingual_manager = rag_system.multilingual_manager
|
| 14 |
|
| 15 |
+
def respond(self, message: str, chat_history: List[Tuple[str, str]]) -> tuple:
|
| 16 |
"""Tạo phản hồi cho tin nhắn đầu vào dựa trên lịch sử trò chuyện và ngôn ngữ."""
|
| 17 |
if chat_history is None:
|
| 18 |
chat_history = []
|
| 19 |
|
| 20 |
+
# Kiểm tra message hợp lệ
|
| 21 |
+
if not message or message.strip() == "":
|
| 22 |
+
return "", chat_history, chat_history, None, "unknown"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
|
| 24 |
try:
|
| 25 |
+
language = self.multilingual_manager.detect_language(message)
|
| 26 |
+
llm_model = self.multilingual_manager.get_llm_model(language)
|
| 27 |
+
|
| 28 |
+
# Xây dựng messages từ chat history
|
| 29 |
+
messages = []
|
| 30 |
+
for user_msg, assistant_msg in chat_history:
|
| 31 |
+
messages.append({"role": "user", "content": user_msg})
|
| 32 |
+
messages.append({"role": "assistant", "content": assistant_msg})
|
| 33 |
+
messages.append({"role": "user", "content": message})
|
| 34 |
+
|
| 35 |
+
# Tìm kiếm RAG
|
| 36 |
rag_results = self.rag_system.semantic_search(message, top_k=3)
|
| 37 |
context_text = ""
|
| 38 |
if rag_results:
|
| 39 |
+
context_text = "\n".join([f"- {result.text}" for result in rag_results])
|
| 40 |
|
| 41 |
+
# Tạo system message
|
| 42 |
if language == 'vi':
|
| 43 |
+
system_content = f"""Bạn là trợ lý AI hữu ích chuyên về tiếng Việt. Hãy trả lời một cách tự nhiên và thân thiện.
|
| 44 |
+
|
| 45 |
+
Thông tin tham khảo:
|
| 46 |
+
{context_text if context_text else "Không có thông tin tham khảo cụ thể."}
|
| 47 |
+
|
| 48 |
+
Nếu thông tin tham khảo có liên quan, hãy sử dụng nó. Nếu không, dựa vào kiến thức chung của bạn. Luôn trả lời bằng tiếng Việt."""
|
| 49 |
else:
|
| 50 |
+
system_content = f"""You are a helpful AI assistant. Please respond naturally and friendly.
|
| 51 |
+
|
| 52 |
+
Reference information:
|
| 53 |
+
{context_text if context_text else "No specific reference information available."}
|
| 54 |
+
|
| 55 |
+
If reference information is relevant, use it. Otherwise, rely on your general knowledge. Always respond in the same language as the user."""
|
| 56 |
+
|
| 57 |
+
system_message = {"role": "system", "content": system_content}
|
| 58 |
+
|
| 59 |
+
# Tạo messages với context
|
| 60 |
messages_with_context = [system_message] + messages
|
| 61 |
|
| 62 |
+
# Gọi Groq API
|
| 63 |
completion = self.groq_client.chat.completions.create(
|
| 64 |
model=llm_model,
|
| 65 |
messages=messages_with_context,
|
| 66 |
max_tokens=512,
|
| 67 |
temperature=0.7,
|
| 68 |
)
|
| 69 |
+
|
| 70 |
+
# SỬA QUAN TRỌNG: Cách truy cập response đúng
|
| 71 |
+
assistant_message = completion.choices[0].message.content.strip()
|
| 72 |
|
| 73 |
+
# Cập nhật chat history
|
| 74 |
chat_history.append((message, assistant_message))
|
| 75 |
|
| 76 |
+
# Tạo TTS
|
| 77 |
tts_audio_path = None
|
| 78 |
if assistant_message and not assistant_message.startswith("Error"):
|
| 79 |
+
try:
|
| 80 |
+
tts_bytes = self.tts_service.text_to_speech(assistant_message, language)
|
| 81 |
+
if tts_bytes:
|
| 82 |
+
tts_audio_path = self.tts_service.save_tts_audio(tts_bytes)
|
| 83 |
+
except Exception as tts_error:
|
| 84 |
+
print(f"⚠️ Lỗi TTS: {tts_error}")
|
| 85 |
+
# Vẫn tiếp tục nếu TTS fail
|
| 86 |
+
|
| 87 |
+
return "", chat_history, chat_history, tts_audio_path, language
|
| 88 |
+
|
| 89 |
except Exception as e:
|
| 90 |
+
error_msg = f"❌ Lỗi trong quá trình tạo phản hồi: {str(e)}"
|
| 91 |
+
chat_history.append((message, error_msg))
|
| 92 |
+
return "", chat_history, chat_history, None, "unknown"
|
| 93 |
+
|
| 94 |
+
def clear_chat_history(self, chat_history: List[Tuple[str, str]]) -> tuple:
|
| 95 |
+
"""Xóa lịch sử trò chuyện."""
|
| 96 |
+
return [], []
|