Spaces:
Sleeping
Sleeping
| import os | |
| import gradio as gr | |
| from sambanova import SambaNova | |
| # Configuración - IMPORTANTE: Configura esto en Secrets de Hugging Face | |
| API_KEY = os.getenv("SAMBANOVA_API_KEY") | |
| def chat_with_sambanova(message, history): | |
| """ | |
| Función de chat para Batuto_Qwin usando SambaNova API | |
| """ | |
| if not API_KEY: | |
| return "❌ Error: Configura SAMBANOVA_API_KEY en los Secrets de Hugging Face" | |
| try: | |
| # Inicializar cliente SambaNova | |
| client = SambaNova( | |
| api_key=API_KEY, | |
| base_url="https://api.sambanova.ai/v1", | |
| ) | |
| # Construir mensajes desde el historial | |
| messages = [ | |
| {"role": "system", "content": "Eres Batuto_Qwin, un asistente inteligente, rápido y muy útil. Responde en español de forma clara y concisa."} | |
| ] | |
| # Procesar historial de conversación | |
| for user_msg, bot_msg in history: | |
| messages.append({"role": "user", "content": user_msg}) | |
| if bot_msg: # Solo agregar si no está vacío | |
| messages.append({"role": "assistant", "content": bot_msg}) | |
| # Agregar mensaje actual del usuario | |
| messages.append({"role": "user", "content": message}) | |
| # Llamar a la API de SambaNova | |
| response = client.chat.completions.create( | |
| model="Qwen3-32B", # Modelo Qwen | |
| messages=messages, | |
| temperature=0.7, # Balance entre creatividad y precisión | |
| top_p=0.9, | |
| max_tokens=1024 | |
| ) | |
| return response.choices[0].message.content | |
| except Exception as e: | |
| error_msg = str(e) | |
| if "401" in error_msg: | |
| return "❌ Error de autenticación: Verifica tu API Key de SambaNova" | |
| elif "404" in error_msg: | |
| return "❌ Error: Modelo Qwen3-32B no disponible" | |
| elif "429" in error_msg: | |
| return "❌ Límite de tasa excedido: Espera un momento" | |
| else: | |
| return f"❌ Error: {error_msg}" | |
| # Crear interfaz Gradio para Batuto_Qwin | |
| with gr.Blocks( | |
| title="🤖 Batuto_Qwin", | |
| theme=gr.themes.Soft(primary_hue="emerald"), | |
| css=""" | |
| .gradio-container { | |
| max-width: 800px !important; | |
| margin: auto; | |
| } | |
| .header { | |
| text-align: center; | |
| padding: 20px; | |
| } | |
| """ | |
| ) as demo: | |
| # Header personalizado para Batuto_Qwin | |
| with gr.Column(elem_classes="header"): | |
| gr.Markdown(""" | |
| # 🤖 Batuto_Qwin | |
| ### *Tu asistente inteligente con Qwen3-32B* | |
| **Características:** | |
| 🚀 Rápido y eficiente • 🧠 Basado en Qwen3-32B • 💬 Conversaciones naturales | |
| """) | |
| # Chatbot | |
| chatbot = gr.Chatbot( | |
| label="💬 Conversación con Batuto_Qwin", | |
| height=450, | |
| show_copy_button=True, | |
| type="messages", | |
| avatar_images=( | |
| "👤", # Avatar usuario | |
| "🤖" # Avatar Batuto_Qwin | |
| ) | |
| ) | |
| # Input area | |
| with gr.Row(): | |
| msg = gr.Textbox( | |
| label="", | |
| placeholder="Escribe tu mensaje para Batuto_Qwin...", | |
| scale=4, | |
| max_lines=3, | |
| container=False | |
| ) | |
| # Botones con estilo | |
| with gr.Row(): | |
| submit_btn = gr.Button("🚀 Enviar a Batuto_Qwin", variant="primary", scale=2) | |
| clear_btn = gr.Button("🧹 Limpiar", variant="secondary", scale=1) | |
| # Estado del sistema | |
| with gr.Row(): | |
| status = gr.Markdown( | |
| f"**Estado del sistema:** {'✅ Conectado a SambaNova' if API_KEY else '❌ Esperando configuración de API Key'}" | |
| ) | |
| # Función de respuesta | |
| def respond(message, chat_history): | |
| if not message or not message.strip(): | |
| return "", chat_history | |
| # Mostrar mensaje del usuario inmediatamente | |
| chat_history.append({"role": "user", "content": message}) | |
| # Obtener respuesta de Batuto_Qwin | |
| bot_message = chat_with_sambanova(message, chat_history) | |
| # Actualizar historial con respuesta | |
| chat_history.append({"role": "assistant", "content": bot_message}) | |
| return "", chat_history | |
| # Event handlers | |
| submit_btn.click( | |
| respond, | |
| inputs=[msg, chatbot], | |
| outputs=[msg, chatbot] | |
| ) | |
| msg.submit( | |
| respond, | |
| inputs=[msg, chatbot], | |
| outputs=[msg, chatbot] | |
| ) | |
| clear_btn.click( | |
| lambda: ([], ""), | |
| outputs=[chatbot, msg] | |
| ) | |
| # Ejemplos de uso | |
| with gr.Accordion("💡 Ejemplos para probar", open=False): | |
| gr.Examples( | |
| examples=[ | |
| "Explícame qué es Batuto_Qwin", | |
| "Ayúdame a escribir un código Python simple", | |
| "¿Cuáles son las ventajas de Qwen3-32B?", | |
| "Háblame sobre inteligencia artificial" | |
| ], | |
| inputs=msg | |
| ) | |
| if __name__ == "__main__": | |
| demo.launch( | |
| share=False, | |
| show_error=True, | |
| favicon_path="https://em-content.zobj.net/source/microsoft/319/robot_1f916.png" | |
| ) |