Spaces:
Running
Running
File size: 4,549 Bytes
62e3275 8d45e13 62e3275 f981512 5010813 f981512 56a81a0 84e07f0 81e1fd9 84e07f0 99ca542 81e1fd9 acd8b76 62097fd acd8b76 62097fd acd8b76 62e3275 acd8b76 81e1fd9 84e07f0 acd8b76 81e1fd9 9a58086 62e3275 62097fd acd8b76 62097fd 81e1fd9 9a58086 84e07f0 acd8b76 0815875 acd8b76 84e07f0 acd8b76 81e1fd9 acd8b76 9a58086 acd8b76 62e3275 acd8b76 9a58086 84e07f0 62097fd 81e1fd9 62097fd 84e07f0 81e1fd9 62097fd 81e1fd9 84e07f0 62097fd 81e1fd9 62097fd 84e07f0 81e1fd9 84e07f0 62097fd 84e07f0 62097fd 84e07f0 81e1fd9 84e07f0 81e1fd9 84e07f0 81e1fd9 9a58086 84e07f0 62097fd 81e1fd9 9a58086 84e07f0 5010813 81e1fd9 |
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 |
from typing import List, Tuple # Aseg煤rate de importar Tuple aqu铆
import time
import os
import google.generativeai as genai
import gradio as gr
from dotenv import load_dotenv
# Cargar las variables de entorno desde el archivo .env
load_dotenv()
# Obtener la clave de la API de las variables de entorno
GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
# Verificar que la clave de la API est茅 configurada
if not GOOGLE_API_KEY:
raise ValueError("GOOGLE_API_KEY is not set in environment variables.")
# Configuraci贸n del modelo Gemini
generation_config = {
"temperature": 1,
"top_p": 0.95,
"top_k": 40,
"max_output_tokens": 8192,
"response_mime_type": "text/plain",
}
genai.configure(api_key=GOOGLE_API_KEY)
model = genai.GenerativeModel(
model_name="gemini-1.5-flash",
generation_config=generation_config
)
# Inicializar la sesi贸n de chat
chat = model.start_chat(history=[])
# Funci贸n para transformar el historial de Gradio al formato de Gemini
def transform_history(history):
new_history = []
for chat_entry in history:
new_history.append({"parts": [{"text": chat_entry[0]}], "role": "user"})
new_history.append({"parts": [{"text": chat_entry[1]}], "role": "model"})
return new_history
# Funci贸n para simular el efecto de escribir car谩cter por car谩cter
def display_typing_effect(response_text: str, chatbot: list) -> list:
chatbot[-1][1] = "" # Borrar la 煤ltima respuesta en el chatbot
for i in range(len(response_text)):
chatbot[-1][1] += response_text[i] # Agregar un car谩cter
time.sleep(0.05) # Controlar la velocidad de escritura
yield chatbot # Mostrar el progreso en el UI
# Funci贸n de respuesta que maneja el historial
def bot_response(
model_choice: str,
system_instruction: str,
text_prompt: str,
chatbot: list,
) -> Tuple[list, str]: # Aqu铆 se usa Tuple correctamente
"""
Env铆a el mensaje al modelo, obtiene la respuesta y actualiza el historial.
"""
if not text_prompt.strip():
return chatbot, "Por favor, escribe un mensaje v谩lido."
# Transformar el historial al formato que espera Gemini
transformed_history = transform_history(chatbot)
# Configurar el modelo
chat.history = transformed_history
# Enviar el mensaje y obtener la respuesta
response = chat.send_message(text_prompt)
response.resolve()
# Obtener el texto generado por el modelo
generated_text = response.text
# Actualizar el historial con la pregunta y la respuesta
chatbot.append((text_prompt, "")) # Inicializar la respuesta vac铆a
# Mostrar la respuesta con efecto de escritura
yield from display_typing_effect(generated_text, chatbot)
# Actualizar el historial con la respuesta final
chatbot[-1] = (text_prompt, generated_text)
return chatbot, ""
# Componentes de la interfaz
chatbot_component = gr.Chatbot(label="Gemini", scale=2, height=300)
text_input_component = gr.Textbox(placeholder="Escribe un mensaje...", show_label=False, scale=8)
run_button_component = gr.Button(value="Enviar", variant="primary", scale=1)
model_dropdown_component = gr.Dropdown(
choices=["gemini-1.5-flash", "gemini-2.0-flash-exp", "gemini-1.5-pro"],
value="gemini-1.5-flash",
label="Selecciona el modelo",
scale=2
)
system_instruction_component = gr.Textbox(
placeholder="Escribe una instrucci贸n para el sistema...",
label="Instrucci贸n del sistema",
scale=8,
value="You are an assistant."
)
# Definir la interfaz
with gr.Blocks() as demo:
gr.HTML(TITLE)
gr.HTML(SUBTITLE)
with gr.Column():
model_dropdown_component.render()
chatbot_component.render()
with gr.Row():
text_input_component.render()
run_button_component.render()
with gr.Accordion("Instrucci贸n del sistema", open=False):
system_instruction_component.render()
# Configurar eventos
run_button_component.click(
fn=bot_response,
inputs=[model_dropdown_component, system_instruction_component, text_input_component, chatbot_component],
outputs=[chatbot_component, text_input_component],
)
text_input_component.submit(
fn=bot_response,
inputs=[model_dropdown_component, system_instruction_component, text_input_component, chatbot_component],
outputs=[chatbot_component, text_input_component],
)
# Lanzar la aplicaci贸n
if __name__ == "__main__":
demo.queue(max_size=99).launch(debug=True, show_error=True)
|