Pierber commited on
Commit
216714f
·
verified ·
1 Parent(s): 7d3e027

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +36 -67
app.py CHANGED
@@ -1,97 +1,66 @@
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
 
 
1
  import gradio as gr
2
  import os
3
  from groq import Groq
 
4
 
5
+ # 1. RECUPERO LA CHIAVE DAI SEGRETI
6
+ api_key = os.environ.get("GROQ_API_KEY")
 
 
 
 
 
 
7
 
8
+ # 2. DEFINISCO LA FUNZIONE DI RISPOSTA
 
 
 
 
9
  def respond(strategia_docente, chat_history, user_input):
10
+ # Controllo di sicurezza
11
+ if not api_key:
12
+ yield "⚠️ ERRORE: Non trovo la chiave API. Vai in Settings > Variables and secrets e controlla di aver creato 'GROQ_API_KEY'."
13
  return
14
 
15
+ try:
16
+ # Mi connetto a Groq
17
+ client = Groq(api_key=api_key)
18
+
19
+ # System Prompt
20
+ system_prompt = f"""
21
+ Sei Marco, uno studente di 14 anni.
22
+ Il tuo docente sta usando questa strategia: "{strategia_docente}".
23
+ Reagisci di conseguenza. Sii breve e colloquiale.
24
+ """
 
 
 
 
 
25
 
26
+ # Costruisco la memoria
27
+ messages = [{"role": "system", "content": system_prompt}]
28
+ for val in chat_history:
29
+ if val[0]: messages.append({"role": "user", "content": val[0]})
30
+ if val[1]: messages.append({"role": "assistant", "content": val[1]})
31
+ messages.append({"role": "user", "content": user_input})
 
32
 
33
+ # CHIAMATA AL NUOVO MODELLO (Quello vecchio dava errore!)
34
  completion = client.chat.completions.create(
35
+ model="llama-3.3-70b-versatile", # <--- ECCO LA CORREZIONE
36
  messages=messages,
37
  temperature=0.7,
38
  max_tokens=150,
39
  stream=True
40
  )
41
+
42
  response = ""
43
  for chunk in completion:
44
  token = chunk.choices[0].delta.content
45
  if token:
46
  response += token
47
  yield response
48
+
49
  except Exception as e:
50
+ # Se c'è un errore, lo scriviamo nella chat invece di fare il popup rosso
51
+ yield f"⛔ ERRORE TECNICO: {str(e)}"
52
 
53
+ # 3. INTERFACCIA GRAFICA
54
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
55
+ gr.Markdown("# 🏫 Project Janus: Laboratorio")
 
 
56
  with gr.Row():
57
+ strategia = gr.Textbox(label="Strategia Avatar", value="Sono autoritario")
58
+ chatbot = gr.Chatbot(label="Chat con Marco", height=350)
59
+ msg = gr.Textbox(label="Messaggio", placeholder="Scrivi a Marco...")
60
+ clear = gr.Button("Reset")
 
 
 
 
 
 
 
 
 
 
 
 
 
61
 
62
+ msg.submit(lambda x, y: ("", y + [[x, None]]), [msg, chatbot], [msg, chatbot], queue=False).then(
63
+ respond, [strategia, chatbot], chatbot
64
  )
65
  clear.click(lambda: None, None, chatbot, queue=False)
66