Update app.py
Browse files
app.py
CHANGED
|
@@ -1,185 +1,220 @@
|
|
| 1 |
import os
|
| 2 |
import gradio as gr
|
| 3 |
import requests
|
| 4 |
-
import inspect
|
| 5 |
import pandas as pd
|
| 6 |
-
from
|
| 7 |
-
|
| 8 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 10 |
|
| 11 |
-
|
| 12 |
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 13 |
"""
|
| 14 |
-
|
| 15 |
-
|
| 16 |
"""
|
| 17 |
-
|
| 18 |
-
space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
|
| 19 |
|
| 20 |
if profile:
|
| 21 |
-
username= f"{profile.username}"
|
| 22 |
-
print(f"
|
| 23 |
else:
|
| 24 |
-
print("
|
| 25 |
-
return "
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
|
| 27 |
api_url = DEFAULT_API_URL
|
| 28 |
questions_url = f"{api_url}/questions"
|
| 29 |
submit_url = f"{api_url}/submit"
|
| 30 |
|
| 31 |
-
# 1.
|
| 32 |
try:
|
| 33 |
-
|
|
|
|
|
|
|
|
|
|
| 34 |
except Exception as e:
|
| 35 |
-
print(f"
|
| 36 |
-
return f"
|
| 37 |
-
|
| 38 |
-
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 39 |
-
print(agent_code)
|
| 40 |
-
|
| 41 |
-
# 2.
|
| 42 |
-
print(f"
|
| 43 |
try:
|
| 44 |
-
response = requests.get(questions_url, timeout=
|
| 45 |
response.raise_for_status()
|
| 46 |
questions_data = response.json()
|
| 47 |
if not questions_data:
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
print(f"
|
| 51 |
except requests.exceptions.RequestException as e:
|
| 52 |
-
print(f"
|
| 53 |
-
return f"
|
| 54 |
except requests.exceptions.JSONDecodeError as e:
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
except Exception as e:
|
| 59 |
-
print(f"
|
| 60 |
-
return f"
|
| 61 |
|
| 62 |
-
# 3.
|
| 63 |
results_log = []
|
| 64 |
answers_payload = []
|
| 65 |
-
print(f"
|
| 66 |
-
for item in questions_data:
|
| 67 |
task_id = item.get("task_id")
|
| 68 |
question_text = item.get("question")
|
| 69 |
if not task_id or question_text is None:
|
| 70 |
-
print(f"
|
| 71 |
continue
|
| 72 |
try:
|
|
|
|
| 73 |
submitted_answer = agent(question_text)
|
| 74 |
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
| 75 |
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
|
|
|
| 76 |
except Exception as e:
|
| 77 |
-
|
| 78 |
-
|
|
|
|
|
|
|
| 79 |
|
| 80 |
if not answers_payload:
|
| 81 |
-
print("
|
| 82 |
-
return "
|
| 83 |
|
| 84 |
-
# 4.
|
| 85 |
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
| 86 |
-
status_update = f"
|
| 87 |
print(status_update)
|
| 88 |
|
| 89 |
-
# 5.
|
| 90 |
-
print(f"
|
| 91 |
try:
|
| 92 |
-
response = requests.post(submit_url, json=submission_data, timeout=
|
| 93 |
response.raise_for_status()
|
| 94 |
result_data = response.json()
|
| 95 |
final_status = (
|
| 96 |
-
f"
|
| 97 |
-
f"
|
| 98 |
-
f"
|
| 99 |
-
f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')}
|
| 100 |
-
f"
|
| 101 |
)
|
| 102 |
-
print("
|
| 103 |
results_df = pd.DataFrame(results_log)
|
| 104 |
return final_status, results_df
|
| 105 |
except requests.exceptions.HTTPError as e:
|
| 106 |
-
error_detail = f"
|
| 107 |
try:
|
| 108 |
error_json = e.response.json()
|
| 109 |
-
error_detail += f"
|
| 110 |
except requests.exceptions.JSONDecodeError:
|
| 111 |
-
error_detail += f"
|
| 112 |
-
status_message = f"
|
| 113 |
print(status_message)
|
| 114 |
results_df = pd.DataFrame(results_log)
|
| 115 |
return status_message, results_df
|
| 116 |
except requests.exceptions.Timeout:
|
| 117 |
-
status_message = "
|
| 118 |
print(status_message)
|
| 119 |
results_df = pd.DataFrame(results_log)
|
| 120 |
return status_message, results_df
|
| 121 |
except requests.exceptions.RequestException as e:
|
| 122 |
-
status_message = f"
|
| 123 |
print(status_message)
|
| 124 |
results_df = pd.DataFrame(results_log)
|
| 125 |
return status_message, results_df
|
| 126 |
except Exception as e:
|
| 127 |
-
status_message = f"
|
| 128 |
print(status_message)
|
| 129 |
results_df = pd.DataFrame(results_log)
|
| 130 |
return status_message, results_df
|
| 131 |
|
| 132 |
|
| 133 |
-
# ---
|
| 134 |
-
with gr.Blocks() as demo:
|
| 135 |
-
gr.Markdown("# GAIA
|
| 136 |
gr.Markdown(
|
| 137 |
"""
|
| 138 |
-
**
|
| 139 |
|
| 140 |
-
1.
|
| 141 |
-
2.
|
| 142 |
-
3.
|
|
|
|
| 143 |
|
| 144 |
---
|
| 145 |
-
**
|
| 146 |
-
|
| 147 |
-
|
| 148 |
"""
|
| 149 |
)
|
| 150 |
|
| 151 |
gr.LoginButton()
|
| 152 |
|
| 153 |
-
run_button = gr.Button("
|
| 154 |
|
| 155 |
-
status_output = gr.Textbox(label="
|
| 156 |
-
results_table = gr.DataFrame(label="
|
| 157 |
|
| 158 |
run_button.click(
|
| 159 |
fn=run_and_submit_all,
|
| 160 |
-
|
|
|
|
|
|
|
| 161 |
)
|
| 162 |
|
| 163 |
if __name__ == "__main__":
|
| 164 |
-
print("\n" + "-"*30 + " App
|
| 165 |
-
# Check for SPACE_HOST and SPACE_ID at startup for information
|
| 166 |
space_host_startup = os.getenv("SPACE_HOST")
|
| 167 |
-
space_id_startup = os.getenv("SPACE_ID")
|
| 168 |
|
| 169 |
if space_host_startup:
|
| 170 |
-
print(f"✅ SPACE_HOST
|
| 171 |
-
print(f"
|
| 172 |
else:
|
| 173 |
-
print("ℹ️
|
| 174 |
|
| 175 |
-
if space_id_startup:
|
| 176 |
-
print(f"✅ SPACE_ID
|
| 177 |
-
print(f"
|
| 178 |
-
print(f"
|
| 179 |
else:
|
| 180 |
-
print("ℹ️
|
|
|
|
|
|
|
|
|
|
|
|
|
| 181 |
|
| 182 |
-
print("-"*(60 + len(" App
|
| 183 |
|
| 184 |
-
print("
|
| 185 |
-
demo.launch(debug=True
|
|
|
|
| 1 |
import os
|
| 2 |
import gradio as gr
|
| 3 |
import requests
|
|
|
|
| 4 |
import pandas as pd
|
| 5 |
+
# from dotenv import load_dotenv # Opzionale per test locali
|
| 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 |
+
# Definisci un fallback o gestisci l'errore come preferisci
|
| 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:
|
| 36 |
+
username = f"{profile.username}"
|
| 37 |
+
print(f"Utente loggato: {username}")
|
| 38 |
else:
|
| 39 |
+
print("Utente non loggato.")
|
| 40 |
+
return "Per favore, effettua il login a Hugging Face con il pulsante.", None
|
| 41 |
+
|
| 42 |
+
if not os.getenv("OPENAI_API_KEY"):
|
| 43 |
+
warning_message = "ATTENZIONE: Il segreto OPENAI_API_KEY non è impostato in questo Space. L'agente probabilmente fallirà."
|
| 44 |
+
print(warning_message)
|
| 45 |
+
# Potresti voler restituire un errore qui o lasciare che l'agente lo gestisca
|
| 46 |
+
# return warning_message, pd.DataFrame([{"Task ID": "N/A", "Question": "Configurazione mancante", "Submitted Answer": warning_message}])
|
| 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 |
+
# Qui istanzi il tuo GaiaAgent. Puoi cambiare model_name se necessario.
|
| 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
|
| 62 |
+
|
| 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)
|
| 70 |
response.raise_for_status()
|
| 71 |
questions_data = response.json()
|
| 72 |
if not questions_data:
|
| 73 |
+
print("La lista delle domande recuperate è vuota.")
|
| 74 |
+
return "La lista delle domande recuperate è vuota o in formato non valido.", None
|
| 75 |
+
print(f"Recuperate {len(questions_data)} domande.")
|
| 76 |
except requests.exceptions.RequestException as e:
|
| 77 |
+
print(f"Errore durante il recupero delle domande: {e}")
|
| 78 |
+
return f"Errore durante il recupero delle domande: {e}", None
|
| 79 |
except requests.exceptions.JSONDecodeError as e:
|
| 80 |
+
print(f"Errore nella decodifica della risposta JSON dall'endpoint delle domande: {e}")
|
| 81 |
+
print(f"Testo della risposta (primi 500 caratteri): {response.text[:500]}")
|
| 82 |
+
return f"Errore nella decodifica della risposta del server per le domande: {e}", None
|
| 83 |
except Exception as e:
|
| 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...")
|
| 91 |
+
for i, item in enumerate(questions_data):
|
| 92 |
task_id = item.get("task_id")
|
| 93 |
question_text = item.get("question")
|
| 94 |
if not task_id or question_text is None:
|
| 95 |
+
print(f"Salto l'elemento con task_id o domanda mancante: {item}")
|
| 96 |
continue
|
| 97 |
try:
|
| 98 |
+
print(f"\nElaborazione Domanda {i+1}/{len(questions_data)} - Task ID: {task_id}, Domanda: {question_text[:100]}...")
|
| 99 |
submitted_answer = agent(question_text)
|
| 100 |
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
| 101 |
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
| 102 |
+
print(f"Task ID: {task_id} - Risposta (primi 100 caratteri): {str(submitted_answer)[:100]}")
|
| 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}) # Invia l'errore come risposta
|
| 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) # Timeout aumentato
|
| 122 |
response.raise_for_status()
|
| 123 |
result_data = response.json()
|
| 124 |
final_status = (
|
| 125 |
+
f"Invio Riuscito!\n"
|
| 126 |
+
f"Utente: {result_data.get('username')}\n"
|
| 127 |
+
f"Punteggio Complessivo: {result_data.get('score', 'N/A')}% "
|
| 128 |
+
f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} corrette)\n"
|
| 129 |
+
f"Messaggio: {result_data.get('message', 'Nessun messaggio ricevuto.')}"
|
| 130 |
)
|
| 131 |
+
print("Invio riuscito.")
|
| 132 |
results_df = pd.DataFrame(results_log)
|
| 133 |
return final_status, results_df
|
| 134 |
except requests.exceptions.HTTPError as e:
|
| 135 |
+
error_detail = f"Il server ha risposto con stato {e.response.status_code}."
|
| 136 |
try:
|
| 137 |
error_json = e.response.json()
|
| 138 |
+
error_detail += f" Dettaglio: {error_json.get('detail', e.response.text)}"
|
| 139 |
except requests.exceptions.JSONDecodeError:
|
| 140 |
+
error_detail += f" Risposta: {e.response.text[:500]}"
|
| 141 |
+
status_message = f"Invio Fallito: {error_detail}"
|
| 142 |
print(status_message)
|
| 143 |
results_df = pd.DataFrame(results_log)
|
| 144 |
return status_message, results_df
|
| 145 |
except requests.exceptions.Timeout:
|
| 146 |
+
status_message = "Invio Fallito: La richiesta è scaduta (timeout)."
|
| 147 |
print(status_message)
|
| 148 |
results_df = pd.DataFrame(results_log)
|
| 149 |
return status_message, results_df
|
| 150 |
except requests.exceptions.RequestException as e:
|
| 151 |
+
status_message = f"Invio Fallito: Errore di rete - {e}"
|
| 152 |
print(status_message)
|
| 153 |
results_df = pd.DataFrame(results_log)
|
| 154 |
return status_message, results_df
|
| 155 |
except Exception as e:
|
| 156 |
+
status_message = f"Errore imprevisto durante l'invio: {e}"
|
| 157 |
print(status_message)
|
| 158 |
results_df = pd.DataFrame(results_log)
|
| 159 |
return status_message, results_df
|
| 160 |
|
| 161 |
|
| 162 |
+
# --- Costruisci l'Interfaccia Gradio usando Blocks ---
|
| 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, DuckDuckGo, Arxiv e un interprete di codice Python.
|
| 170 |
+
2. Assicurati che `OPENAI_API_KEY` sia impostata come **Secret** nelle impostazioni del tuo Hugging Face Space.
|
| 171 |
+
3. Effettua il login al tuo account Hugging Face usando il pulsante qui sotto. Il tuo username HF verrà usato per l'invio.
|
| 172 |
+
4. Clicca su 'Esegui Valutazione & Invia Tutte le Risposte' per recuperare le domande, eseguire il tuo agente, inviare le risposte e vedere il punteggio.
|
| 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, # Gradio passa implicitamente il profilo OAuth se la funzione lo accetta
|
| 191 |
+
outputs=[status_output, results_table],
|
| 192 |
+
api_name="run_evaluation"
|
| 193 |
)
|
| 194 |
|
| 195 |
if __name__ == "__main__":
|
| 196 |
+
print("\n" + "-"*30 + " Avvio App " + "-"*30)
|
|
|
|
| 197 |
space_host_startup = os.getenv("SPACE_HOST")
|
| 198 |
+
space_id_startup = os.getenv("SPACE_ID")
|
| 199 |
|
| 200 |
if space_host_startup:
|
| 201 |
+
print(f"✅ SPACE_HOST trovato: {space_host_startup}")
|
| 202 |
+
print(f" L'URL di runtime dovrebbe essere: https://{space_host_startup}.hf.space")
|
| 203 |
else:
|
| 204 |
+
print("ℹ️ Variabile d'ambiente SPACE_HOST non trovata (esecuzione locale?).")
|
| 205 |
|
| 206 |
+
if space_id_startup:
|
| 207 |
+
print(f"✅ SPACE_ID trovato: {space_id_startup}")
|
| 208 |
+
print(f" URL del Repo: https://huggingface.co/spaces/{space_id_startup}")
|
| 209 |
+
print(f" URL dell'albero del Repo: https://huggingface.co/spaces/{space_id_startup}/tree/main")
|
| 210 |
else:
|
| 211 |
+
print("ℹ️ Variabile d'ambiente SPACE_ID non trovata (esecuzione locale?). L'URL del Repo non può essere determinato.")
|
| 212 |
+
|
| 213 |
+
if not os.getenv("OPENAI_API_KEY"):
|
| 214 |
+
print("\n⚠️ ATTENZIONE: La variabile d'ambiente OPENAI_API_KEY NON È IMPOSTATA.")
|
| 215 |
+
print("Per favore, impostala come Secret nelle impostazioni del tuo Hugging Face Space se stai deployando lì, o nel tuo ambiente locale.\n")
|
| 216 |
|
| 217 |
+
print("-"*(60 + len(" Avvio App ")) + "\n")
|
| 218 |
|
| 219 |
+
print("Avvio Interfaccia Gradio per Valutazione Agente GAIA...")
|
| 220 |
+
demo.launch(share=False) # debug=True può essere utile per lo sviluppo locale
|