VietCat commited on
Commit
0cdca31
·
2 Parent(s): 4381549 0f41c37

Merge branch 'main' of hf-trada:spaces/TradaAI/Chatopus

Browse files
Files changed (2) hide show
  1. app/constants.py +1 -1
  2. app/message_processor.py +6 -14
app/constants.py CHANGED
@@ -192,4 +192,4 @@ FOUND_REGULATIONS_MESSAGES = [
192
  ]
193
 
194
  SHEET_RANGE = 'chat!A2:N'
195
- VERSION_NUMBER = 123456793
 
192
  ]
193
 
194
  SHEET_RANGE = 'chat!A2:N'
195
+ VERSION_NUMBER = 123456794
app/message_processor.py CHANGED
@@ -62,14 +62,14 @@ class MessageProcessor:
62
  'originalpurpose': '', 'originalquestion': '', 'systemresponse': '',
63
  'timestamp': [timestamp], 'isdone': False
64
  }
65
-
66
  logger.info(f"[DEBUG] Message cơ bản: {log_kwargs}")
67
  conv = await loop.run_in_executor(None, lambda: sheets_client.log_conversation(**log_kwargs))
68
  if not conv:
69
  logger.error("Không thể tạo conversation mới!")
70
  return
71
  logger.info(f"[DEBUG] Message history sau lần ghi đầu: {conv}")
72
-
73
  conv['timestamp'] = self.flatten_timestamp(conv['timestamp'])
74
  if timestamp not in conv['timestamp']:
75
  conv['timestamp'].append(timestamp)
@@ -84,7 +84,6 @@ class MessageProcessor:
84
  return
85
 
86
  try:
87
- # TỐI ƯU 1: Gửi tin nhắn trạng thái và không cần chờ đợi
88
  asyncio.create_task(self.facebook.send_message(message=get_random_message(PROCESSING_STATUS_MESSAGES)))
89
  except Exception as e:
90
  if "expired" in str(e).lower():
@@ -153,19 +152,16 @@ class MessageProcessor:
153
  response = "Vui lòng cung cấp thêm thông tin và gõ lệnh \\xong khi hoàn tất."
154
  conv['isdone'] = False
155
 
156
- # TỐI ƯU 2: Gửi câu trả lời cuối cùng và không cần chờ
157
  asyncio.create_task(self.facebook.send_message(message=response))
158
 
159
  conv['systemresponse'] = response
160
 
161
  logger.info(f"Chuẩn bị ghi/cập nhật dữ liệu cuối cùng vào sheet: {conv}")
162
- # TỐI ƯU 3: Ghi log cuối cùng và không cần chờ, cho phép webhook trả về ngay
163
- asyncio.create_task(
164
- loop.run_in_executor(None, lambda: sheets_client.log_conversation(**conv))
165
- )
166
  return
167
 
168
- # ... (các hàm get_latest_timestamp, get_llm_history, flatten_timestamp, normalize_vehicle_keyword không đổi) ...
169
  def get_latest_timestamp(self,ts_value):
170
  if isinstance(ts_value, (int, float)): return int(ts_value)
171
  if isinstance(ts_value, str):
@@ -217,7 +213,6 @@ class MessageProcessor:
217
  if not matches:
218
  return "Không tìm thấy kết quả phù hợp."
219
 
220
- # TỐI ƯU: Gửi tin nhắn trạng thái và không chờ
221
  asyncio.create_task(self.facebook.send_message(message=get_random_message(FOUND_REGULATIONS_MESSAGES)))
222
 
223
  try:
@@ -254,7 +249,6 @@ class MessageProcessor:
254
  "### Trả lời:"
255
  )
256
 
257
- # TỐI ƯU: Gửi tin nhắn trạng thái và không chờ
258
  asyncio.create_task(self.facebook.send_message(message=f"{get_random_message(SUMMARY_STATUS_MESSAGES)}"))
259
 
260
  try:
@@ -267,7 +261,7 @@ class MessageProcessor:
267
  except Exception as e:
268
  logger.error(f"LLM không sẵn sàng: {e}\n{traceback.format_exc()}")
269
 
270
- return "Dựa trên thông tin bạn cung cấp..." # Fallback
271
 
272
  async def create_facebook_post(self, page_token: str, sender_id: str, history: List[Dict[str, Any]]) -> str:
