File size: 3,841 Bytes
1ffb5bb
9a5bed3
aa3daf7
 
 
 
 
 
1ffb5bb
e64914d
1ffb5bb
 
 
 
 
 
 
 
 
e64914d
 
 
 
 
 
 
1ffb5bb
e64914d
 
 
 
1ffb5bb
e64914d
 
 
 
1ffb5bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e64914d
 
 
 
1ffb5bb
b520edc
1ffb5bb
 
 
 
 
 
 
 
 
b520edc
 
e64914d
 
 
 
 
1ffb5bb
 
 
 
 
 
 
 
 
 
b520edc
 
 
1ffb5bb
b520edc
 
 
e64914d
 
 
b520edc
e64914d
 
b520edc
e64914d
b520edc
 
 
 
 
e64914d
aa3daf7
 
 
 
 
 
c58df45
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
# /modules/database/chat_mongo_db.py
from .mongo_db import insert_document, find_documents, get_collection
from datetime import datetime, timezone
import logging

logger = logging.getLogger(__name__)
COLLECTION_NAME = 'chat_history-v3'

def get_chat_history(username: str, analysis_type: str = 'sidebar', limit: int = None) -> list:
    """
    Recupera el historial del chat.
    
    Args:
        username: Nombre del usuario
        analysis_type: Tipo de an谩lisis ('sidebar' por defecto)
        limit: L铆mite de conversaciones a recuperar
        
    Returns:
        list: Lista de conversaciones con formato
    """
    try:
        query = {
            "username": username,
            "analysis_type": analysis_type
        }
        
        collection = get_collection(COLLECTION_NAME)
        if collection is None:
            logger.error("No se pudo obtener la colecci贸n de chat")
            return []
            
        # Obtener y formatear conversaciones
        cursor = collection.find(query).sort("timestamp", -1)
        if limit:
            cursor = cursor.limit(limit)
            
        conversations = []
        for chat in cursor:
            try:
                formatted_chat = {
                    'timestamp': chat['timestamp'],
                    'messages': [
                        {
                            'role': msg.get('role', 'unknown'),
                            'content': msg.get('content', '')
                        }
                        for msg in chat.get('messages', [])
                    ]
                }
                conversations.append(formatted_chat)
            except Exception as e:
                logger.error(f"Error formateando chat: {str(e)}")
                continue
                
        return conversations
        
    except Exception as e:
        logger.error(f"Error al recuperar historial de chat: {str(e)}")
        return []

def store_chat_history(username: str, messages: list, analysis_type: str = 'sidebar') -> bool:
    """
    Guarda el historial del chat.
    
    Args:
        username: Nombre del usuario
        messages: Lista de mensajes a guardar
        analysis_type: Tipo de an谩lisis
    
    Returns:
        bool: True si se guard贸 correctamente
    """
    try:
        collection = get_collection(COLLECTION_NAME)
        if collection is None:
            logger.error("No se pudo obtener la colecci贸n de chat")
            return False
            
        # Formatear mensajes antes de guardar
        formatted_messages = [
            {
                'role': msg.get('role', 'unknown'),
                'content': msg.get('content', ''),
                'timestamp': datetime.now(timezone.utc).isoformat()
            }
            for msg in messages
        ]
        
        chat_document = {
            'username': username,
            'timestamp': datetime.now(timezone.utc).isoformat(),
            'messages': formatted_messages,
            'analysis_type': analysis_type
        }
        
        result = collection.insert_one(chat_document)
        if result.inserted_id:
            logger.info(f"Historial de chat guardado con ID: {result.inserted_id} para el usuario: {username}")
            return True
            
        logger.error("No se pudo insertar el documento")
        return False
        
    except Exception as e:
        logger.error(f"Error al guardar historial de chat: {str(e)}")
        return False
        
        
        #def get_chat_history(username, analysis_type=None, limit=10):
#    query = {"username": username}
#    if analysis_type:
#        query["analysis_type"] = analysis_type

#    return find_documents(COLLECTION_NAME, query, sort=[("timestamp", -1)], limit=limit)

# Agregar funciones para actualizar y eliminar chat si es necesario