Spaces:
Running
Running
Update modules/database/chat_mongo_db.py
Browse files- modules/database/chat_mongo_db.py +116 -115
modules/database/chat_mongo_db.py
CHANGED
@@ -1,116 +1,117 @@
|
|
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 = {
|
23 |
-
"username": username,
|
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)
|
75 |
-
if collection is None:
|
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 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
#
|
111 |
-
#
|
112 |
-
#
|
113 |
-
|
114 |
-
|
115 |
-
|
|
|
116 |
# Agregar funciones para actualizar y eliminar chat si es necesario
|
|
|
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 = {
|
23 |
+
"username": username,
|
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)
|
75 |
+
if collection is None:
|
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 |
+
'metadata': metadata or {} # Nuevo campo 18-5-2025
|
95 |
+
}
|
96 |
+
|
97 |
+
result = collection.insert_one(chat_document)
|
98 |
+
if result.inserted_id:
|
99 |
+
logger.info(f"Historial de chat guardado con ID: {result.inserted_id} para el usuario: {username}")
|
100 |
+
return True
|
101 |
+
|
102 |
+
logger.error("No se pudo insertar el documento")
|
103 |
+
return False
|
104 |
+
|
105 |
+
except Exception as e:
|
106 |
+
logger.error(f"Error al guardar historial de chat: {str(e)}")
|
107 |
+
return False
|
108 |
+
|
109 |
+
|
110 |
+
#def get_chat_history(username, analysis_type=None, limit=10):
|
111 |
+
# query = {"username": username}
|
112 |
+
# if analysis_type:
|
113 |
+
# query["analysis_type"] = analysis_type
|
114 |
+
|
115 |
+
# return find_documents(COLLECTION_NAME, query, sort=[("timestamp", -1)], limit=limit)
|
116 |
+
|
117 |
# Agregar funciones para actualizar y eliminar chat si es necesario
|