VietCat commited on
Commit
844483c
·
1 Parent(s): af289ca

adjust parallel search and rerank

Browse files
Files changed (1) hide show
  1. app/message_processor.py +69 -19
app/message_processor.py CHANGED
@@ -331,37 +331,87 @@ class MessageProcessor:
331
  logger.info(f"[MOCK] Creating Facebook post for sender_id={sender_id} with history={history}")
332
  return "https://facebook.com/mock_post_url"
333
 
334
- async def handle_muc_phat(self, conv, conversation_context, page_token, sender_id):
335
- vehicle = conv.get('originalvehicle', '')
336
- action = conv.get('originalaction', '')
337
- question = conv.get('originalquestion', '')
338
-
339
-
340
- if not action and not question:
341
- return "Để tra cứu mức phạt, bạn vui lòng cung cấp hành vi vi phạm nhé."
342
-
343
- search_query = action or question
344
- logger.info(f"[DEBUG] tạo embedding cho: '{search_query}'")
345
  try:
346
- embedding = await self.channel.embedder.create_embedding(search_query)
347
- logger.info(f"[DEBUG] embedding: {embedding[:5]} ... (total {len(embedding)})")
348
 
 
 
349
  loop = asyncio.get_event_loop()
350
  match_count = get_settings().match_count
351
 
352
-
353
  matches = await loop.run_in_executor(
354
  None,
355
  lambda: self.channel.supabase.match_documents(
356
- embedding,
357
  match_count=match_count,
358
- user_question=search_query
 
359
  )
360
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
361
 
362
- logger.info(f"[DEBUG] matches: {matches[:2]}...{matches[-2:]}")
363
- if matches:
364
- response = await self.format_search_results(conversation_context, question or action, matches, page_token, sender_id)
365
  else:
366
  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ả."
367
  except Exception as e:
 
331
  logger.info(f"[MOCK] Creating Facebook post for sender_id={sender_id} with history={history}")
332
  return "https://facebook.com/mock_post_url"
333
 
334
+ async def _search_and_rerank_task(self, keyword: str, full_query_context: str, vehicle_keywords: List[str]) -> List[Dict[str, Any]]:
335
+ """
336
+ Hàm trợ giúp để thực hiện một tác vụ song song: query từ Supabase và sau đó rerank kết quả.
337
+ LƯU Ý: Việc rerank cho mỗi luồng riêng lẻ có thể tốn kém và không hiệu quả về chất lượng kết quả cuối cùng.
338
+ """
 
 
 
 
 
 
339
  try:
340
+ logger.info(f"[SEARCH_RERANK_TASK] Bắt đầu tác vụ cho từ khóa: '{keyword}'")
 
341
 
342
+ # 1. Query Supabase
343
+ embedding = await self.channel.embedder.create_embedding(keyword)
344
  loop = asyncio.get_event_loop()
345
  match_count = get_settings().match_count
346
 
 
347
  matches = await loop.run_in_executor(
348
  None,
349
  lambda: self.channel.supabase.match_documents(
350
+ embedding=embedding,
351
  match_count=match_count,
352
+ user_question=full_query_context,
353
+ vehicle_keywords=vehicle_keywords
354
  )
355
  )
356
+
357
+ if not matches:
358
+ logger.info(f"[SEARCH_RERANK_TASK] Không tìm thấy kết quả nào từ Supabase cho từ khóa: '{keyword}'")
359
+ return []
360
+
361
+ logger.info(f"[SEARCH_RERANK_TASK] Tìm thấy {len(matches)} kết quả. Bắt đầu rerank cho từ khóa: '{keyword}'")
362
+
363
+ # 2. Rerank (Tạm thời bỏ qua theo logic code gốc, nhưng nếu bật sẽ chạy ở đây)
364
+ # CẢNH BÁO: Bước này rất tốn kém và làm chậm hệ thống nếu chạy cho mỗi từ khóa.
365
+ # Việc rerank nhiều lần sẽ làm tăng chi phí và có thể chạm giới hạn API.
366
+ reranked_matches = matches # Mặc định trả về kết quả gốc nếu rerank bị lỗi hoặc tắt
367
+ # try:
368
+ # # Sử dụng full_query_context để rerank sẽ cho kết quả tốt hơn là chỉ dùng keyword
369
+ # reranked = await self.channel.reranker.rerank(full_query_context, matches, top_k=10)
370
+ # if reranked:
371
+ # reranked_matches = reranked
372
+ # logger.info(f"[SEARCH_RERANK_TASK] Rerank thành công cho từ khóa '{keyword}', còn lại {len(reranked_matches)} kết quả.")
373
+ # except Exception as e:
374
+ # logger.error(f"[SEARCH_RERANK_TASK] Lỗi khi rerank cho từ khóa '{keyword}': {e}. Sử dụng kết quả gốc.")
375
+
376
+ return reranked_matches
377
+ except Exception as e:
378
+ logger.error(f"Lỗi trong tác vụ tìm kiếm và rerank cho từ khóa '{keyword}': {e}")
379
+ return [] # Trả về danh sách rỗng để không làm hỏng luồng chung
380
+
381
+ async def handle_muc_phat(self, conv, conversation_context, page_token, sender_id):
382
+ vehicle_str = conv.get('originalvehicle', '')
383
+ vehicle_keywords = vehicle_str.split(',') if vehicle_str else []
384
+ action_keywords_str = conv.get('originalaction', '')
385
+ question = conv.get('originalquestion', '')
386
+
387
+ tu_khoa_list = action_keywords_str.split()
388
+
389
+ if not tu_khoa_list and not question:
390
+ return "Để tra cứu mức phạt, bạn vui lòng cung cấp hành vi vi phạm nhé."
391
+
392
+ main_query_for_context = question or action_keywords_str
393
+
394
+ try:
395
+ # --- 1. Tạo và chạy song song các tác vụ Query -> Rerank ---
396
+ search_terms = tu_khoa_list if tu_khoa_list else [main_query_for_context]
397
+ tasks = [self._search_and_rerank_task(term, main_query_for_context, vehicle_keywords) for term in search_terms]
398
+ list_of_reranked_results = await asyncio.gather(*tasks)
399
+
400
+ # --- 2. Tổng hợp và loại bỏ kết quả trùng lặp ---
401
+ combined_matches = []
402
+ seen_ids = set()
403
+ for reranked_list in list_of_reranked_results:
404
+ for match in reranked_list:
405
+ match_id = match.get('id')
406
+ if match_id and match_id not in seen_ids:
407
+ combined_matches.append(match)
408
+ seen_ids.add(match_id)
409
+
410
+ logger.info(f"Tổng hợp được {len(combined_matches)} văn bản duy nhất từ các tác vụ song song.")
411
 
412
+ # --- 3. Tạo câu trả lời ---
413
+ if combined_matches:
414
+ response = await self.format_search_results(conversation_context, main_query_for_context, combined_matches, page_token, sender_id)
415
  else:
416
  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ả."
417
  except Exception as e: