Spaces:
Runtime error
Runtime error
File size: 3,261 Bytes
21f3b0a d16a437 7f2d2c1 53c6ec8 71888c6 97c9616 7f2d2c1 97c9616 7f2d2c1 8938605 71888c6 2b53d7a 7f2d2c1 97c9616 a7bad57 97c9616 4737061 d16a437 4737061 d16a437 2b53d7a 7f2d2c1 2b53d7a d16a437 261d13d 2b53d7a d16a437 1783ef3 d16a437 2b53d7a d16a437 2b53d7a d16a437 261d13d d16a437 7f2d2c1 d16a437 2b53d7a 97c9616 7f2d2c1 3696fad be75cd5 7f2d2c1 21f3b0a 4737061 | 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 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 | import gradio as gr
from transformers import pipeline
import os
# 1. Recogida de los datos del formulario (o de Settings)
bot_name = os.getenv("BOT_NAME", "Asistente corporativo")
bot_description = os.getenv("BOT_DESCRIPTION", "Asistente virtual de atención al cliente.")
system_instructions = os.getenv("SYSTEM_INSTRUCTIONS", "Eres un asistente amable, claro y profesional.")
knowledge_base = os.getenv("KNOWLEDGE_BASE", "No hay información adicional.")
# 2. Unión de las instrucciones y los datos
final_system_prompt = f"""DIRECTRICES DEL ASISTENTE:\n{system_instructions}\n\nCONTEXTO Y BASE DE CONOCIMIENTO DE LA EMPRESA:\n{knowledge_base}"""
# Modelo para seguir instrucciones
pipe = pipeline("text-generation", model="Qwen/Qwen2.5-1.5B-Instruct", device=-1)
def respond(message, history, max_tokens, temperature, top_p):
# Formato a la conversación
messages = [{"role": "system", "content": final_system_prompt}]
# Se estrae estrictamente texto del historial
for turn in history:
if isinstance(turn, dict): # Si Gradio usa el formato moderno (diccionarios)
content = turn.get("content", "")
if isinstance(content, (list, tuple)): content = content[0]
messages.append({"role": turn.get("role", "user"), "content": str(content)})
elif isinstance(turn, (list, tuple)) and len(turn) == 2: # Si Gradio usa el formato clásico (tuplas)
u_msg, b_msg = turn[0], turn[1]
if isinstance(u_msg, (list, tuple)): u_msg = u_msg[0]
if isinstance(b_msg, (list, tuple)): b_msg = b_msg[0]
if u_msg: messages.append({"role": "user", "content": str(u_msg)})
if b_msg: messages.append({"role": "assistant", "content": str(b_msg)})
# Se añade el mensaje actual
current_msg = message
if isinstance(current_msg, dict): current_msg = current_msg.get("text", "")
elif isinstance(current_msg, (list, tuple)): current_msg = current_msg[0]
messages.append({"role": "user", "content": str(current_msg)})
# Se genera la plantilla para el modelo
prompt = pipe.tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
try:
# Se ejecuta el modelo
outputs = pipe(
prompt,
max_new_tokens=max_tokens,
max_length=None,
temperature=temperature,
top_p=top_p,
do_sample=True,
return_full_text=False
)
# Se entrega solo la respuesta limpia
yield outputs[0]["generated_text"]
except Exception as e:
yield f"⚠️ Error interno procesando el texto: {str(e)}"
# 3. Interfaz gráfica
chatbot = gr.ChatInterface(
respond,
title=bot_name,
description=bot_description,
additional_inputs=[
gr.Slider(1, 1024, 512, step=10, label="Max new tokens"),
gr.Slider(0.1, 2.0, 0.7, step=0.1, label="Temperature"),
gr.Slider(0.1, 1.0, 0.95, step=0.05, label="Top-p"),
],
examples=[
["¿Cuáles son vuestros horarios?"],
["¿Qué servicios ofrecéis?"],
["¿Dónde estáis ubicados?"]
],
cache_examples=False,
)
if __name__ == "__main__":
chatbot.launch() |