Pierber commited on
Commit
7d3e027
·
verified ·
1 Parent(s): 30a699f

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +98 -0
app.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import os
3
+ from groq import Groq
4
+ import random
5
+
6
+ # RECUPERO CHIAVI (Gestione Rotazione per alto traffico)
7
+ # Se hai messo solo GROQ_API_KEY, userà quella. Se ne hai messe altre, le ruota.
8
+ keys = [
9
+ os.environ.get("GROQ_API_KEY"),
10
+ os.environ.get("KEY_2"),
11
+ os.environ.get("KEY_3")
12
+ ]
13
+ valid_keys = [k for k in keys if k is not None]
14
+
15
+ def get_client():
16
+ if not valid_keys: return None
17
+ return Groq(api_key=random.choice(valid_keys))
18
+
19
+ # CONFIGURAZIONE SISTEMA PEDAGOGICO
20
+ def respond(strategia_docente, chat_history, user_input):
21
+ client = get_client()
22
+ if not client:
23
+ yield "⚠️ Errore: Nessuna API Key configurata nei Settings dello Space."
24
+ return
25
+
26
+ # Il Prompt che abbiamo appena validato su Colab
27
+ system_prompt = f"""
28
+ Sei Marco, uno studente di 14 anni in un istituto tecnico.
29
+
30
+ IL TUO INTERLOCUTORE:
31
+ È un 'Avatar Docente' che sta seguendo questa strategia pedagogica:
32
+ "{strategia_docente}"
33
+
34
+ LE TUE ISTRUZIONI DI COMPORTAMENTO:
35
+ 1. Reagisci emotivamente alla strategia del docente.
36
+ 2. Se il docente è severo/freddo: Diventa oppositivo, usa sarcasmo o chiuditi ("Boh", "Non mi va").
37
+ 3. Se il docente è empatico/autentico: Mostra una leggera apertura, ma non fidarti subito.
38
+ 4. Usa linguaggio colloquiale ("Raga", "Uffa", "Che ne so").
39
+ 5. Sii breve (max 2 frasi).
40
+ """
41
+
42
+ messages = [{"role": "system", "content": system_prompt}]
43
+
44
+ for val in chat_history:
45
+ if val[0]: messages.append({"role": "user", "content": val[0]})
46
+ if val[1]: messages.append({"role": "assistant", "content": val[1]})
47
+
48
+ messages.append({"role": "user", "content": user_input})
49
+
50
+ try:
51
+ completion = client.chat.completions.create(
52
+ model="llama-3.3-70b-versatile", # Il modello potente che abbiamo testato
53
+ messages=messages,
54
+ temperature=0.7,
55
+ max_tokens=150,
56
+ stream=True
57
+ )
58
+
59
+ response = ""
60
+ for chunk in completion:
61
+ token = chunk.choices[0].delta.content
62
+ if token:
63
+ response += token
64
+ yield response
65
+
66
+ except Exception as e:
67
+ yield f"⚠️ Errore di connessione (Troppo traffico): {str(e)}. Riprova tra 5 secondi."
68
+
69
+ # INTERFACCIA GRAFICA (Per gli studenti)
70
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
71
+ gr.Markdown("# 🏫 Project Janus: Laboratorio di Simulazione")
72
+ gr.Markdown("Testa la tua strategia didattica contro 'Marco', uno studente simulato dall'IA.")
73
+
74
+ with gr.Row():
75
+ strategia = gr.Textbox(label="1. La tua Strategia (Come vuoi che si comporti il tuo Avatar?)",
76
+ placeholder="Es: Sono severo e distaccato... OPPURE... Sono empatico e ascolto...")
77
+
78
+ chatbot = gr.Chatbot(label="Chat con Marco", height=400)
79
+ msg = gr.Textbox(label="2. Cosa dici a Marco?", placeholder="Scrivi qui...")
80
+ clear = gr.Button("Ricomincia")
81
+
82
+ def user(user_message, history):
83
+ return "", history + [[user_message, None]]
84
+
85
+ def bot(strategia, history):
86
+ user_message = history[-1][0]
87
+ bot_message_generator = respond(strategia, history[:-1], user_message)
88
+ history[-1][1] = ""
89
+ for char in bot_message_generator:
90
+ history[-1][1] = char
91
+ yield history
92
+
93
+ msg.submit(user, [msg, chatbot], [msg, chatbot], queue=False).then(
94
+ bot, [strategia, chatbot], chatbot
95
+ )
96
+ clear.click(lambda: None, None, chatbot, queue=False)
97
+
98
+ demo.launch()