Spaces:
Runtime error
Runtime error
Download app.py from evavega20e/Chatbot-Assistant: direct link, hf CLI and curl.
- Browser
- Download file 3.26 kB
-
https://huggingface.co/spaces/evavega20e/Chatbot-Assistant/resolve/main/app.py
- Command line
-
hf download hf://spaces/evavega20e/Chatbot-Assistant/app.py
-
curl -L -o app.py https://huggingface.co/spaces/evavega20e/Chatbot-Assistant/resolve/main/app.py
3.26 kB
| 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() |