JeCabrera commited on
Commit
6d5589e
verified
1 Parent(s): 9167aa4

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +62 -152
app.py CHANGED
@@ -309,156 +309,70 @@ for message in st.session_state.messages:
309
  st.markdown(message['content'])
310
 
311
  # React to user input
312
- if prompt := st.chat_input('驴En qu茅 puedo ayudarte hoy?'):
313
- # Verificar si es el primer mensaje del usuario
314
- is_first_message = len(st.session_state.messages) == 0
315
-
316
- # Guardar informaci贸n del chat
317
- if st.session_state.current_chat_id not in st.session_state.chats_in_memory:
318
- # Es una nueva conversaci贸n, generamos un t铆tulo basado en el primer mensaje
319
- temp_title = f'Sesi贸nChat-{st.session_state.current_chat_id}'
320
-
321
- # Generamos un t铆tulo basado en el contenido del mensaje
322
- try:
323
- title_generator = genai.GenerativeModel('gemini-2.0-flash')
324
- title_response = title_generator.generate_content(
325
- f"Genera un t铆tulo corto (m谩ximo 5 palabras) que describa de qu茅 trata esta consulta, sin usar comillas ni puntuaci贸n: '{prompt}'")
326
-
327
- generated_title = title_response.text.strip()
328
-
329
- if generated_title:
330
- st.session_state.chat_title = generated_title
331
- else:
332
- st.session_state.chat_title = temp_title
333
- except Exception as e:
334
- print(f"Error al generar t铆tulo: {e}")
335
- st.session_state.chat_title = temp_title
336
-
337
- # Guardar en memoria
338
- st.session_state.chats_in_memory[st.session_state.current_chat_id] = {
339
- 'messages': st.session_state.messages,
340
- 'gemini_history': st.session_state.gemini_history,
341
- 'title': st.session_state.chat_title
342
- }
343
-
344
- # Mostrar mensaje del usuario
345
- with st.chat_message('user', avatar=USER_AVATAR_ICON):
346
- st.markdown(prompt)
347
-
348
- # A帽adir mensaje del usuario al historial
349
- st.session_state.messages.append({
350
- 'role': 'user',
351
- 'content': prompt,
352
- 'avatar': USER_AVATAR_ICON
353
  })
354
-
355
- # Si es el primer mensaje, mostrar el mensaje de bienvenida
356
- if is_first_message:
 
 
357
  with st.chat_message(name=MODEL_ROLE, avatar=AI_AVATAR_ICON):
358
- st.markdown(WELCOME_MESSAGE)
359
-
360
- st.session_state.messages.append({
361
- 'role': MODEL_ROLE,
362
- 'content': WELCOME_MESSAGE,
363
- 'avatar': AI_AVATAR_ICON,
364
- })
365
-
366
- # Actualizar chat en memoria
367
- st.session_state.chats_in_memory[st.session_state.current_chat_id].update({
368
- 'messages': st.session_state.messages,
369
- 'gemini_history': st.session_state.gemini_history,
370
- 'title': st.session_state.chat_title
371
- })
372
- st.rerun()
373
-
374
- # Implementaci贸n de reintentos con retroceso exponencial
375
- max_retries = 3
376
  retry_count = 0
377
  while retry_count < max_retries:
378
  try:
379
- # Enviar mensaje al modelo
380
  response = st.session_state.chat.send_message(prompt, stream=True)
381
-
382
- # Procesar la respuesta completa
383
- full_text = ""
384
- for chunk in response:
385
- full_text += chunk.text
386
-
387
- # Mostrar respuesta del asistente con efecto de escritura
388
  mensaje_mostrado = mostrar_con_efecto_escritura(full_text, velocidad=0.05)
389
 
390
- # A帽adir respuesta al historial
391
- st.session_state.messages.append({
392
- 'role': MODEL_ROLE,
393
- 'content': mensaje_mostrado,
394
- 'avatar': AI_AVATAR_ICON,
395
- })
396
-
397
- # Actualizar historial
398
  st.session_state.gemini_history = st.session_state.chat.history
399
-
400
- # Actualizar chat en memoria
401
- st.session_state.chats_in_memory[st.session_state.current_chat_id].update({
402
- 'messages': st.session_state.messages,
403
- 'gemini_history': st.session_state.gemini_history,
404
- 'title': st.session_state.chat_title
405
- })
406
-
407
- break
408
 
