File size: 21,402 Bytes
5f02751 f6cdf9d 0dfd3e3 f6cdf9d 4032184 4c4c55e 4032184 74c90ba 759b17a f6cdf9d 4032184 f6cdf9d 4032184 74c90ba 4032184 f6cdf9d f0cf2d8 3e4a08a f6cdf9d 0dfd3e3 3d65afc 0dfd3e3 3d65afc 0dfd3e3 f6cdf9d 5f02751 3d65afc 3b499b7 f6cdf9d 673fcb4 3d65afc f6cdf9d 0dfd3e3 3d65afc 0dfd3e3 f6cdf9d 0dfd3e3 f6cdf9d 0dfd3e3 f6cdf9d 0dfd3e3 16ae2fb f6cdf9d 0dfd3e3 f6866df f6cdf9d 0dfd3e3 f6cdf9d e529ed6 5f02751 f6cdf9d e529ed6 5f02751 f6cdf9d e529ed6 5f02751 f6cdf9d 5f02751 f6cdf9d 5f02751 0dfd3e3 e529ed6 bfde537 0dfd3e3 e529ed6 0dfd3e3 bfde537 f6866df 3d65afc bfde537 3d65afc bfde537 d14992f bfde537 d14992f bfde537 d14992f 65b4cff d14992f bfde537 d14992f bfde537 298cf0a 0dfd3e3 3d65afc 0dfd3e3 3d65afc f6cdf9d f6866df f6cdf9d 6e261a5 f6cdf9d 3d65afc f6cdf9d 4032184 f6cdf9d 7f2bcc2 f6cdf9d 0dfd3e3 f6cdf9d 0dfd3e3 f6cdf9d 0dfd3e3 399dc64 5f02751 f6cdf9d 0dfd3e3 f6cdf9d 0dfd3e3 70d2f99 0dfd3e3 99e5f5e f6cdf9d 99e5f5e 0dfd3e3 f6cdf9d 99e5f5e 9fee5fd f6cdf9d 7089324 f6cdf9d 0dfd3e3 f6cdf9d 0dfd3e3 759b17a 6e261a5 298cf0a 5f02751 0dfd3e3 5f02751 0dfd3e3 9dcf8cb 5f02751 9dcf8cb 0dfd3e3 5f02751 e529ed6 5f02751 0dfd3e3 298cf0a 0dfd3e3 5f02751 298cf0a 0dfd3e3 3d65afc 0dfd3e3 3d65afc 0dfd3e3 d14992f 298cf0a d14992f 0dfd3e3 d14992f 0dfd3e3 d14992f 298cf0a d14992f 298cf0a d14992f 298cf0a d14992f 298cf0a d14992f 298cf0a d14992f af4e098 3d65afc 0dfd3e3 af4e098 968d612 008f627 af4e098 0dfd3e3 | 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 | from typing import Dict, Any, List, Optional
import asyncio
import traceback
import json
from loguru import logger
from .constants import SUMMARY_STATUS_MESSAGES, PROCESSING_STATUS_MESSAGES, FOUND_REGULATIONS_MESSAGES, BATCH_STATUS_MESSAGES
from .utils import get_random_message
from .facebook import FacebookClient
from app.config import get_settings
import re
class MessageProcessor:
def __init__(self, channel, sender_id):
self.channel = channel
self.sender_id = sender_id
# FacebookClient riêng cho từng conversation
self.facebook = FacebookClient(
app_secret=get_settings().facebook_app_secret,
page_id=channel.page_id,
page_token=channel.get_page_token(),
sender_id=sender_id
)
async def process_message(self, message_data: Dict[str, Any]):
if not message_data or not isinstance(message_data, dict):
logger.error(f"[ERROR] Invalid message_data: {message_data}")
return
required_fields = ["sender_id", "page_id", "text", "timestamp"]
for field in required_fields:
if field not in message_data:
logger.error(f"[ERROR] Missing field {field} in message_data: {message_data}")
return
sender_id = message_data["sender_id"]
page_id = message_data["page_id"]
message_text = message_data["text"]
timestamp = message_data["timestamp"]
attachments = message_data.get('attachments', [])
logger.bind(user_id=sender_id, page_id=page_id, message=message_text).info("Processing message")
if not message_text and not attachments:
logger.info(f"[DEBUG] Không có message_text và attachments, không xử lý...")
return
loop = asyncio.get_event_loop()
sheets_client = self.channel.get_sheets_client()
history = await loop.run_in_executor(
None, lambda: sheets_client.get_conversation_history(sender_id, page_id)
)
logger.info(f"[DEBUG] history: ... {history[-3:]}")
# --- SỬA LỖI LOGIC CHỐNG TRÙNG LẶP TẠI ĐÂY ---
# Kiểm tra xem timestamp của sự kiện webhook này đã tồn tại trong lịch sử chưa
for row in history:
# Chuyển đổi an toàn sang string để so sánh
sheet_timestamps = [str(ts) for ts in row.get('timestamp', [])]
if str(timestamp) in sheet_timestamps:
logger.warning(f"Webhook lặp lại cho sự kiện đã tồn tại (timestamp: {timestamp}). Bỏ qua.")
return # Bỏ qua hoàn toàn để tránh xử lý lại
# --- LUỒNG XỬ LÝ GỐC CỦA BẠN ĐƯỢC GIỮ NGUYÊN ---
log_kwargs = {
'conversation_id': None,
'recipient_id': sender_id,
'page_id': page_id,
'originaltext': message_text,
'originalcommand': '',
'originalcontent': '',
'originalattachments': attachments,
'originalvehicle': '',
'originalaction': '',
'originalpurpose': '',
'originalquestion': '',
'systemresponse': '',
'timestamp': [timestamp],
'isdone': False
}
logger.info(f"[DEBUG] Message cơ bản: {log_kwargs}")
conv = await loop.run_in_executor(None, lambda: sheets_client.log_conversation(**log_kwargs))
if not conv:
logger.error("Không thể tạo conversation mới!")
return
logger.info(f"[DEBUG] Message history sau lần ghi đầu: {conv}")
# Thêm timestamp mới nếu chưa có (logic này có thể không cần thiết nữa nhưng giữ lại để không thay đổi luồng)
conv['timestamp'] = self.flatten_timestamp(conv['timestamp'])
if timestamp not in conv['timestamp']:
conv['timestamp'].append(timestamp)
# Lần gọi thứ 2 để cập nhật thêm thông tin ban đầu (nếu có)
conv_after_update1 = await loop.run_in_executor(None, lambda: sheets_client.log_conversation(**conv))
if conv_after_update1:
conv = conv_after_update1
page_token = self.channel.get_page_token()
if not page_token:
logger.error(f"No access token found for page {message_data['page_id']}")
return
try:
await self.facebook.send_message(message=get_random_message(PROCESSING_STATUS_MESSAGES))
except Exception as e:
if "expired" in str(e).lower():
logger.warning("[FACEBOOK] Token expired, invalidate and refresh")
self.channel.invalidate_page_token()
page_token = self.channel.get_page_token(force_refresh=True)
self.facebook.page_token = page_token
else:
raise
from app.utils import extract_command, extract_keywords
from app.constants import VEHICLE_KEYWORDS
command, remaining_text = extract_command(message_text)
llm_analysis = await self.channel.llm.analyze(message_text, self.get_llm_history(history))
logger.info(f"[LLM][RAW] Kết quả trả về từ analyze: {llm_analysis}")
muc_dich = None
tu_khoa = None
cau_hoi = None
if isinstance(llm_analysis, dict):
keywords = [self.normalize_vehicle_keyword(llm_analysis.get('phuong_tien', ''))]
muc_dich = llm_analysis.get('muc_dich')
tu_khoa = llm_analysis.get('tu_khoa')
cau_hoi = llm_analysis.get('cau_hoi')
elif isinstance(llm_analysis, list) and len(llm_analysis) > 0:
keywords = [self.normalize_vehicle_keyword(llm_analysis[0].get('phuong_tien', ''))]
muc_dich = llm_analysis[0].get('muc_dich')
tu_khoa = llm_analysis[0].get('tu_khoa')
cau_hoi = llm_analysis[0].get('cau_hoi')
else:
keywords = extract_keywords(message_text, VEHICLE_KEYWORDS)
cau_hoi = message_text
for kw in keywords:
cau_hoi = cau_hoi.replace(kw, "")
cau_hoi = cau_hoi.strip()
logger.info(f"[DEBUG] Phương tiện: {keywords} - Hành vi: {tu_khoa} - Mục đích: {muc_dich} - Câu hỏi: {cau_hoi}")
# Hợp nhất dữ liệu đã phân tích vào `conv`
conv['originalcommand'] = command
conv['originalcontent'] = remaining_text
conv['originalvehicle'] = ','.join(keywords)
conv['originalaction'] = tu_khoa
conv['originalpurpose'] = muc_dich
conv['originalquestion'] = cau_hoi or ""
muc_dich_to_use = muc_dich or conv.get('originalpurpose')
logger.info(f"[DEBUG] Định hướng mục đích xử lý: {muc_dich_to_use}")
conversation_context = self.get_llm_history(history)
response = None
if not command:
if muc_dich_to_use == "hỏi về mức phạt":
response = await self.handle_muc_phat(conv, conversation_context, page_token, sender_id)
elif muc_dich_to_use == "hỏi về quy tắc giao thông":
response = await self.handle_quy_tac(conv, conversation_context, page_token, sender_id)
elif muc_dich_to_use == "hỏi về báo hiệu đường bộ":
response = await self.handle_bao_hieu(conv, conversation_context, page_token, sender_id)
elif muc_dich_to_use == "hỏi về quy trình xử lý vi phạm giao thông":
response = await self.handle_quy_trinh(conv, conversation_context, page_token, sender_id)
elif muc_dich_to_use == "thông tin cá nhân của AI":
response = await self.handle_ca_nhan(conv, conversation_context, page_token, sender_id)
else:
response = await self.handle_khac(conv, conversation_context, page_token, sender_id)
else:
if command == "xong":
post_url = await self.create_facebook_post(page_token, conv['recipient_id'], [conv])
if post_url:
response = f"Bài viết đã được tạo thành công! Bạn có thể xem tại: {post_url}"
else:
response = "Đã xảy ra lỗi khi tạo bài viết. Vui lòng thử lại sau."
conv['isdone'] = True
else:
response = "Vui lòng cung cấp thêm thông tin và gõ lệnh \\xong khi hoàn tất."
conv['isdone'] = False
await self.facebook.send_message(message=response)
conv['systemresponse'] = response
logger.info(f"Chuẩn bị ghi/cập nhật dữ liệu cuối cùng vào sheet: {conv}")
await loop.run_in_executor(None, lambda: sheets_client.log_conversation(**conv))
return
def get_latest_timestamp(self,ts_value):
if isinstance(ts_value, (int, float)): return int(ts_value)
if isinstance(ts_value, str):
try: return int(json.loads(ts_value))
except:
try: return int(ts_value)
except: return 0
if isinstance(ts_value, list):
if not ts_value: return 0
return max([self.get_latest_timestamp(item) for item in ts_value]) if ts_value else 0
return 0
def get_llm_history(self, history: List):
sorted_history = sorted(history, key=lambda row: self.get_latest_timestamp(row.get('timestamp', 0)))
total_chars = 0
MAX_CONTEXT_CHARS = 20_000
conversation_context = []
for row in reversed(sorted_history):
temp_blocks = []
# --- SỬA LỖI THỨ TỰ LỊCH SỬ TẠI ĐÂY ---
# Đảm bảo lượt nói của user luôn được thêm vào trước.
if row.get('originaltext'):
temp_blocks.append({"role": "user", "content": row['originaltext']})
# Lượt nói của trợ lý ảo được thêm vào sau.
if row.get('systemresponse'):
temp_blocks.append({"role": "assistant", "content": row['systemresponse']})
temp_total = sum(len(block['content']) for block in temp_blocks)
if total_chars + temp_total > MAX_CONTEXT_CHARS: continue
# Thêm cặp hỏi-đáp vào đầu danh sách context, duy trì thứ tự thời gian
conversation_context = temp_blocks + conversation_context
total_chars += temp_total
return conversation_context
def flatten_timestamp(self, ts):
flat = []
if not isinstance(ts, list):
ts = [ts]
for t in ts:
if isinstance(t, list):
flat.extend(self.flatten_timestamp(t))
else:
flat.append(t)
return flat
def normalize_vehicle_keyword(self, keyword: str) -> str:
from app.constants import VEHICLE_KEYWORDS
import difflib
if not keyword:
return ""
matches = difflib.get_close_matches(keyword.lower(), [k.lower() for k in VEHICLE_KEYWORDS], n=1, cutoff=0.6)
if matches:
for k in VEHICLE_KEYWORDS:
if k.lower() == matches[0]:
return k
return keyword
async def format_search_results(self, conversation_context: str, question: str, matches: List[Dict[str, Any]], page_token: str, sender_id: str) -> str:
if not matches:
return "Không tìm thấy kết quả phù hợp."
await self.facebook.send_message(message=get_random_message(FOUND_REGULATIONS_MESSAGES))
try:
reranked = await self.channel.reranker.rerank(question, matches, top_k=10)
if reranked:
matches = reranked
except Exception as e:
logger.error(f"[RERANK] Lỗi khi rerank: {e}")
full_result_text = ""
def arr_to_str(arr, sep=", "):
if not arr: return ""
return sep.join([str(x) for x in arr if x not in (None, "")]) if isinstance(arr, list) else str(arr)
for i, match in enumerate(matches, 1):
full_result_text += f"\n- Nguồn: {(match.get('structure') or '').strip()}:\n"
fullContent = (match.get('fullcontent') or '').strip()
full_result_text += f"{fullContent}"
hpbsnoidung = arr_to_str(match.get('hpbsnoidung'), sep="; ")
if hpbsnoidung:
full_result_text += f"\n- Hình phạt bổ sung: {hpbsnoidung}"
bpkpnoidung = arr_to_str(match.get('bpkpnoidung'), sep="; ")
if bpkpnoidung:
full_result_text += f"\n- Biện pháp khắc phục: {bpkpnoidung}"
impounding = match.get('impounding')
if impounding:
full_result_text += f"\n- Có thể tạm giữ phương tiện."
# --- PROMPT MỚI ĐƯỢC CẬP NHẬT TẠI ĐÂY ---
prompt = (
"Bạn là một trợ lý pháp lý AI chuyên nghiệp. Nhiệm vụ của bạn là tổng hợp thông tin từ hai nguồn: **Lịch sử trò chuyện** và **Các đoạn luật liên quan** để đưa ra một câu trả lời duy nhất, liền mạch và tự nhiên cho người dùng.\n\n"
"**QUY TẮC BẮT BUỘC:**\n"
"1. **Hành văn tự nhiên:** Trả lời thẳng vào câu hỏi. **Không** bắt đầu bằng các cụm từ như 'Dựa trên thông tin được cung cấp', 'Theo các đoạn luật', v.v.\n"
"2. **Nguồn trích dẫn:** Khi cần trích dẫn, chỉ nêu nguồn từ văn bản luật (ví dụ: 'theo Khoản 1, Điều 5...'). **Tuyệt đối không** trích dẫn nguồn là 'từ lịch sử trò chuyện'.\n"
"3. **Tổng hợp thông tin:** Phải kết hợp thông tin từ cả hai nguồn một cách mượt mà. Ví dụ, nếu lịch sử trò chuyện đã có mức phạt cho xe máy, và câu hỏi hiện tại là về xe máy điện, hãy sử dụng thông tin từ văn bản luật để xác định xe máy điện thuộc nhóm xe nào, sau đó áp dụng mức phạt đã biết từ lịch sử.\n"
"4. **Ngắn gọn, chính xác:** Luôn trả lời ngắn gọn, rõ ràng và chỉ dựa vào thông tin được cung cấp.\n\n"
f"### Lịch sử trò chuyện:\n{conversation_context}\n\n"
f"### Các đoạn luật liên quan:\n{full_result_text}\n\n"
f"### Câu hỏi của người dùng:\n{question}\n\n"
"### Trả lời:"
)
await self.facebook.send_message(message=f"{get_random_message(SUMMARY_STATUS_MESSAGES)}")
try:
answer = await self.channel.llm.generate_text(prompt)
if answer and answer.strip():
logger.info(f"LLM trả về câu trả lời: \n\tanswer: {answer}")
return answer.strip()
else:
logger.error(f"LLM không trả về câu trả lời phù hợp: \n\tanswer: {answer}")
except Exception as e:
logger.error(f"LLM không sẵn sàng: {e}\n{traceback.format_exc()}")
# Fallback response
return "Dựa trên thông tin bạn cung cấp, tôi đã tìm thấy một số quy định liên quan. Tuy nhiên, tôi đang gặp chút khó khăn trong việc tóm tắt. Bạn vui lòng tham khảo nội dung chi tiết trong các văn bản luật nhé."
async def create_facebook_post(self, page_token: str, sender_id: str, history: List[Dict[str, Any]]) -> str:
logger.info(f"[MOCK] Creating Facebook post for sender_id={sender_id} with history={history}")
# In a real scenario, you would use the Facebook Graph API to create a post.
# This is a mock implementation.
return "https://facebook.com/mock_post_url"
async def handle_muc_phat(self, conv, conversation_context, page_token, sender_id):
vehicle = conv.get('originalvehicle', '')
action = conv.get('originalaction', '')
question = conv.get('originalquestion', '')
if not action and not question:
return "Để tra cứu mức phạt, bạn vui lòng cung cấp hành vi vi phạm nhé."
search_query = action or question
logger.info(f"[DEBUG] tạo embedding cho: '{search_query}'")
try:
embedding = await self.channel.embedder.create_embedding(search_query)
logger.info(f"[DEBUG] embedding: {embedding[:5]} ... (total {len(embedding)})")
match_count = get_settings().match_count
matches = self.channel.supabase.match_documents(
embedding,
match_count=match_count,
user_question=search_query
)
logger.info(f"[DEBUG] matches: {matches[:2]}...{matches[-2:]}")
if matches:
response = await self.format_search_results(conversation_context, question or action, matches, page_token, sender_id)
else:
response = "Xin lỗi, tôi không tìm thấy thông tin phù hợp với hành vi bạn mô tả."
except Exception as e:
logger.error(f"Lỗi khi tra cứu mức phạt: {e}")
response = "Đã có lỗi xảy ra trong quá trình tra cứu. Vui lòng thử lại sau."
conv['isdone'] = True
return response
async def _handle_general_question(self, conversation_context: str, message_text: str, topic: str) -> str:
"""Hàm chung để xử lý các câu hỏi kiến thức chung."""
prompt = (
"Bạn là một trợ lý AI am hiểu về luật giao thông Việt Nam. "
"Dựa vào lịch sử trò chuyện và kiến thức của bạn, hãy trả lời câu hỏi của người dùng một cách rõ ràng, ngắn gọn và chính xác.\n"
f"Chủ đề câu hỏi là về: {topic}\n"
f"### Lịch sử:\n{conversation_context}\n"
f"### Câu hỏi của người dùng:\n{message_text}\n"
"### Trả lời:"
)
try:
answer = await self.channel.llm.generate_text(prompt)
if answer and answer.strip():
return answer.strip()
return f"Tôi chưa có thông tin về câu hỏi của bạn liên quan đến {topic}."
except Exception as e:
logger.error(f"Lỗi khi xử lý chủ đề {topic}: {e}")
return f"Xin lỗi, tôi đang gặp sự cố khi xử lý câu hỏi về {topic}. Vui lòng thử lại sau."
async def handle_khac(self, conv, conversation_context, page_token, sender_id):
conv['isdone'] = True
return await self._handle_general_question(conversation_context, conv['originaltext'], "một vấn đề khác")
async def handle_quy_tac(self, conv, conversation_context, page_token, sender_id):
conv['isdone'] = True
# return await self._handle_general_question(conversation_context, conv['originaltext'], "quy tắc giao thông")
return await self.handle_muc_phat(conv, conversation_context, page_token, sender_id)
async def handle_bao_hieu(self, conv, conversation_context, page_token, sender_id):
conv['isdone'] = True
# return await self._handle_general_question(conversation_context, conv['originaltext'], "báo hiệu đường bộ")
return await self.handle_muc_phat(conv, conversation_context, page_token, sender_id)
async def handle_quy_trinh(self, conv, conversation_context, page_token, sender_id):
conv['isdone'] = True
# return await self._handle_general_question(conversation_context, conv['originaltext'], "quy trình xử lý vi phạm giao thông")
return await self.handle_muc_phat(conv, conversation_context, page_token, sender_id)
async def handle_ca_nhan(self, conv, conversation_context, page_token, sender_id):
prompt = (
"Biết rằng bạn đã có lịch sử trao đổi như sau:"
f"Lịch sử:\n{conversation_context}\n\n"
'Với các thông tin sau: "Bạn có tên là WeThoong AI, là trợ lý giao thông thông minh. Bạn được anh Viet Cat tạo ra và facebook cá nhân của anh ấy là https://facebook.com/vietcat". '
'Không được trả lời bạn là AI của Google, OpenAI, hay bất kỳ hãng nào khác. '
'Hãy trả lời thông minh, hài hước, ngắn gọn cho câu hỏi sau:\n'
# --- SỬA LỖI CÚ PHÁP TẠI ĐÂY ---
f'Câu hỏi:\n"{conv["originaltext"]}"'
)
try:
answer = await self.channel.llm.generate_text(prompt)
conv['isdone'] = True
return answer.strip() if answer and answer.strip() else "Chào bạn, mình là WeThoong AI đây!"
except Exception as e:
logger.error(f"Lỗi khi xử lý câu hỏi cá nhân: {e}")
return "Chào bạn, mình là WeThoong AI, trợ lý giao thông thông minh của bạn!"
|