import gradio as gr from huggingface_hub import InferenceClient # Cliente de IA gratuito y sin límites client = InferenceClient("Qwen/Qwen2.5-7B-Instruct") def responder(mensaje, historial, sistema, temperatura): # 1. Preparar el contexto y la personalidad mensajes_api = [{"role": "system", "content": sistema}] # 2. Cargar el historial previo para que la IA tenga memoria for msg in historial: mensajes_api.append({"role": "user", "content": msg[0]}) if msg[1] is not None: mensajes_api.append({"role": "assistant", "content": msg[1]}) # 3. Añadir el mensaje actual del usuario mensajes_api.append({"role": "user", "content": mensaje}) respuesta_generada = "" try: # Llamar al modelo de IA en la nube stream = client.chat_completion( mensajes_api, max_tokens=1024, temperature=temperatura, stream=True ) for chunk in stream: texto = chunk.choices[0].delta.content if texto is not None: respuesta_generada += texto yield respuesta_generada except Exception as e: yield f"⚠️ Error de conexión con el servidor: {str(e)}" # --- INTERFAZ PROFESIONAL CON BOTONES FUNCIONALES --- with gr.Blocks(theme=gr.themes.Ocean()) as demo: gr.Markdown("

🤖 Mi Inteligencia Artificial Privada

") with gr.Row(): # COLUMNA IZQUIERDA (Ajustes y Botones) with gr.Column(scale=1, variant="panel"): gr.Markdown("### ⚙️ Ajustes del Chat") sistema_input = gr.Textbox( value="Eres un asistente ultra-inteligente, amigable y experto. Respondes siempre en español.", label="Instrucciones de la IA (Personalidad)", lines=3 ) temp_input = gr.Slider(minimum=0.1, maximum=1.5, value=0.7, step=0.1, label="Nivel de Creatividad") gr.Markdown("---") gr.Markdown("### 🛠️ Herramientas") # Botón funcional para borrar la memoria del chat btn_limpiar = gr.Button("🗑️ Limpiar Conversación", variant="secondary") # Panel de información desplegable with gr.Accordion("ℹ️ Información del Servidor", open=False): gr.Markdown("**Host:** Hugging Face Spaces\n**Motor IA:** Qwen 2.5 (7B)\n**Estado:** Online") # COLUMNA DERECHA (La ventana principal del Chat) with gr.Column(scale=3): chatbot = gr.Chatbot(height=500, label="Chat en vivo", bubble_full_width=False) with gr.Row(): mensaje_input = gr.Textbox(placeholder="Escribe tu mensaje aquí y presiona Enter...", show_label=False, scale=4) btn_enviar = gr.Button("Enviar 🚀", variant="primary", scale=1) # --- LÓGICA INTERNA DE LOS BOTONES --- def procesar_mensaje(mensaje_usuario, historial): # Muestra el mensaje del usuario en la pantalla inmediatamente if not mensaje_usuario.strip(): return "", historial return "", historial + [[mensaje_usuario, None]] def generar_respuesta(historial, sistema, temperatura): # Toma el último mensaje y genera la respuesta de la IA poco a poco if not historial or historial[-1][0] is None: yield historial return mensaje_usuario = historial[-1][0] historial_previo = historial[:-1] generador = responder(mensaje_usuario, historial_previo, sistema, temperatura) for texto_parcial in generador: historial[-1][1] = texto_parcial yield historial # 1. Acción al presionar "Enter" en la caja de texto mensaje_input.submit( procesar_mensaje, [mensaje_input, chatbot], [mensaje_input, chatbot], queue=False ).then( generar_respuesta, [chatbot, sistema_input, temp_input], chatbot ) # 2. Acción al presionar el botón "Enviar" btn_enviar.click( procesar_mensaje, [mensaje_input, chatbot], [mensaje_input, chatbot], queue=False ).then( generar_respuesta, [chatbot, sistema_input, temp_input], chatbot ) # 3. Acción al presionar el botón "Limpiar Conversación" btn_limpiar.click(lambda: None, None, chatbot, queue=False) if __name__ == "__main__": demo.launch()