GPT_copy / app.py
JeCabrera's picture
Update app.py
1b93766 verified
raw
history blame
1.46 kB
import os
import time
import gradio as gr
import google.generativeai as genai
from dotenv import load_dotenv
# Cargar variables de entorno
load_dotenv()
# Configurar la API de Google con la clave
genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
# Crear la sesi贸n de chat con el modelo de Gemini
model = genai.GenerativeModel("gemini-2.0-flash")
def chat_stream(message, history):
"""Env铆a el mensaje del usuario a Gemini con historial y devuelve la respuesta en streaming."""
try:
# Crear una conversaci贸n nueva
chat = model.start_chat()
# Agregar el historial previo a la conversaci贸n
for user_msg, assistant_msg in history:
chat.send_message(user_msg)
# Enviar el mensaje actual y obtener la respuesta en streaming
response = chat.send_message(message, stream=True)
# Devolver los fragmentos como un flujo
for chunk in response:
if chunk.text:
time.sleep(0.05) # A帽ade un peque帽o retraso de 50ms entre chunks
yield chunk.text
except Exception as e:
yield f"Error: {e}"
# Crear la interfaz de chat con historial
demo = gr.ChatInterface(
fn=chat_stream,
examples=["Write an example Python lambda function."],
title="Gemini Chatbot",
description="Chatbot interactivo con historial de conversaci贸n usando Gemini AI."
)
# Iniciar la app
demo.launch()