File size: 2,703 Bytes
7d3e027 fe8fef8 7d3e027 fe8fef8 4cf07ec fe8fef8 6dbc00a 7b7da2a fe8fef8 4da3a9c 4cf07ec fe8fef8 4cf07ec fe8fef8 4da3a9c fe8fef8 a50c2fb fe8fef8 4cf07ec fe8fef8 4cf07ec 7d3e027 7b7da2a | 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 gradio as gr
import requests
import json
# --- CONFIGURAZIONE ---
API_KEY = "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"
URL = "https://api.groq.com/openai/v1/chat/completions"
def rispondi_a_marco(messaggio, storia):
# 1. Prompt
system_prompt = """
SEI MARCO, 14 ANNI.
Sei uno studente svogliato, ribelle e sarcastico.
Odi la scuola. Rispondi male ai professori.
Usa slang ("Boh", "Che ansia", "Raga", "Cringe").
Rispondi in massimo 2 frasi.
"""
# Inizializziamo i messaggi con il sistema
messages = [{"role": "system", "content": system_prompt}]
# --- BLOCCO DI SICUREZZA MEMORIA ---
# Questo ciclo 'try-except' impedisce il crash se la storia è formattata male
try:
for turno in storia:
# Controllo rigoroso: accettiamo solo se sono stringhe valide
if isinstance(turno, (list, tuple)) and len(turno) == 2:
user_msg = str(turno[0]) if turno[0] is not None else ""
bot_msg = str(turno[1]) if turno[1] is not None else ""
if user_msg and bot_msg:
messages.append({"role": "user", "content": user_msg})
messages.append({"role": "assistant", "content": bot_msg})
except Exception as e:
# Se c'è un errore nella memoria, lo stampiamo ma NON FERMIAMO IL PROGRAMMA
print(f"Errore lettura memoria: {e}")
# Continuiamo senza memoria vecchia, meglio smemorato che morto.
# Aggiungiamo il messaggio nuovo
messages.append({"role": "user", "content": str(messaggio)})
# 2. Configurazione Dati (Payload)
payload = {
"model": "llama-3.1-8b-instant", # Modello Veloce
"messages": messages,
"temperature": 0.8,
"max_tokens": 150,
"stream": False # NO STREAMING (per evitare crash socket)
}
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {API_KEY}"
}
# 3. Chiamata Diretta (Blindata)
try:
response = requests.post(URL, headers=headers, json=payload, timeout=20)
if response.status_code == 200:
data = response.json()
return data['choices'][0]['message']['content']
else:
return f"⚠️ ERRORE API ({response.status_code}): {response.text}"
except Exception as e:
return f"⚠️ ERRORE CRITICO: {str(e)}"
# --- INTERFACCIA ---
# Semplice e pulita
demo = gr.ChatInterface(
fn=rispondi_a_marco,
title="Project Janus: Marco (Safe Mode)",
description="Marco (Versione Anti-Crash)"
)
if __name__ == "__main__":
demo.launch() |