409
  except Exception as e:
410
  retry_count += 1
411
- if retry_count >= max_retries:
412
- error_message = f"Lo siento, estoy experimentando problemas para procesar tu solicitud. Por favor, intenta de nuevo m谩s tarde. Error: {str(e)}"
413
-
414
- with st.chat_message(name=MODEL_ROLE, avatar=AI_AVATAR_ICON):
415
- st.error(error_message)
416
-
417
- st.session_state.messages.append({
418
- 'role': MODEL_ROLE,
419
- 'content': error_message,
420
- 'avatar': AI_AVATAR_ICON,
421
- })
422
-
423
- # Actualizar chat en memoria con el error
424
- st.session_state.chats_in_memory[st.session_state.current_chat_id].update({
425
- 'messages': st.session_state.messages,
426
- 'gemini_history': st.session_state.gemini_history,
427
- 'title': st.session_state.chat_title
428
- })
429
- else:
430
- wait_time = (2 ** retry_count) + (time.time() % 1)
431
- time.sleep(wait_time)
432
-
433
- # Salir del bucle si la solicitud fue exitosa
434
- break
435
 
436
- # T铆tulo y subt铆tulo principales
437
- # Inicializar el estado para los ejemplos
438
- if 'show_examples' not in st.session_state:
439
- st.session_state.show_examples = True
440
-
441
- # Funci贸n para manejar los clics de los botones
442
  def handle_example_click(prompt_text):
443
- # Reiniciar estado
444
  st.session_state.update({
445
  'show_examples': False,
446
  'messages': [],
447
  'current_chat_id': str(time.time())
448
  })
449
 
450
- # A帽adir mensaje del usuario
451
- message = {
452
- 'role': 'user',
453
- 'content': prompt_text,
454
- 'avatar': USER_AVATAR_ICON
455
- }
456
- st.session_state.messages.append(message)
457
-
458
  with st.chat_message('user', avatar=USER_AVATAR_ICON):
459
  st.markdown(prompt_text)
460
 
461
- # Actualizar chat en memoria
462
  if st.session_state.current_chat_id not in st.session_state.chats_in_memory:
463
  st.session_state.chats_in_memory[st.session_state.current_chat_id] = {
464
  'messages': st.session_state.messages,
@@ -466,32 +380,27 @@ def handle_example_click(prompt_text):
466
  'title': 'Nuevo Chat'
467
  }
468
 
469
- # Procesar la respuesta del modelo directamente
470
- try:
471
- response = st.session_state.chat.send_message(prompt_text, stream=True)
472
- full_text = ""
473
- for chunk in response:
474
- full_text += chunk.text
475
-
476
- # Mostrar respuesta del asistente
477
- mensaje_mostrado = mostrar_con_efecto_escritura(full_text, velocidad=0.05)
478
-
479
- # Actualizar historial
480
- st.session_state.messages.append({
481
- 'role': MODEL_ROLE,
482
- 'content': mensaje_mostrado,
483
- 'avatar': AI_AVATAR_ICON,
484
- })
485
- st.session_state.gemini_history = st.session_state.chat.history
486
 
487
- # Actualizar chat en memoria
488
- st.session_state.chats_in_memory[st.session_state.current_chat_id].update({
489
- 'messages': st.session_state.messages,
490
- 'gemini_history': st.session_state.gemini_history,
491
- 'title': st.session_state.chat_title
492
- })
493
- except Exception as e:
494
- st.error(f"Error al procesar la solicitud: {str(e)}")
 
 
 
 
495
 
496
  # Mostrar ejemplos solo si show_examples es True y no hay mensajes previos
497
  if st.session_state.show_examples and not st.session_state.messages:
@@ -601,3 +510,4 @@ with st.sidebar:
601
  st.session_state.gemini_history = []
602
  st.session_state.chat_title = 'Nuevo Chat'
603
  st.rerun()
 
 
309
  st.markdown(message['content'])
310
 
311
  # React to user input
312
+ # Funciones auxiliares para manejo de mensajes y errores
313
+ def add_message(role, content, avatar):
314
+ """Funci贸n centralizada para a帽adir mensajes al historial"""
315
+ message = {
316
+ 'role': role,
317
+ 'content': content,
318
+ 'avatar': avatar
319
+ }
320
+ st.session_state.messages.append(message)
321
+ return message
322
+
323
+ def update_chat_memory():
324
+ """Funci贸n centralizada para actualizar el chat en memoria"""
325
+ st.session_state.chats_in_memory[st.session_state.current_chat_id].update({
326
+ 'messages': st.session_state.messages,
327
+ 'gemini_history': st.session_state.gemini_history,
328
+ 'title': st.session_state.chat_title
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
329
  })
