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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
import gradio as gr
|
| 3 |
+
from sambanova import SambaNova
|
| 4 |
+
|
| 5 |
+
# Configuración - IMPORTANTE: Configura esto en Secrets de Hugging Face
|
| 6 |
+
API_KEY = os.getenv("SAMBANOVA_API_KEY")
|
| 7 |
+
|
| 8 |
+
def chat_with_sambanova(message, history):
|
| 9 |
+
"""
|
| 10 |
+
Función de chat para Batuto_Qwin usando SambaNova API
|
| 11 |
+
"""
|
| 12 |
+
if not API_KEY:
|
| 13 |
+
return "❌ Error: Configura SAMBANOVA_API_KEY en los Secrets de Hugging Face"
|
| 14 |
+
|
| 15 |
+
try:
|
| 16 |
+
# Inicializar cliente SambaNova
|
| 17 |
+
client = SambaNova(
|
| 18 |
+
api_key=API_KEY,
|
| 19 |
+
base_url="https://api.sambanova.ai/v1",
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
# Construir mensajes desde el historial
|
| 23 |
+
messages = [
|
| 24 |
+
{"role": "system", "content": "Eres Batuto_Qwin, un asistente inteligente, rápido y muy útil. Responde en español de forma clara y concisa."}
|
| 25 |
+
]
|
| 26 |
+
|
| 27 |
+
# Procesar historial de conversación
|
| 28 |
+
for user_msg, bot_msg in history:
|
| 29 |
+
messages.append({"role": "user", "content": user_msg})
|
| 30 |
+
if bot_msg: # Solo agregar si no está vacío
|
| 31 |
+
messages.append({"role": "assistant", "content": bot_msg})
|
| 32 |
+
|
| 33 |
+
# Agregar mensaje actual del usuario
|
| 34 |
+
messages.append({"role": "user", "content": message})
|
| 35 |
+
|
| 36 |
+
# Llamar a la API de SambaNova
|
| 37 |
+
response = client.chat.completions.create(
|
| 38 |
+
model="Qwen3-32B", # Modelo Qwen
|
| 39 |
+
messages=messages,
|
| 40 |
+
temperature=0.7, # Balance entre creatividad y precisión
|
| 41 |
+
top_p=0.9,
|
| 42 |
+
max_tokens=1024
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
return response.choices[0].message.content
|
| 46 |
+
|
| 47 |
+
except Exception as e:
|
| 48 |
+
error_msg = str(e)
|
| 49 |
+
if "401" in error_msg:
|
| 50 |
+
return "❌ Error de autenticación: Verifica tu API Key de SambaNova"
|
| 51 |
+
elif "404" in error_msg:
|
| 52 |
+
return "❌ Error: Modelo Qwen3-32B no disponible"
|
| 53 |
+
elif "429" in error_msg:
|
| 54 |
+
return "❌ Límite de tasa excedido: Espera un momento"
|
| 55 |
+
else:
|
| 56 |
+
return f"❌ Error: {error_msg}"
|
| 57 |
+
|
| 58 |
+
# Crear interfaz Gradio para Batuto_Qwin
|
| 59 |
+
with gr.Blocks(
|
| 60 |
+
title="🤖 Batuto_Qwin",
|
| 61 |
+
theme=gr.themes.Soft(primary_hue="emerald"),
|
| 62 |
+
css="""
|
| 63 |
+
.gradio-container {
|
| 64 |
+
max-width: 800px !important;
|
| 65 |
+
margin: auto;
|
| 66 |
+
}
|
| 67 |
+
.header {
|
| 68 |
+
text-align: center;
|
| 69 |
+
padding: 20px;
|
| 70 |
+
}
|
| 71 |
+
"""
|
| 72 |
+
) as demo:
|
| 73 |
+
|
| 74 |
+
# Header personalizado para Batuto_Qwin
|
| 75 |
+
with gr.Column(elem_classes="header"):
|
| 76 |
+
gr.Markdown("""
|
| 77 |
+
# 🤖 Batuto_Qwin
|
| 78 |
+
### *Tu asistente inteligente con Qwen3-32B*
|
| 79 |
+
|
| 80 |
+
**Características:**
|
| 81 |
+
🚀 Rápido y eficiente • 🧠 Basado en Qwen3-32B • 💬 Conversaciones naturales
|
| 82 |
+
""")
|
| 83 |
+
|
| 84 |
+
# Chatbot
|
| 85 |
+
chatbot = gr.Chatbot(
|
| 86 |
+
label="💬 Conversación con Batuto_Qwin",
|
| 87 |
+
height=450,
|
| 88 |
+
show_copy_button=True,
|
| 89 |
+
type="messages",
|
| 90 |
+
avatar_images=(
|
| 91 |
+
"👤", # Avatar usuario
|
| 92 |
+
"🤖" # Avatar Batuto_Qwin
|
| 93 |
+
)
|
| 94 |
+
)
|
| 95 |
+
|
| 96 |
+
# Input area
|
| 97 |
+
with gr.Row():
|
| 98 |
+
msg = gr.Textbox(
|
| 99 |
+
label="",
|
| 100 |
+
placeholder="Escribe tu mensaje para Batuto_Qwin...",
|
| 101 |
+
scale=4,
|
| 102 |
+
max_lines=3,
|
| 103 |
+
container=False
|
| 104 |
+
)
|
| 105 |
+
|
| 106 |
+
# Botones con estilo
|
| 107 |
+
with gr.Row():
|
| 108 |
+
submit_btn = gr.Button("🚀 Enviar a Batuto_Qwin", variant="primary", scale=2)
|
| 109 |
+
clear_btn = gr.Button("🧹 Limpiar", variant="secondary", scale=1)
|
| 110 |
+
|
| 111 |
+
# Estado del sistema
|
| 112 |
+
with gr.Row():
|
| 113 |
+
status = gr.Markdown(
|
| 114 |
+
f"**Estado del sistema:** {'✅ Conectado a SambaNova' if API_KEY else '❌ Esperando configuración de API Key'}"
|
| 115 |
+
)
|
| 116 |
+
|
| 117 |
+
# Función de respuesta
|
| 118 |
+
def respond(message, chat_history):
|
| 119 |
+
if not message or not message.strip():
|
| 120 |
+
return "", chat_history
|
| 121 |
+
|
| 122 |
+
# Mostrar mensaje del usuario inmediatamente
|
| 123 |
+
chat_history.append({"role": "user", "content": message})
|
| 124 |
+
|
| 125 |
+
# Obtener respuesta de Batuto_Qwin
|
| 126 |
+
bot_message = chat_with_sambanova(message, chat_history)
|
| 127 |
+
|
| 128 |
+
# Actualizar historial con respuesta
|
| 129 |
+
chat_history.append({"role": "assistant", "content": bot_message})
|
| 130 |
+
|
| 131 |
+
return "", chat_history
|
| 132 |
+
|
| 133 |
+
# Event handlers
|
| 134 |
+
submit_btn.click(
|
| 135 |
+
respond,
|
| 136 |
+
inputs=[msg, chatbot],
|
| 137 |
+
outputs=[msg, chatbot]
|
| 138 |
+
)
|
| 139 |
+
|
| 140 |
+
msg.submit(
|
| 141 |
+
respond,
|
| 142 |
+
inputs=[msg, chatbot],
|
| 143 |
+
outputs=[msg, chatbot]
|
| 144 |
+
)
|
| 145 |
+
|
| 146 |
+
clear_btn.click(
|
| 147 |
+
lambda: ([], ""),
|
| 148 |
+
outputs=[chatbot, msg]
|
| 149 |
+
)
|
| 150 |
+
|
| 151 |
+
# Ejemplos de uso
|
| 152 |
+
with gr.Accordion("💡 Ejemplos para probar", open=False):
|
| 153 |
+
gr.Examples(
|
| 154 |
+
examples=[
|
| 155 |
+
"Explícame qué es Batuto_Qwin",
|
| 156 |
+
"Ayúdame a escribir un código Python simple",
|
| 157 |
+
"¿Cuáles son las ventajas de Qwen3-32B?",
|
| 158 |
+
"Háblame sobre inteligencia artificial"
|
| 159 |
+
],
|
| 160 |
+
inputs=msg
|
| 161 |
+
)
|
| 162 |
+
|
| 163 |
+
if __name__ == "__main__":
|
| 164 |
+
demo.launch(
|
| 165 |
+
share=False,
|
| 166 |
+
show_error=True,
|
| 167 |
+
favicon_path="https://em-content.zobj.net/source/microsoft/319/robot_1f916.png"
|
| 168 |
+
)
|