File size: 9,740 Bytes
6748f9a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92c9eaf
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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
import streamlit as st
import joblib
import os
from google import genai
from google.genai import types

DEFAULT_GEMINI_MODEL = 'gemini-3.1-flash-lite-preview'
DATA_DIR = 'data'
PAST_CHATS_LIST_PATH = f'{DATA_DIR}/past_chats_list'

class SessionState:
    """
    Clase para gestionar el estado de la sesión de Streamlit de manera centralizada.
    Encapsula todas las operaciones relacionadas con st.session_state.
    """
    
    def __init__(self):
        # Inicializar valores por defecto si no existen
        if 'chat_id' not in st.session_state:
            st.session_state.chat_id = None
        
        if 'chat_title' not in st.session_state:
            st.session_state.chat_title = None
            
        if 'messages' not in st.session_state:
            st.session_state.messages = []
            
        if 'gemini_history' not in st.session_state:
            st.session_state.gemini_history = []
            
        if 'model' not in st.session_state:
            st.session_state.model = None

        if 'client' not in st.session_state:
            st.session_state.client = None
            
        if 'chat' not in st.session_state:
            st.session_state.chat = None
            
        if 'prompt' not in st.session_state:
            st.session_state.prompt = None

        if 'system_instruction' not in st.session_state:
            st.session_state.system_instruction = None
    
    # Getters y setters para cada propiedad
    @property
    def chat_id(self):
        return st.session_state.chat_id
    
    @chat_id.setter
    def chat_id(self, value):
        st.session_state.chat_id = value
    
    @property
    def chat_title(self):
        return st.session_state.chat_title
    
    @chat_title.setter
    def chat_title(self, value):
        st.session_state.chat_title = value
    
    @property
    def messages(self):
        return st.session_state.messages
    
    @messages.setter
    def messages(self, value):
        st.session_state.messages = value
    
    @property
    def gemini_history(self):
        return st.session_state.gemini_history
    
    @gemini_history.setter
    def gemini_history(self, value):
        st.session_state.gemini_history = value
    
    @property
    def model(self):
        return st.session_state.model
    
    @model.setter
    def model(self, value):
        st.session_state.model = value

    @property
    def client(self):
        return st.session_state.client

    @client.setter
    def client(self, value):
        st.session_state.client = value
    
    @property
    def chat(self):
        return st.session_state.chat
    
    @chat.setter
    def chat(self, value):
        st.session_state.chat = value
    
    @property
    def prompt(self):
        return st.session_state.prompt
    
    @prompt.setter
    def prompt(self, value):
        st.session_state.prompt = value

    @property
    def system_instruction(self):
        return st.session_state.system_instruction

    @system_instruction.setter
    def system_instruction(self, value):
        st.session_state.system_instruction = value

    # Métodos de utilidad
    def add_message(self, role, content, avatar=None):
        """Añade un mensaje al historial"""
        message = {
            'role': role,
            'content': content,
        }
        if avatar:
            message['avatar'] = avatar
        self.messages.append(message)
    
    def clear_prompt(self):
        """Limpia el prompt del estado de la sesión"""
        self.prompt = None

    def initialize_model(self, model_name=None, api_key=None):
        """Inicializa el modelo de IA"""
        if model_name is None:
            model_name = DEFAULT_GEMINI_MODEL
        if api_key is None:
            api_key = os.environ.get('GOOGLE_API_KEY')
        self.client = genai.Client(api_key=api_key)
        self.model = model_name
    
    def initialize_chat(self, history=None, system_instruction=None):
        """Inicializa el chat con el modelo"""
        if history is None:
            history = self.gemini_history
        if system_instruction is None:
            system_instruction = self.system_instruction
        else:
            self.system_instruction = system_instruction
        
        # Asegurar que el modelo está inicializado
        if self.model is None or self.client is None:
            self.initialize_model()

        chat_kwargs = {'model': self.model}
        if history:
            chat_kwargs['history'] = history
        if system_instruction:
            chat_kwargs['config'] = types.GenerateContentConfig(
                system_instruction=system_instruction
            )

        # Inicializar chat con el SDK moderno
        self.chat = self.client.chats.create(**chat_kwargs)
        
        # Verificar que el chat se inicializó correctamente
        if self.chat is None:
            raise ValueError("Error al inicializar el chat")
    
    def send_message(self, prompt, stream=True):
        """Método unificado para enviar mensajes y mantener el streaming"""
        try:
            if self.chat is None:
                self.initialize_chat()
                
            if stream:
                return self.chat.send_message_stream(prompt)
            return self.chat.send_message(prompt)
        except Exception as e:
            print(f"Error al enviar mensaje: {e}")
            # Reintentar una vez si hay error
            self.initialize_chat()
            if stream:
                return self.chat.send_message_stream(prompt)
            return self.chat.send_message(prompt)
    
    def generate_chat_title(self, prompt, model_name=None):
        """Genera un título para el chat basado en el primer mensaje"""
        try:
            if model_name is None:
                model_name = DEFAULT_GEMINI_MODEL
            if self.client is None:
                self.client = genai.Client(api_key=os.environ.get('GOOGLE_API_KEY'))
            title_response = self.client.models.generate_content(
                model=model_name,
                contents=(
                    "Genera un título natural y humano en español (3 a 6 palabras) "
                    "que resuma esta consulta. No uses separadores tipo '|', no uses etiquetas, "
                    "no uses comillas y evita formato robótico. Devuelve solo el título final: "
                    f"'{prompt}'"
                )
            )
            cleaned_title = " ".join(
                title_response.text.strip().replace('"', '').replace('|', ' ').split()
            )
            return " ".join(cleaned_title.split()[:6])
        except Exception as e:
            print(f"Error al generar título: {e}")
            return None
    
    def save_chat_history(self, chat_id=None):
        """Guarda el historial del chat"""
        if chat_id is None:
            chat_id = self.chat_id
        
        serialized_history = self._serialize_gemini_history(self.gemini_history)
        os.makedirs(DATA_DIR, exist_ok=True)
        joblib.dump(self.messages, self._st_messages_path(chat_id))
        joblib.dump(serialized_history, self._gemini_messages_path(chat_id))
    
    def load_chat_history(self, chat_id=None):
        """Carga el historial del chat"""
        if chat_id is None:
            chat_id = self.chat_id
        
        try:
            self.messages = joblib.load(self._st_messages_path(chat_id))
            loaded_history = joblib.load(self._gemini_messages_path(chat_id))
            self.gemini_history = self._deserialize_gemini_history(loaded_history)
            return True
        except (FileNotFoundError, EOFError):
            self.messages = []
            self.gemini_history = []
            return False

    def _st_messages_path(self, chat_id):
        return f'{DATA_DIR}/{chat_id}-st_messages'

    def _gemini_messages_path(self, chat_id):
        return f'{DATA_DIR}/{chat_id}-gemini_messages'

    def _serialize_gemini_history(self, history):
        """Convierte tipos del SDK (Content/Part) a diccionarios serializables."""
        serialized = []
        for item in history or []:
            if isinstance(item, dict):
                serialized.append(item)
                continue
            if hasattr(item, "model_dump"):
                serialized.append(item.model_dump(mode="python"))
                continue
            if hasattr(item, "to_dict"):
                serialized.append(item.to_dict())
                continue
            serialized.append(item)
        return serialized

    def _deserialize_gemini_history(self, history):
        """Reconstruye Content para rehidratar chat history en google-genai."""
        deserialized = []
        for item in history or []:
            if isinstance(item, dict) and "role" in item and "parts" in item:
                role = item.get("role")
                parts_data = item.get("parts", [])
                parts = []
                for part in parts_data:
                    if isinstance(part, dict) and "text" in part:
                        parts.append(types.Part(text=part["text"]))
                    elif isinstance(part, str):
                        parts.append(types.Part(text=part))
                if parts:
                    deserialized.append(types.Content(role=role, parts=parts))
                    continue
            deserialized.append(item)
        return deserialized
    
    def has_messages(self):
        """Verifica si hay mensajes en el historial"""
        return len(self.messages) > 0
    
    def has_prompt(self):
        """Verifica si hay un prompt en el estado de la sesión"""
        return self.prompt is not None and self.prompt.strip() != ""