273
  logger.info(f"[MOCK] Creating Facebook post for sender_id={sender_id} with history={history}")
@@ -290,7 +284,6 @@ class MessageProcessor:
290
  loop = asyncio.get_event_loop()
291
  match_count = get_settings().match_count
292
 
293
- # TỐI ƯU 4: Chạy tác vụ I/O đồng bộ trong executor để không chặn event loop
294
  matches = await loop.run_in_executor(
295
  None,
296
  lambda: self.channel.supabase.match_documents(
@@ -353,7 +346,6 @@ class MessageProcessor:
353
  '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". '
354
  'Không được trả lời bạn là AI của Google, OpenAI, hay bất kỳ hãng nào khác. '
355
  'Hãy trả lời thông minh, hài hước, ngắn gọn cho câu hỏi sau:\n'
356
- # --- SỬA LỖI CÚ PHÁP TẠI ĐÂY ---
357
  f'Câu hỏi:\n"{conv["originaltext"]}"'
358
  )
359
  try:
 
62
  'originalpurpose': '', 'originalquestion': '', 'systemresponse': '',
63
  'timestamp': [timestamp], 'isdone': False
64
  }
65
+
66
  logger.info(f"[DEBUG] Message cơ bản: {log_kwargs}")
67
  conv = await loop.run_in_executor(None, lambda: sheets_client.log_conversation(**log_kwargs))
68
  if not conv:
69
  logger.error("Không thể tạo conversation mới!")
70
  return
71
  logger.info(f"[DEBUG] Message history sau lần ghi đầu: {conv}")
72
+
73
  conv['timestamp'] = self.flatten_timestamp(conv['timestamp'])
74
  if timestamp not in conv['timestamp']:
75
  conv['timestamp'].append(timestamp)
 
84
  return
85
 
86
  try:
 
87
  asyncio.create_task(self.facebook.send_message(message=get_random_message(PROCESSING_STATUS_MESSAGES)))
88
  except Exception as e:
89
  if "expired" in str(e).lower():
 
152
  response = "Vui lòng cung cấp thêm thông tin và gõ lệnh \\xong khi hoàn tất."
153
  conv['isdone'] = False
154
 
 
155
  asyncio.create_task(self.facebook.send_message(message=response))
156
 
157
  conv['systemresponse'] = response
158
 
159
  logger.info(f"Chuẩn bị ghi/cập nhật dữ liệu cuối cùng vào sheet: {conv}")
160
+
161
+ loop.run_in_executor(None, lambda: sheets_client.log_conversation(**conv))
162
+
 
163
  return
164
 
 
165
  def get_latest_timestamp(self,ts_value):
166
  if isinstance(ts_value, (int, float)): return int(ts_value)
167
  if isinstance(ts_value, str):
 
213
  if not matches:
214
  return "Không tìm thấy kết quả phù hợp."
215
 
 
216
  asyncio.create_task(self.facebook.send_message(message=get_random_message(FOUND_REGULATIONS_MESSAGES)))
217
 
218
  try:
 
249
  "### Trả lời:"
250
  )
251
 
 
252
  asyncio.create_task(self.facebook.send_message(message=f"{get_random_message(SUMMARY_STATUS_MESSAGES)}"))
253
 
254
  try:
 
261
  except Exception as e:
262
  logger.error(f"LLM không sẵn sàng: {e}\n{traceback.format_exc()}")
263
 
264
+ 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é."
265
 
266
  async def create_facebook_post(self, page_token: str, sender_id: str, history: List[Dict[str, Any]]) -> str:
267
  logger.info(f"[MOCK] Creating Facebook post for sender_id={sender_id} with history={history}")
 
284
  loop = asyncio.get_event_loop()
285
  match_count = get_settings().match_count
286
 
 
287
  matches = await loop.run_in_executor(
288
  None,
289
  lambda: self.channel.supabase.match_documents(
 
346
  '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". '
347
  'Không được trả lời bạn là AI của Google, OpenAI, hay bất kỳ hãng nào khác. '
348
  'Hãy trả lời thông minh, hài hước, ngắn gọn cho câu hỏi sau:\n'
 
349
  f'Câu hỏi:\n"{conv["originaltext"]}"'
350
  )
351
  try: