ManTea commited on
Commit
505bcba
·
1 Parent(s): 098f912

fix knowledge history

Browse files
Files changed (2) hide show
  1. NLP_model/chatbot.py +8 -3
  2. mongodb.py +30 -14
NLP_model/chatbot.py CHANGED
@@ -18,7 +18,7 @@ import functools
18
  import hashlib
19
  import logging
20
  import random
21
- from mongodb import get_chat_history
22
 
23
  # Configure logging
24
  logging.basicConfig(
@@ -110,6 +110,7 @@ You have to use core knowledge and conversation history to chat with users, who
110
 
111
  Return Format:
112
  Respond in friendly, natural, concise and use only English like a real tour guide.
 
113
 
114
  Warning:
115
  Let's support users like a real tour guide, not a bot. The information in core knowledge is your own knowledge.
@@ -135,6 +136,10 @@ def get_history(user_id):
135
  """Get conversation history for a specific user from MongoDB"""
136
  return get_chat_history(user_id)
137
 
 
 
 
 
138
 
139
  def get_chain():
140
  """Get the retrieval chain with Pinecone vector store (singleton pattern)"""
@@ -151,7 +156,7 @@ def get_chain():
151
  text_key="text"
152
  )
153
 
154
- _retriever_instance = vectorstore.as_retriever(search_kwargs={"k": 5})
155
  logger.info(f"Pinecone retriever initialized in {time.time() - start_time:.2f} seconds")
156
  return _retriever_instance
157
  except Exception as e:
@@ -218,7 +223,7 @@ def chat(request, user_id="default_user"):
218
  current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
219
 
220
  # Sử dụng invoke thay vì get_relevant_documents
221
- retrieved_docs = retriever.invoke(request)
222
  context = "\n".join([doc.page_content for doc in retrieved_docs])
223
 
224
  # Sử dụng generate_content thay vì invoke cho model Gemini
 
18
  import hashlib
19
  import logging
20
  import random
21
+ from mongodb import get_chat_history, get_request_history
22
 
23
  # Configure logging
24
  logging.basicConfig(
 
110
 
111
  Return Format:
112
  Respond in friendly, natural, concise and use only English like a real tour guide.
113
+ Return in format that use for telegram
114
 
115
  Warning:
116
  Let's support users like a real tour guide, not a bot. The information in core knowledge is your own knowledge.
 
136
  """Get conversation history for a specific user from MongoDB"""
137
  return get_chat_history(user_id)
138
 
139
+ def get_request(user_id):
140
+ """Get conversation history for a specific user from MongoDB"""
141
+ return get_request_history(user_id)
142
+
143
 
144
  def get_chain():
145
  """Get the retrieval chain with Pinecone vector store (singleton pattern)"""
 
156
  text_key="text"
157
  )
158
 
159
+ _retriever_instance = vectorstore.as_retriever(search_kwargs={"k": 7})
160
  logger.info(f"Pinecone retriever initialized in {time.time() - start_time:.2f} seconds")
161
  return _retriever_instance
162
  except Exception as e:
 
223
  current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
224
 
225
  # Sử dụng invoke thay vì get_relevant_documents
226
+ retrieved_docs = retriever.invoke(get_request_history(user_id))
227
  context = "\n".join([doc.page_content for doc in retrieved_docs])
228
 
229
  # Sử dụng generate_content thay vì invoke cho model Gemini
mongodb.py CHANGED
@@ -22,20 +22,6 @@ collection = db[MONGODB_COLLECTION]
22
 
23
 
24
  def get_chat_history(user_id: int) -> str:
25
- """
26
- Lấy lịch sử chat cho user_id cho trước từ MongoDB và ghép thành chuỗi theo định dạng:
27
-
28
- Bot: ...
29
- User: ...
30
- Bot: ...
31
- ...
32
-
33
- Giả sử:
34
- - Các document chứa trường "user_id" để lọc theo user_id.
35
- - Trường "factor" xác định nguồn tin (nếu factor == "user" thì là tin của User,
36
- còn lại coi là tin của Bot/RAG).
37
- - Trường "timestamp" dùng để sắp xếp theo thời gian (nếu có).
38
- """
39
  try:
40
  # Truy vấn tất cả các document có user_id, sắp xếp theo timestamp tăng dần
41
  # Nếu không có trường timestamp, có thể sort theo _id
@@ -64,6 +50,36 @@ def get_chat_history(user_id: int) -> str:
64
  logger.error(f"Lỗi khi lấy lịch sử chat cho user_id {user_id}: {e}")
65
  return ""
66
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67
  # if __name__ == '__main__':
68
  # user_id = int(input("Nhập user_id cần lấy lịch sử chat: ").strip())
69
  # history = get_chat_history(user_id)
 
22
 
23
 
24
  def get_chat_history(user_id: int) -> str:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
  try:
26
  # Truy vấn tất cả các document có user_id, sắp xếp theo timestamp tăng dần
27
  # Nếu không có trường timestamp, có thể sort theo _id
 
50
  logger.error(f"Lỗi khi lấy lịch sử chat cho user_id {user_id}: {e}")
51
  return ""
52
 
53
+ def get_request_history(user_id: int) -> str:
54
+ try:
55
+ # Truy vấn tất cả các document có user_id, sắp xếp theo timestamp tăng dần
56
+ # Nếu không có trường timestamp, có thể sort theo _id
57
+ docs = list(collection.find({"user_id": user_id}).sort("timestamp", -1).limit(15))
58
+ docs.reverse()
59
+
60
+ if not docs:
61
+ logger.info(f"Không tìm thấy dữ liệu cho user_id: {user_id}")
62
+ return ""
63
+
64
+ conversation_lines = []
65
+ for doc in docs:
66
+ factor = doc.get("factor", "").lower()
67
+ action = doc.get("action", "").lower()
68
+ message = doc.get("message", "")
69
+
70
+ if action == "freely asking":
71
+ # Only keep the most recent 3 messages
72
+ if len(conversation_lines) >= 3:
73
+ conversation_lines.pop(0) # Remove oldest message
74
+ conversation_lines.append(message)
75
+
76
+ # Ghép các dòng thành chuỗi, mỗi dòng cách nhau bằng xuống dòng
77
+ logger.info("User ID: " + str(user_id))
78
+ return "\n".join(conversation_lines)
79
+ except Exception as e:
80
+ logger.error(f"Lỗi khi lấy lịch sử request cho user_id {user_id}: {e}")
81
+ return ""
82
+
83
  # if __name__ == '__main__':
84
  # user_id = int(input("Nhập user_id cần lấy lịch sử chat: ").strip())
85
  # history = get_chat_history(user_id)