330
+
331
+ def handle_model_error(error, retry_count, max_retries):
332
+ """Funci贸n centralizada para manejar errores del modelo"""
333
+ if retry_count >= max_retries:
334
+ error_message = f"Lo siento, estoy experimentando problemas para procesar tu solicitud. Por favor, intenta de nuevo m谩s tarde. Error: {str(error)}"
335
  with st.chat_message(name=MODEL_ROLE, avatar=AI_AVATAR_ICON):
336
+ st.error(error_message)
337
+ add_message(MODEL_ROLE, error_message, AI_AVATAR_ICON)
338
+ update_chat_memory()
339
+ return True
340
+ return False
341
+
342
+ def process_model_response(prompt, max_retries=3):
343
+ """Funci贸n centralizada para procesar respuestas del modelo"""
 
 
 
 
 
 
 
 
 
 
344
  retry_count = 0
345
  while retry_count < max_retries:
346
  try:
 
347
  response = st.session_state.chat.send_message(prompt, stream=True)
348
+ full_text = "".join(chunk.text for chunk in response)
 
 
 
 
 
 
349
  mensaje_mostrado = mostrar_con_efecto_escritura(full_text, velocidad=0.05)
350
 
351
+ add_message(MODEL_ROLE, mensaje_mostrado, AI_AVATAR_ICON)
 
 
 
 
 
 
 
352
  st.session_state.gemini_history = st.session_state.chat.history
353
+ update_chat_memory()
354
+ return True
 
 
 
 
 
 
 
355
 
356
  except Exception as e:
357
  retry_count += 1
358
+ if handle_model_error(e, retry_count, max_retries):
359
+ return False
360
+ wait_time = (2 ** retry_count) + (time.time() % 1)
361
+ time.sleep(wait_time)
362
+ return False
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
363
 
364
+ # Modificar la funci贸n handle_example_click para usar las nuevas funciones
 
 
 
 
 
365
  def handle_example_click(prompt_text):
 
366
  st.session_state.update({
367
  'show_examples': False,
368
  'messages': [],
369
  'current_chat_id': str(time.time())
370
  })
371
 
372
+ add_message('user', prompt_text, USER_AVATAR_ICON)
 
 
 
 
 
 
 
373
  with st.chat_message('user', avatar=USER_AVATAR_ICON):
374
  st.markdown(prompt_text)
375
 
 
376
  if st.session_state.current_chat_id not in st.session_state.chats_in_memory:
377
  st.session_state.chats_in_memory[st.session_state.current_chat_id] = {
378
  'messages': st.session_state.messages,
 
380
  'title': 'Nuevo Chat'
381
  }
382
 
383
+ process_model_response(prompt_text)
384
+
385
+ # Modificar la secci贸n principal de manejo de chat
386
+ if prompt := st.chat_input('驴En qu茅 puedo ayudarte hoy?'):
387
+ is_first_message = len(st.session_state.messages) == 0
388
+
389
+ if st.session_state.current_chat_id not in st.session_state.chats_in_memory:
390
+ # ... existing code for title generation ...
 
 
 
 
 
 
 
 
 
391
 
392
+ add_message('user', prompt, USER_AVATAR_ICON)
393
+ with st.chat_message('user', avatar=USER_AVATAR_ICON):
394
+ st.markdown(prompt)
395
+
396
+ if is_first_message:
397
+ add_message(MODEL_ROLE, WELCOME_MESSAGE, AI_AVATAR_ICON)
398
+ with st.chat_message(name=MODEL_ROLE, avatar=AI_AVATAR_ICON):
399
+ st.markdown(WELCOME_MESSAGE)
400
+ update_chat_memory()
401
+ st.rerun()
402
+
403
+ process_model_response(prompt)
404
 
405
  # Mostrar ejemplos solo si show_examples es True y no hay mensajes previos
406
  if st.session_state.show_examples and not st.session_state.messages:
 
510
  st.session_state.gemini_history = []
511
  st.session_state.chat_title = 'Nuevo Chat'
512
  st.rerun()
513
+ st.rerun()