Update app.py
Browse files
app.py
CHANGED
|
@@ -2,34 +2,24 @@ import os
|
|
| 2 |
import gradio as gr
|
| 3 |
import requests
|
| 4 |
import pandas as pd
|
| 5 |
-
# from dotenv import load_dotenv
|
| 6 |
|
| 7 |
-
# Carica variabili d'ambiente da .env se presente (per test locali)
|
| 8 |
# load_dotenv()
|
| 9 |
|
| 10 |
-
# Importa il tuo agente
|
| 11 |
try:
|
| 12 |
from agent import GaiaAgent
|
| 13 |
except ImportError as e:
|
| 14 |
print(f"ERRORE: agent.py non trovato o errore nell'importazione di GaiaAgent: {e}")
|
| 15 |
-
|
| 16 |
-
class GaiaAgent: # Fallback BasicAgent se l'import fallisce
|
| 17 |
def __init__(self, model_name="gpt-4o"):
|
| 18 |
print("Fallback BasicAgent inizializzato perché l'import di GaiaAgent è fallito.")
|
| 19 |
self.model_name = model_name
|
| 20 |
def __call__(self, question: str) -> str:
|
| 21 |
return f"Errore: GaiaAgent (modello: {self.model_name}) non caricato. Questa è una risposta di fallback."
|
| 22 |
|
| 23 |
-
|
| 24 |
-
# --- Costanti ---
|
| 25 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 26 |
|
| 27 |
-
|
| 28 |
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 29 |
-
"""
|
| 30 |
-
Recupera tutte le domande, esegue GaiaAgent su di esse, invia tutte le risposte,
|
| 31 |
-
e visualizza i risultati.
|
| 32 |
-
"""
|
| 33 |
space_id = os.getenv("SPACE_ID")
|
| 34 |
|
| 35 |
if profile:
|
|
@@ -39,23 +29,25 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 39 |
print("Utente non loggato.")
|
| 40 |
return "Per favore, effettua il login a Hugging Face con il pulsante.", None
|
| 41 |
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
|
| 49 |
api_url = DEFAULT_API_URL
|
| 50 |
questions_url = f"{api_url}/questions"
|
| 51 |
submit_url = f"{api_url}/submit"
|
| 52 |
|
| 53 |
-
# 1. Istanzia l'Agente
|
| 54 |
try:
|
| 55 |
-
|
| 56 |
-
# "gpt-4.1" potrebbe non essere un identificatore di modello valido.
|
| 57 |
-
# Usa "gpt-4o", "gpt-4-turbo", "gpt-4-0125-preview", o un altro modello a cui hai accesso.
|
| 58 |
-
agent = GaiaAgent(model_name="gpt-4o")
|
| 59 |
except Exception as e:
|
| 60 |
print(f"Errore durante l'istanziazione dell'agente: {e}")
|
| 61 |
return f"Errore durante l'inizializzazione dell'agente: {e}", None
|
|
@@ -63,7 +55,6 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 63 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main" if space_id else "Link al codice non disponibile (SPACE_ID non impostato)"
|
| 64 |
print(f"Link al codice dell'agente: {agent_code}")
|
| 65 |
|
| 66 |
-
# 2. Recupera le Domande
|
| 67 |
print(f"Recupero domande da: {questions_url}")
|
| 68 |
try:
|
| 69 |
response = requests.get(questions_url, timeout=30)
|
|
@@ -84,7 +75,6 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 84 |
print(f"Errore imprevisto durante il recupero delle domande: {e}")
|
| 85 |
return f"Errore imprevisto durante il recupero delle domande: {e}", None
|
| 86 |
|
| 87 |
-
# 3. Esegui il tuo Agente
|
| 88 |
results_log = []
|
| 89 |
answers_payload = []
|
| 90 |
print(f"Esecuzione dell'agente su {len(questions_data)} domande...")
|
|
@@ -103,22 +93,20 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 103 |
except Exception as e:
|
| 104 |
error_message = f"ERRORE AGENTE sul task {task_id}: {e}"
|
| 105 |
print(error_message)
|
| 106 |
-
answers_payload.append({"task_id": task_id, "submitted_answer": error_message})
|
| 107 |
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": error_message})
|
| 108 |
|
| 109 |
if not answers_payload:
|
| 110 |
print("L'agente non ha prodotto alcuna risposta da inviare.")
|
| 111 |
return "L'agente non ha prodotto alcuna risposta da inviare.", pd.DataFrame(results_log if results_log else [])
|
| 112 |
|
| 113 |
-
# 4. Prepara l'Invio
|
| 114 |
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
| 115 |
status_update = f"Agente terminato. Invio di {len(answers_payload)} risposte per l'utente '{username}'..."
|
| 116 |
print(status_update)
|
| 117 |
|
| 118 |
-
# 5. Invia
|
| 119 |
print(f"Invio di {len(answers_payload)} risposte a: {submit_url}")
|
| 120 |
try:
|
| 121 |
-
response = requests.post(submit_url, json=submission_data, timeout=180)
|
| 122 |
response.raise_for_status()
|
| 123 |
result_data = response.json()
|
| 124 |
final_status = (
|
|
@@ -158,36 +146,27 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 158 |
results_df = pd.DataFrame(results_log)
|
| 159 |
return status_message, results_df
|
| 160 |
|
| 161 |
-
|
| 162 |
-
#
|
| 163 |
-
with gr.Blocks(css="footer {visibility: hidden}") as demo: # Nasconde il footer di Gradio se desiderato
|
| 164 |
-
gr.Markdown("# GAIA Level 1 Agent - Evaluation Runner")
|
| 165 |
gr.Markdown(
|
| 166 |
"""
|
| 167 |
**Istruzioni:**
|
| 168 |
|
| 169 |
-
1. Questo Space implementa un `GaiaAgent` che utilizza Wikipedia,
|
| 170 |
-
2. Assicurati che `OPENAI_API_KEY`
|
| 171 |
-
3. Effettua il login al tuo account Hugging Face usando il pulsante qui sotto.
|
| 172 |
-
4. Clicca su 'Esegui Valutazione & Invia Tutte le Risposte' per
|
| 173 |
-
|
| 174 |
-
---
|
| 175 |
-
**Disclaimer:**
|
| 176 |
-
Una volta cliccato il pulsante di invio, il processo può richiedere diverso tempo (l'agente deve elaborare tutte le domande).
|
| 177 |
-
Questo Space fornisce una configurazione di base. Per soluzioni più robuste, considera il caching delle risposte o l'elaborazione asincrona.
|
| 178 |
"""
|
| 179 |
)
|
| 180 |
|
| 181 |
gr.LoginButton()
|
| 182 |
-
|
| 183 |
run_button = gr.Button("Esegui Valutazione & Invia Tutte le Risposte")
|
| 184 |
-
|
| 185 |
status_output = gr.Textbox(label="Stato Esecuzione / Risultato Invio", lines=6, interactive=False)
|
| 186 |
results_table = gr.DataFrame(label="Domande e Risposte dell'Agente", wrap=True, height=400)
|
| 187 |
|
| 188 |
run_button.click(
|
| 189 |
fn=run_and_submit_all,
|
| 190 |
-
inputs=None,
|
| 191 |
outputs=[status_output, results_table],
|
| 192 |
api_name="run_evaluation"
|
| 193 |
)
|
|
@@ -212,9 +191,12 @@ if __name__ == "__main__":
|
|
| 212 |
|
| 213 |
if not os.getenv("OPENAI_API_KEY"):
|
| 214 |
print("\n⚠️ ATTENZIONE: La variabile d'ambiente OPENAI_API_KEY NON È IMPOSTATA.")
|
| 215 |
-
|
|
|
|
|
|
|
|
|
|
| 216 |
|
| 217 |
-
print("-"*(60 + len(" Avvio App ")) + "\n")
|
| 218 |
|
| 219 |
-
print("
|
| 220 |
-
|
|
|
|
|
|
| 2 |
import gradio as gr
|
| 3 |
import requests
|
| 4 |
import pandas as pd
|
| 5 |
+
# from dotenv import load_dotenv
|
| 6 |
|
|
|
|
| 7 |
# load_dotenv()
|
| 8 |
|
|
|
|
| 9 |
try:
|
| 10 |
from agent import GaiaAgent
|
| 11 |
except ImportError as e:
|
| 12 |
print(f"ERRORE: agent.py non trovato o errore nell'importazione di GaiaAgent: {e}")
|
| 13 |
+
class GaiaAgent:
|
|
|
|
| 14 |
def __init__(self, model_name="gpt-4o"):
|
| 15 |
print("Fallback BasicAgent inizializzato perché l'import di GaiaAgent è fallito.")
|
| 16 |
self.model_name = model_name
|
| 17 |
def __call__(self, question: str) -> str:
|
| 18 |
return f"Errore: GaiaAgent (modello: {self.model_name}) non caricato. Questa è una risposta di fallback."
|
| 19 |
|
|
|
|
|
|
|
| 20 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 21 |
|
|
|
|
| 22 |
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
space_id = os.getenv("SPACE_ID")
|
| 24 |
|
| 25 |
if profile:
|
|
|
|
| 29 |
print("Utente non loggato.")
|
| 30 |
return "Per favore, effettua il login a Hugging Face con il pulsante.", None
|
| 31 |
|
| 32 |
+
# Controlli per le API Keys
|
| 33 |
+
openai_key_present = bool(os.getenv("OPENAI_API_KEY"))
|
| 34 |
+
tavily_key_present = bool(os.getenv("TAVILY_API_KEY"))
|
| 35 |
+
|
| 36 |
+
if not openai_key_present:
|
| 37 |
+
warning_message_openai = "ATTENZIONE: Il segreto OPENAI_API_KEY non è impostato in questo Space. L'agente probabilmente fallirà."
|
| 38 |
+
print(warning_message_openai)
|
| 39 |
+
# Potresti voler restituire un errore più severo qui
|
| 40 |
+
if not tavily_key_present:
|
| 41 |
+
warning_message_tavily = "ATTENZIONE: Il segreto TAVILY_API_KEY non è impostato. La ricerca web con Tavily non funzionerà."
|
| 42 |
+
print(warning_message_tavily)
|
| 43 |
+
# Potresti voler restituire un errore più severo qui
|
| 44 |
|
| 45 |
api_url = DEFAULT_API_URL
|
| 46 |
questions_url = f"{api_url}/questions"
|
| 47 |
submit_url = f"{api_url}/submit"
|
| 48 |
|
|
|
|
| 49 |
try:
|
| 50 |
+
agent = GaiaAgent(model_name="gpt-4o") # o "gpt-4-turbo", ecc.
|
|
|
|
|
|
|
|
|
|
| 51 |
except Exception as e:
|
| 52 |
print(f"Errore durante l'istanziazione dell'agente: {e}")
|
| 53 |
return f"Errore durante l'inizializzazione dell'agente: {e}", None
|
|
|
|
| 55 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main" if space_id else "Link al codice non disponibile (SPACE_ID non impostato)"
|
| 56 |
print(f"Link al codice dell'agente: {agent_code}")
|
| 57 |
|
|
|
|
| 58 |
print(f"Recupero domande da: {questions_url}")
|
| 59 |
try:
|
| 60 |
response = requests.get(questions_url, timeout=30)
|
|
|
|
| 75 |
print(f"Errore imprevisto durante il recupero delle domande: {e}")
|
| 76 |
return f"Errore imprevisto durante il recupero delle domande: {e}", None
|
| 77 |
|
|
|
|
| 78 |
results_log = []
|
| 79 |
answers_payload = []
|
| 80 |
print(f"Esecuzione dell'agente su {len(questions_data)} domande...")
|
|
|
|
| 93 |
except Exception as e:
|
| 94 |
error_message = f"ERRORE AGENTE sul task {task_id}: {e}"
|
| 95 |
print(error_message)
|
| 96 |
+
answers_payload.append({"task_id": task_id, "submitted_answer": error_message})
|
| 97 |
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": error_message})
|
| 98 |
|
| 99 |
if not answers_payload:
|
| 100 |
print("L'agente non ha prodotto alcuna risposta da inviare.")
|
| 101 |
return "L'agente non ha prodotto alcuna risposta da inviare.", pd.DataFrame(results_log if results_log else [])
|
| 102 |
|
|
|
|
| 103 |
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
| 104 |
status_update = f"Agente terminato. Invio di {len(answers_payload)} risposte per l'utente '{username}'..."
|
| 105 |
print(status_update)
|
| 106 |
|
|
|
|
| 107 |
print(f"Invio di {len(answers_payload)} risposte a: {submit_url}")
|
| 108 |
try:
|
| 109 |
+
response = requests.post(submit_url, json=submission_data, timeout=180)
|
| 110 |
response.raise_for_status()
|
| 111 |
result_data = response.json()
|
| 112 |
final_status = (
|
|
|
|
| 146 |
results_df = pd.DataFrame(results_log)
|
| 147 |
return status_message, results_df
|
| 148 |
|
| 149 |
+
with gr.Blocks(css="footer {visibility: hidden}") as demo:
|
| 150 |
+
gr.Markdown("# GAIA Level 1 Agent (con Tavily) - Evaluation Runner")
|
|
|
|
|
|
|
| 151 |
gr.Markdown(
|
| 152 |
"""
|
| 153 |
**Istruzioni:**
|
| 154 |
|
| 155 |
+
1. Questo Space implementa un `GaiaAgent` che utilizza Wikipedia, **Tavily Search**, Arxiv e un interprete di codice Python.
|
| 156 |
+
2. Assicurati che `OPENAI_API_KEY` e `TAVILY_API_KEY` siano impostate come **Secrets** nelle impostazioni del tuo Hugging Face Space.
|
| 157 |
+
3. Effettua il login al tuo account Hugging Face usando il pulsante qui sotto.
|
| 158 |
+
4. Clicca su 'Esegui Valutazione & Invia Tutte le Risposte' per avviare il processo.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 159 |
"""
|
| 160 |
)
|
| 161 |
|
| 162 |
gr.LoginButton()
|
|
|
|
| 163 |
run_button = gr.Button("Esegui Valutazione & Invia Tutte le Risposte")
|
|
|
|
| 164 |
status_output = gr.Textbox(label="Stato Esecuzione / Risultato Invio", lines=6, interactive=False)
|
| 165 |
results_table = gr.DataFrame(label="Domande e Risposte dell'Agente", wrap=True, height=400)
|
| 166 |
|
| 167 |
run_button.click(
|
| 168 |
fn=run_and_submit_all,
|
| 169 |
+
inputs=None,
|
| 170 |
outputs=[status_output, results_table],
|
| 171 |
api_name="run_evaluation"
|
| 172 |
)
|
|
|
|
| 191 |
|
| 192 |
if not os.getenv("OPENAI_API_KEY"):
|
| 193 |
print("\n⚠️ ATTENZIONE: La variabile d'ambiente OPENAI_API_KEY NON È IMPOSTATA.")
|
| 194 |
+
if not os.getenv("TAVILY_API_KEY"):
|
| 195 |
+
print("\n⚠️ ATTENZIONE: La variabile d'ambiente TAVILY_API_KEY NON È IMPOSTATA.")
|
| 196 |
+
if not os.getenv("OPENAI_API_KEY") or not os.getenv("TAVILY_API_KEY"):
|
| 197 |
+
print("Per favore, imposta le API keys mancanti come Secrets nelle impostazioni del tuo Hugging Face Space o nel tuo ambiente locale.\n")
|
| 198 |
|
|
|
|
| 199 |
|
| 200 |
+
print("-"*(60 + len(" Avvio App ")) + "\n")
|
| 201 |
+
print("Avvio Interfaccia Gradio per Valutazione Agente GAIA (con Tavily)...")
|
| 202 |
+
demo.launch(share=False)
|