update message flow
Browse files- app/main.py +10 -4
- app/sheets.py +22 -22
- app/supabase_db.py +10 -7
app/main.py
CHANGED
|
@@ -122,13 +122,18 @@ async def process_message(message_data: Dict[str, Any]):
|
|
| 122 |
sender_id = message_data["sender_id"]
|
| 123 |
page_id = message_data["page_id"]
|
| 124 |
message_text = message_data["text"]
|
|
|
|
| 125 |
logger.bind(user_id=sender_id, page_id=page_id, message=message_text).info("Processing message")
|
| 126 |
-
|
|
|
|
|
|
|
| 127 |
return
|
| 128 |
|
| 129 |
# Get page access token (sync)
|
| 130 |
page_token = supabase_client.get_page_token(page_id)
|
| 131 |
logger.info(f"[DEBUG] page_token: {page_token}")
|
|
|
|
|
|
|
| 132 |
if not page_token:
|
| 133 |
logger.error(f"No access token found for page {page_id}")
|
| 134 |
return
|
|
@@ -147,12 +152,13 @@ async def process_message(message_data: Dict[str, Any]):
|
|
| 147 |
response = ""
|
| 148 |
log_needed = True
|
| 149 |
log_kwargs = {
|
|
|
|
| 150 |
'user_id': sender_id,
|
| 151 |
'page_id': page_id,
|
| 152 |
'message': message_text,
|
| 153 |
'command': command,
|
| 154 |
'content': remaining_text,
|
| 155 |
-
'attachments':
|
| 156 |
'vehicle': ','.join(keywords),
|
| 157 |
'is_done': False
|
| 158 |
}
|
|
@@ -164,7 +170,7 @@ async def process_message(message_data: Dict[str, Any]):
|
|
| 164 |
# Có thông tin phương tiện
|
| 165 |
embedding = await embedding_client.create_embedding(message_text)
|
| 166 |
logger.info(f"[DEBUG] embedding: {embedding[:5]} ... (total {len(embedding)})")
|
| 167 |
-
matches = supabase_client.match_documents(embedding)
|
| 168 |
logger.info(f"[DEBUG] matches: {matches}")
|
| 169 |
if matches:
|
| 170 |
response = format_search_results(matches)
|
|
@@ -194,7 +200,7 @@ async def process_message(message_data: Dict[str, Any]):
|
|
| 194 |
# Có thông tin phương tiện
|
| 195 |
embedding = await embedding_client.create_embedding(message_text)
|
| 196 |
logger.info(f"[DEBUG] embedding: {embedding[:5]} ... (total {len(embedding)})")
|
| 197 |
-
matches = supabase_client.match_documents(embedding)
|
| 198 |
logger.info(f"[DEBUG] matches: {matches}")
|
| 199 |
if matches:
|
| 200 |
response = format_search_results(matches)
|
|
|
|
| 122 |
sender_id = message_data["sender_id"]
|
| 123 |
page_id = message_data["page_id"]
|
| 124 |
message_text = message_data["text"]
|
| 125 |
+
attachments = message_data.get('attachments', [])
|
| 126 |
logger.bind(user_id=sender_id, page_id=page_id, message=message_text).info("Processing message")
|
| 127 |
+
|
| 128 |
+
# Nếu không có message_text và attachments, không xử lý
|
| 129 |
+
if not message_text and not attachments:
|
| 130 |
return
|
| 131 |
|
| 132 |
# Get page access token (sync)
|
| 133 |
page_token = supabase_client.get_page_token(page_id)
|
| 134 |
logger.info(f"[DEBUG] page_token: {page_token}")
|
| 135 |
+
|
| 136 |
+
# Nếu không có page_token, không xử lý
|
| 137 |
if not page_token:
|
| 138 |
logger.error(f"No access token found for page {page_id}")
|
| 139 |
return
|
|
|
|
| 152 |
response = ""
|
| 153 |
log_needed = True
|
| 154 |
log_kwargs = {
|
| 155 |
+
'conversation_id': None,
|
| 156 |
'user_id': sender_id,
|
| 157 |
'page_id': page_id,
|
| 158 |
'message': message_text,
|
| 159 |
'command': command,
|
| 160 |
'content': remaining_text,
|
| 161 |
+
'attachments': attachments,
|
| 162 |
'vehicle': ','.join(keywords),
|
| 163 |
'is_done': False
|
| 164 |
}
|
|
|
|
| 170 |
# Có thông tin phương tiện
|
| 171 |
embedding = await embedding_client.create_embedding(message_text)
|
| 172 |
logger.info(f"[DEBUG] embedding: {embedding[:5]} ... (total {len(embedding)})")
|
| 173 |
+
matches = supabase_client.match_documents(embedding, vehicle_filters=keywords)
|
| 174 |
logger.info(f"[DEBUG] matches: {matches}")
|
| 175 |
if matches:
|
| 176 |
response = format_search_results(matches)
|
|
|
|
| 200 |
# Có thông tin phương tiện
|
| 201 |
embedding = await embedding_client.create_embedding(message_text)
|
| 202 |
logger.info(f"[DEBUG] embedding: {embedding[:5]} ... (total {len(embedding)})")
|
| 203 |
+
matches = supabase_client.match_documents(embedding, vehicle_filters=keywords)
|
| 204 |
logger.info(f"[DEBUG] matches: {matches}")
|
| 205 |
if matches:
|
| 206 |
response = format_search_results(matches)
|
app/sheets.py
CHANGED
|
@@ -90,7 +90,7 @@ class SheetsClient:
|
|
| 90 |
history = []
|
| 91 |
|
| 92 |
for row in values:
|
| 93 |
-
if
|
| 94 |
history.append({
|
| 95 |
'conversation_id': row[0],
|
| 96 |
'originalcommand': row[1],
|
|
@@ -111,6 +111,7 @@ class SheetsClient:
|
|
| 111 |
@timing_decorator_sync
|
| 112 |
def log_conversation(
|
| 113 |
self,
|
|
|
|
| 114 |
user_id: str,
|
| 115 |
page_id: str,
|
| 116 |
message: str,
|
|
@@ -131,11 +132,9 @@ class SheetsClient:
|
|
| 131 |
if not self.service:
|
| 132 |
raise RuntimeError("Google Sheets service not initialized")
|
| 133 |
|
| 134 |
-
# Get existing conversations
|
| 135 |
-
existing_conversations = self.get_conversation_history(user_id, page_id)
|
| 136 |
timestamp = datetime.now().isoformat()
|
| 137 |
|
| 138 |
-
if not
|
| 139 |
# Create new conversation
|
| 140 |
conversation_id = generate_conversation_id(user_id, page_id, timestamp)
|
| 141 |
values = [[
|
|
@@ -163,9 +162,7 @@ class SheetsClient:
|
|
| 163 |
).execute()
|
| 164 |
else:
|
| 165 |
# Update existing conversation
|
| 166 |
-
|
| 167 |
-
conversation_id = conversation['conversation_id']
|
| 168 |
-
|
| 169 |
# Find the row with this conversation_id
|
| 170 |
result = self.service.spreadsheets().values().get(
|
| 171 |
spreadsheetId=self.sheet_id,
|
|
@@ -181,24 +178,27 @@ class SheetsClient:
|
|
| 181 |
break
|
| 182 |
|
| 183 |
if row_index is not None:
|
| 184 |
-
#
|
| 185 |
-
|
| 186 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 187 |
conversation_id,
|
| 188 |
-
command
|
| 189 |
-
content
|
| 190 |
-
json.dumps(attachments
|
| 191 |
-
user_id,
|
| 192 |
-
page_id,
|
| 193 |
-
message,
|
| 194 |
-
vehicle
|
| 195 |
-
str(is_done).lower()
|
| 196 |
-
]
|
| 197 |
-
|
| 198 |
body = {
|
| 199 |
-
'values':
|
| 200 |
}
|
| 201 |
-
|
| 202 |
self.service.spreadsheets().values().update(
|
| 203 |
spreadsheetId=self.sheet_id,
|
| 204 |
range=update_range,
|
|
|
|
| 90 |
history = []
|
| 91 |
|
| 92 |
for row in values:
|
| 93 |
+
if row[4] == user_id and row[5] == page_id and row[8].lower() == 'false':
|
| 94 |
history.append({
|
| 95 |
'conversation_id': row[0],
|
| 96 |
'originalcommand': row[1],
|
|
|
|
| 111 |
@timing_decorator_sync
|
| 112 |
def log_conversation(
|
| 113 |
self,
|
| 114 |
+
conversation_id: str,
|
| 115 |
user_id: str,
|
| 116 |
page_id: str,
|
| 117 |
message: str,
|
|
|
|
| 132 |
if not self.service:
|
| 133 |
raise RuntimeError("Google Sheets service not initialized")
|
| 134 |
|
|
|
|
|
|
|
| 135 |
timestamp = datetime.now().isoformat()
|
| 136 |
|
| 137 |
+
if not conversation_id:
|
| 138 |
# Create new conversation
|
| 139 |
conversation_id = generate_conversation_id(user_id, page_id, timestamp)
|
| 140 |
values = [[
|
|
|
|
| 162 |
).execute()
|
| 163 |
else:
|
| 164 |
# Update existing conversation
|
| 165 |
+
|
|
|
|
|
|
|
| 166 |
# Find the row with this conversation_id
|
| 167 |
result = self.service.spreadsheets().values().get(
|
| 168 |
spreadsheetId=self.sheet_id,
|
|
|
|
| 178 |
break
|
| 179 |
|
| 180 |
if row_index is not None:
|
| 181 |
+
# Lấy dữ liệu dòng hiện tại
|
| 182 |
+
current_row = values[row_index]
|
| 183 |
+
# Đảm bảo đủ 9 cột
|
| 184 |
+
while len(current_row) < 9:
|
| 185 |
+
current_row.append("")
|
| 186 |
+
# Tạo dòng mới với giá trị mới nếu có, giữ nguyên nếu không
|
| 187 |
+
new_row = [
|
| 188 |
conversation_id,
|
| 189 |
+
command if command else current_row[1],
|
| 190 |
+
content if content else current_row[2],
|
| 191 |
+
json.dumps(attachments) if attachments is not None else current_row[3],
|
| 192 |
+
user_id if user_id else current_row[4],
|
| 193 |
+
page_id if page_id else current_row[5],
|
| 194 |
+
message if message else current_row[6],
|
| 195 |
+
vehicle if vehicle else current_row[7],
|
| 196 |
+
str(is_done).lower() if is_done is not None else current_row[8]
|
| 197 |
+
]
|
| 198 |
+
update_range = f"{SHEET_RANGE.split('!')[0]}!A{row_index + 1}"
|
| 199 |
body = {
|
| 200 |
+
'values': [new_row]
|
| 201 |
}
|
|
|
|
| 202 |
self.service.spreadsheets().values().update(
|
| 203 |
spreadsheetId=self.sheet_id,
|
| 204 |
range=update_range,
|
app/supabase_db.py
CHANGED
|
@@ -30,20 +30,23 @@ class SupabaseClient:
|
|
| 30 |
return None
|
| 31 |
|
| 32 |
@timing_decorator_sync
|
| 33 |
-
def match_documents(self, embedding: List[float], match_count: int = 5):
|
| 34 |
"""
|
| 35 |
Truy vấn vector similarity search qua RPC match_documents.
|
| 36 |
-
Input: embedding (list[float]), match_count (int)
|
| 37 |
Output: list[dict] kết quả truy vấn.
|
| 38 |
"""
|
| 39 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
response = self.client.rpc(
|
| 41 |
'match_documents',
|
| 42 |
-
|
| 43 |
-
'query_embedding': embedding,
|
| 44 |
-
'match_threshold': 0.7,
|
| 45 |
-
'match_count': match_count
|
| 46 |
-
}
|
| 47 |
).execute()
|
| 48 |
|
| 49 |
if response.data:
|
|
|
|
| 30 |
return None
|
| 31 |
|
| 32 |
@timing_decorator_sync
|
| 33 |
+
def match_documents(self, embedding: List[float], match_count: int = 5, vehicle_filters: Optional[List[str]] = None):
|
| 34 |
"""
|
| 35 |
Truy vấn vector similarity search qua RPC match_documents.
|
| 36 |
+
Input: embedding (list[float]), match_count (int), vehicle_filters (list[str] hoặc None)
|
| 37 |
Output: list[dict] kết quả truy vấn.
|
| 38 |
"""
|
| 39 |
try:
|
| 40 |
+
payload = {
|
| 41 |
+
'query_embedding': embedding,
|
| 42 |
+
'match_threshold': 0.7,
|
| 43 |
+
'match_count': match_count
|
| 44 |
+
}
|
| 45 |
+
if vehicle_filters is not None:
|
| 46 |
+
payload['vehicle_filters'] = vehicle_filters
|
| 47 |
response = self.client.rpc(
|
| 48 |
'match_documents',
|
| 49 |
+
payload
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
).execute()
|
| 51 |
|
| 52 |
if response.data:
|