Spaces:
Running
Running
import time | |
import gradio as gr | |
import google.generativeai as genai | |
import os | |
# Cargar la clave de la API de Gemini desde el entorno | |
GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY") | |
if not GOOGLE_API_KEY: | |
raise ValueError("GOOGLE_API_KEY is not set in environment variables.") | |
# Configurar la API de Gemini | |
genai.configure(api_key=GOOGLE_API_KEY) | |
# Inicializar el chat de Gemini | |
chat = genai.Chat() | |
# Transformar el historial de Gradio a formato compatible con Gemini | |
def transform_history(history): | |
new_history = [] | |
for chat in history: | |
new_history.append({"parts": [{"text": chat[0]}], "role": "user"}) | |
new_history.append({"parts": [{"text": chat[1]}], "role": "model"}) | |
return new_history | |
# Función para generar una respuesta con Gemini | |
def response(message, history): | |
global chat | |
# Actualizar el historial con el formato correcto | |
chat.history = transform_history(history) | |
# Enviar el mensaje a la API de Gemini | |
response = chat.send_message(message) | |
response.resolve() | |
# Mostrar la respuesta mientras se escribe | |
for i in range(len(response.text)): | |
time.sleep(0.05) | |
yield response.text[: i + 1] | |
# Interfaz de usuario con Gradio | |
gr.ChatInterface(response, | |
title='Gemini Chat', | |
textbox=gr.Textbox(placeholder="Pregunta a Gemini"), | |
retry_btn=None).launch(debug=True) | |