File size: 2,604 Bytes
d532e81
 
 
 
ebd1f5e
 
 
d532e81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ebd1f5e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d532e81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import gradio as gr
from huggingface_hub import InferenceClient

# Modelo abierto alojado en Hugging Face
# (si este diera problemas luego podemos cambiarlo por otro)
MODEL_ID = "HuggingFaceH4/zephyr-7b-beta"

HF_TOKEN = os.environ.get("HF_TOKEN")
if HF_TOKEN is None:
    raise ValueError(
        "No se encontró el token HF_TOKEN. "
        "Ve a Settings → Variables and secrets y añade tu token de Hugging Face."
    )

client = InferenceClient(MODEL_ID, token=HF_TOKEN)

SYSTEM_PROMPT = """
Eres Amiya, una asistente latinoamericana de educación mediática,
cultura digital y derechos en internet.
Respondes SIEMPRE en español claro, con ejemplos cotidianos.
No usas tecnicismos innecesarios y hablas con calma.
Si una pregunta se sale de tu tema (política partidista, salud específica, etc.),
invitas a buscar ayuda experta.
Si algo no está claro o no tienes información suficiente, lo dices sin inventar.
"""

def amiya_chat(message, history):
    messages = [{"role": "system", "content": SYSTEM_PROMPT}]

    for user_msg, bot_msg in history:
        if user_msg:
            messages.append({"role": "user", "content": user_msg})
        if bot_msg:
            messages.append({"role": "assistant", "content": bot_msg})

    messages.append({"role": "user", "content": message})

    try:
        completion = client.chat_completion(
            messages=messages,
            max_tokens=400,
            temperature=0.4,
        )

        # Soportar tanto respuesta tipo objeto como tipo dict
        choice = completion.choices[0]
        if hasattr(choice, "message"):
            reply = getattr(choice.message, "content", None) or choice.message["content"]
        else:
            reply = choice["message"]["content"]

    except Exception as e:
        # Mostrar el error dentro del chat para poder entender qué pasa
        reply = f"⚠️ Hubo un error al llamar al modelo: {e}"

    history.append((message, reply))
    return "", history

with gr.Blocks() as demo:
    gr.Markdown(
        "# Amiya – menos ruido, más criterio\n"
        "Bot de cultura digital y educación mediática para América Latina y el Caribe."
    )

    chat = gr.Chatbot(label="Chat con Amiya", height=450)
    msg = gr.Textbox(
        label="Escribe tu pregunta",
        placeholder="Pregúntale a Amiya sobre IA, desinformación, algoritmos, bienestar digital…",
    )
    clear = gr.Button("Limpiar conversación")

    msg.submit(amiya_chat, [msg, chat], [msg, chat])
    clear.click(lambda: ("", []), None, [msg, chat])

if __name__ == "__main__":
    demo.launch()