Spaces:
Sleeping
Sleeping
Update modules/database/chat_mongo_db.py
Browse files
modules/database/chat_mongo_db.py
CHANGED
|
@@ -1,15 +1,22 @@
|
|
| 1 |
-
|
| 2 |
from .mongo_db import insert_document, find_documents, get_collection
|
| 3 |
from datetime import datetime, timezone
|
| 4 |
import logging
|
| 5 |
-
from .database_init import get_mongodb # Aseg煤rate de que esta importaci贸n est茅 al principio del archivo
|
| 6 |
|
| 7 |
logger = logging.getLogger(__name__)
|
| 8 |
COLLECTION_NAME = 'chat_history-v3'
|
| 9 |
|
| 10 |
-
def get_chat_history(username, analysis_type='sidebar', limit=None):
|
| 11 |
"""
|
| 12 |
-
Recupera el historial del chat
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
"""
|
| 14 |
try:
|
| 15 |
query = {
|
|
@@ -17,23 +24,51 @@ def get_chat_history(username, analysis_type='sidebar', limit=None):
|
|
| 17 |
"analysis_type": analysis_type
|
| 18 |
}
|
| 19 |
|
| 20 |
-
collection = get_collection(COLLECTION_NAME)
|
| 21 |
if collection is None:
|
| 22 |
logger.error("No se pudo obtener la colecci贸n de chat")
|
| 23 |
return []
|
| 24 |
|
|
|
|
| 25 |
cursor = collection.find(query).sort("timestamp", -1)
|
| 26 |
if limit:
|
| 27 |
cursor = cursor.limit(limit)
|
| 28 |
|
| 29 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
except Exception as e:
|
| 31 |
logger.error(f"Error al recuperar historial de chat: {str(e)}")
|
| 32 |
return []
|
| 33 |
|
| 34 |
-
def store_chat_history(username, messages, analysis_type='sidebar'):
|
| 35 |
"""
|
| 36 |
-
Guarda el historial del chat
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
"""
|
| 38 |
try:
|
| 39 |
collection = get_collection(COLLECTION_NAME)
|
|
@@ -41,10 +76,20 @@ def store_chat_history(username, messages, analysis_type='sidebar'):
|
|
| 41 |
logger.error("No se pudo obtener la colecci贸n de chat")
|
| 42 |
return False
|
| 43 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
chat_document = {
|
| 45 |
'username': username,
|
| 46 |
'timestamp': datetime.now(timezone.utc).isoformat(),
|
| 47 |
-
'messages':
|
| 48 |
'analysis_type': analysis_type
|
| 49 |
}
|
| 50 |
|
|
@@ -59,7 +104,6 @@ def store_chat_history(username, messages, analysis_type='sidebar'):
|
|
| 59 |
except Exception as e:
|
| 60 |
logger.error(f"Error al guardar historial de chat: {str(e)}")
|
| 61 |
return False
|
| 62 |
-
|
| 63 |
|
| 64 |
|
| 65 |
#def get_chat_history(username, analysis_type=None, limit=10):
|
|
|
|
| 1 |
+
# /modules/database/chat_mongo_db.py
|
| 2 |
from .mongo_db import insert_document, find_documents, get_collection
|
| 3 |
from datetime import datetime, timezone
|
| 4 |
import logging
|
|
|
|
| 5 |
|
| 6 |
logger = logging.getLogger(__name__)
|
| 7 |
COLLECTION_NAME = 'chat_history-v3'
|
| 8 |
|
| 9 |
+
def get_chat_history(username: str, analysis_type: str = 'sidebar', limit: int = None) -> list:
|
| 10 |
"""
|
| 11 |
+
Recupera el historial del chat.
|
| 12 |
+
|
| 13 |
+
Args:
|
| 14 |
+
username: Nombre del usuario
|
| 15 |
+
analysis_type: Tipo de an谩lisis ('sidebar' por defecto)
|
| 16 |
+
limit: L铆mite de conversaciones a recuperar
|
| 17 |
+
|
| 18 |
+
Returns:
|
| 19 |
+
list: Lista de conversaciones con formato
|
| 20 |
"""
|
| 21 |
try:
|
| 22 |
query = {
|
|
|
|
| 24 |
"analysis_type": analysis_type
|
| 25 |
}
|
| 26 |
|
| 27 |
+
collection = get_collection(COLLECTION_NAME)
|
| 28 |
if collection is None:
|
| 29 |
logger.error("No se pudo obtener la colecci贸n de chat")
|
| 30 |
return []
|
| 31 |
|
| 32 |
+
# Obtener y formatear conversaciones
|
| 33 |
cursor = collection.find(query).sort("timestamp", -1)
|
| 34 |
if limit:
|
| 35 |
cursor = cursor.limit(limit)
|
| 36 |
|
| 37 |
+
conversations = []
|
| 38 |
+
for chat in cursor:
|
| 39 |
+
try:
|
| 40 |
+
formatted_chat = {
|
| 41 |
+
'timestamp': chat['timestamp'],
|
| 42 |
+
'messages': [
|
| 43 |
+
{
|
| 44 |
+
'role': msg.get('role', 'unknown'),
|
| 45 |
+
'content': msg.get('content', '')
|
| 46 |
+
}
|
| 47 |
+
for msg in chat.get('messages', [])
|
| 48 |
+
]
|
| 49 |
+
}
|
| 50 |
+
conversations.append(formatted_chat)
|
| 51 |
+
except Exception as e:
|
| 52 |
+
logger.error(f"Error formateando chat: {str(e)}")
|
| 53 |
+
continue
|
| 54 |
+
|
| 55 |
+
return conversations
|
| 56 |
+
|
| 57 |
except Exception as e:
|
| 58 |
logger.error(f"Error al recuperar historial de chat: {str(e)}")
|
| 59 |
return []
|
| 60 |
|
| 61 |
+
def store_chat_history(username: str, messages: list, analysis_type: str = 'sidebar') -> bool:
|
| 62 |
"""
|
| 63 |
+
Guarda el historial del chat.
|
| 64 |
+
|
| 65 |
+
Args:
|
| 66 |
+
username: Nombre del usuario
|
| 67 |
+
messages: Lista de mensajes a guardar
|
| 68 |
+
analysis_type: Tipo de an谩lisis
|
| 69 |
+
|
| 70 |
+
Returns:
|
| 71 |
+
bool: True si se guard贸 correctamente
|
| 72 |
"""
|
| 73 |
try:
|
| 74 |
collection = get_collection(COLLECTION_NAME)
|
|
|
|
| 76 |
logger.error("No se pudo obtener la colecci贸n de chat")
|
| 77 |
return False
|
| 78 |
|
| 79 |
+
# Formatear mensajes antes de guardar
|
| 80 |
+
formatted_messages = [
|
| 81 |
+
{
|
| 82 |
+
'role': msg.get('role', 'unknown'),
|
| 83 |
+
'content': msg.get('content', ''),
|
| 84 |
+
'timestamp': datetime.now(timezone.utc).isoformat()
|
| 85 |
+
}
|
| 86 |
+
for msg in messages
|
| 87 |
+
]
|
| 88 |
+
|
| 89 |
chat_document = {
|
| 90 |
'username': username,
|
| 91 |
'timestamp': datetime.now(timezone.utc).isoformat(),
|
| 92 |
+
'messages': formatted_messages,
|
| 93 |
'analysis_type': analysis_type
|
| 94 |
}
|
| 95 |
|
|
|
|
| 104 |
except Exception as e:
|
| 105 |
logger.error(f"Error al guardar historial de chat: {str(e)}")
|
| 106 |
return False
|
|
|
|
| 107 |
|
| 108 |
|
| 109 |
#def get_chat_history(username, analysis_type=None, limit=10):
|