Spaces:
Sleeping
Sleeping
File size: 1,458 Bytes
093162a 1b93766 446d2fd f68f2c5 ff48396 a6341df ff48396 a6341df b01ef58 06c02ed ff48396 d135972 b01ef58 ff48396 d135972 403eda5 ff48396 76612f3 403eda5 76612f3 1b93766 76612f3 403eda5 ff48396 403eda5 ff48396 a6341df d135972 ff48396 a6341df 5906ce7 ff48396 29f787a |
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 |
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()
|