|
|
import os |
|
|
import gradio as gr |
|
|
import requests |
|
|
import pandas as pd |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
try: |
|
|
from agent import GaiaAgent |
|
|
except ImportError as e: |
|
|
print(f"ERRORE: agent.py non trovato o errore nell'importazione di GaiaAgent: {e}") |
|
|
class GaiaAgent: |
|
|
def __init__(self, model_name="o4-mini"): |
|
|
print("Fallback BasicAgent inizializzato perché l'import di GaiaAgent è fallito.") |
|
|
self.model_name = model_name |
|
|
def __call__(self, question: str) -> str: |
|
|
return f"Errore: GaiaAgent (modello: {self.model_name}) non caricato. Questa è una risposta di fallback." |
|
|
|
|
|
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space" |
|
|
|
|
|
def run_and_submit_all(profile: gr.OAuthProfile | None): |
|
|
space_id = os.getenv("SPACE_ID") |
|
|
|
|
|
if profile: |
|
|
username = f"{profile.username}" |
|
|
print(f"Utente loggato: {username}") |
|
|
else: |
|
|
print("Utente non loggato.") |
|
|
return "Per favore, effettua il login a Hugging Face con il pulsante.", None |
|
|
|
|
|
|
|
|
openai_key_present = bool(os.getenv("OPENAI_API_KEY")) |
|
|
tavily_key_present = bool(os.getenv("TAVILY_API_KEY")) |
|
|
|
|
|
if not openai_key_present: |
|
|
warning_message_openai = "ATTENZIONE: Il segreto OPENAI_API_KEY non è impostato in questo Space. L'agente probabilmente fallirà." |
|
|
print(warning_message_openai) |
|
|
|
|
|
if not tavily_key_present: |
|
|
warning_message_tavily = "ATTENZIONE: Il segreto TAVILY_API_KEY non è impostato. La ricerca web con Tavily non funzionerà." |
|
|
print(warning_message_tavily) |
|
|
|
|
|
|
|
|
api_url = DEFAULT_API_URL |
|
|
questions_url = f"{api_url}/questions" |
|
|
submit_url = f"{api_url}/submit" |
|
|
|
|
|
try: |
|
|
agent = GaiaAgent(model_name="o4-mini") |
|
|
except Exception as e: |
|
|
print(f"Errore durante l'istanziazione dell'agente: {e}") |
|
|
return f"Errore durante l'inizializzazione dell'agente: {e}", None |
|
|
|
|
|
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main" if space_id else "Link al codice non disponibile (SPACE_ID non impostato)" |
|
|
print(f"Link al codice dell'agente: {agent_code}") |
|
|
|
|
|
print(f"Recupero domande da: {questions_url}") |
|
|
try: |
|
|
response = requests.get(questions_url, timeout=30) |
|
|
response.raise_for_status() |
|
|
questions_data = response.json() |
|
|
if not questions_data: |
|
|
print("La lista delle domande recuperate è vuota.") |
|
|
return "La lista delle domande recuperate è vuota o in formato non valido.", None |
|
|
print(f"Recuperate {len(questions_data)} domande.") |
|
|
except requests.exceptions.RequestException as e: |
|
|
print(f"Errore durante il recupero delle domande: {e}") |
|
|
return f"Errore durante il recupero delle domande: {e}", None |
|
|
except requests.exceptions.JSONDecodeError as e: |
|
|
print(f"Errore nella decodifica della risposta JSON dall'endpoint delle domande: {e}") |
|
|
print(f"Testo della risposta (primi 500 caratteri): {response.text[:500]}") |
|
|
return f"Errore nella decodifica della risposta del server per le domande: {e}", None |
|
|
except Exception as e: |
|
|
print(f"Errore imprevisto durante il recupero delle domande: {e}") |
|
|
return f"Errore imprevisto durante il recupero delle domande: {e}", None |
|
|
|
|
|
results_log = [] |
|
|
answers_payload = [] |
|
|
print(f"Esecuzione dell'agente su {len(questions_data)} domande...") |
|
|
for i, item in enumerate(questions_data): |
|
|
task_id = item.get("task_id") |
|
|
question_text = item.get("question") |
|
|
if not task_id or question_text is None: |
|
|
print(f"Salto l'elemento con task_id o domanda mancante: {item}") |
|
|
continue |
|
|
try: |
|
|
print(f"\nElaborazione Domanda {i+1}/{len(questions_data)} - Task ID: {task_id}, Domanda: {question_text[:100]}...") |
|
|
submitted_answer = agent(question_text) |
|
|
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer}) |
|
|
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer}) |
|
|
print(f"Task ID: {task_id} - Risposta (primi 100 caratteri): {str(submitted_answer)[:100]}") |
|
|
except Exception as e: |
|
|
error_message = f"ERRORE AGENTE sul task {task_id}: {e}" |
|
|
print(error_message) |
|
|
answers_payload.append({"task_id": task_id, "submitted_answer": error_message}) |
|
|
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": error_message}) |
|
|
|
|
|
if not answers_payload: |
|
|
print("L'agente non ha prodotto alcuna risposta da inviare.") |
|
|
return "L'agente non ha prodotto alcuna risposta da inviare.", pd.DataFrame(results_log if results_log else []) |
|
|
|
|
|
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload} |
|
|
status_update = f"Agente terminato. Invio di {len(answers_payload)} risposte per l'utente '{username}'..." |
|
|
print(status_update) |
|
|
|
|
|
print(f"Invio di {len(answers_payload)} risposte a: {submit_url}") |
|
|
try: |
|
|
response = requests.post(submit_url, json=submission_data, timeout=180) |
|
|
response.raise_for_status() |
|
|
result_data = response.json() |
|
|
final_status = ( |
|
|
f"Invio Riuscito!\n" |
|
|
f"Utente: {result_data.get('username')}\n" |
|
|
f"Punteggio Complessivo: {result_data.get('score', 'N/A')}% " |
|
|
f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} corrette)\n" |
|
|
f"Messaggio: {result_data.get('message', 'Nessun messaggio ricevuto.')}" |
|
|
) |
|
|
print("Invio riuscito.") |
|
|
results_df = pd.DataFrame(results_log) |
|
|
return final_status, results_df |
|
|
except requests.exceptions.HTTPError as e: |
|
|
error_detail = f"Il server ha risposto con stato {e.response.status_code}." |
|
|
try: |
|
|
error_json = e.response.json() |
|
|
error_detail += f" Dettaglio: {error_json.get('detail', e.response.text)}" |
|
|
except requests.exceptions.JSONDecodeError: |
|
|
error_detail += f" Risposta: {e.response.text[:500]}" |
|
|
status_message = f"Invio Fallito: {error_detail}" |
|
|
print(status_message) |
|
|
results_df = pd.DataFrame(results_log) |
|
|
return status_message, results_df |
|
|
except requests.exceptions.Timeout: |
|
|
status_message = "Invio Fallito: La richiesta è scaduta (timeout)." |
|
|
print(status_message) |
|
|
results_df = pd.DataFrame(results_log) |
|
|
return status_message, results_df |
|
|
except requests.exceptions.RequestException as e: |
|
|
status_message = f"Invio Fallito: Errore di rete - {e}" |
|
|
print(status_message) |
|
|
results_df = pd.DataFrame(results_log) |
|
|
return status_message, results_df |
|
|
except Exception as e: |
|
|
status_message = f"Errore imprevisto durante l'invio: {e}" |
|
|
print(status_message) |
|
|
results_df = pd.DataFrame(results_log) |
|
|
return status_message, results_df |
|
|
|
|
|
with gr.Blocks(css="footer {visibility: hidden}") as demo: |
|
|
gr.Markdown("# GAIA Level 1 Agent (con Tavily) - Evaluation Runner") |
|
|
gr.Markdown( |
|
|
""" |
|
|
**Istruzioni:** |
|
|
|
|
|
1. Questo Space implementa un `GaiaAgent` che utilizza Wikipedia, **Tavily Search**, Arxiv e un interprete di codice Python. |
|
|
2. Assicurati che `OPENAI_API_KEY` e `TAVILY_API_KEY` siano impostate come **Secrets** nelle impostazioni del tuo Hugging Face Space. |
|
|
3. Effettua il login al tuo account Hugging Face usando il pulsante qui sotto. |
|
|
4. Clicca su 'Esegui Valutazione & Invia Tutte le Risposte' per avviare il processo. |
|
|
""" |
|
|
) |
|
|
|
|
|
gr.LoginButton() |
|
|
run_button = gr.Button("Esegui Valutazione & Invia Tutte le Risposte") |
|
|
status_output = gr.Textbox(label="Stato Esecuzione / Risultato Invio", lines=6, interactive=False) |
|
|
results_table = gr.DataFrame(label="Domande e Risposte dell'Agente", wrap=True) |
|
|
|
|
|
run_button.click( |
|
|
fn=run_and_submit_all, |
|
|
inputs=None, |
|
|
outputs=[status_output, results_table], |
|
|
api_name="run_evaluation" |
|
|
) |
|
|
|
|
|
if __name__ == "__main__": |
|
|
print("\n" + "-"*30 + " Avvio App " + "-"*30) |
|
|
space_host_startup = os.getenv("SPACE_HOST") |
|
|
space_id_startup = os.getenv("SPACE_ID") |
|
|
|
|
|
if space_host_startup: |
|
|
print(f"✅ SPACE_HOST trovato: {space_host_startup}") |
|
|
print(f" L'URL di runtime dovrebbe essere: https://{space_host_startup}.hf.space") |
|
|
else: |
|
|
print("ℹ️ Variabile d'ambiente SPACE_HOST non trovata (esecuzione locale?).") |
|
|
|
|
|
if space_id_startup: |
|
|
print(f"✅ SPACE_ID trovato: {space_id_startup}") |
|
|
print(f" URL del Repo: https://huggingface.co/spaces/{space_id_startup}") |
|
|
print(f" URL dell'albero del Repo: https://huggingface.co/spaces/{space_id_startup}/tree/main") |
|
|
else: |
|
|
print("ℹ️ Variabile d'ambiente SPACE_ID non trovata (esecuzione locale?). L'URL del Repo non può essere determinato.") |
|
|
|
|
|
if not os.getenv("OPENAI_API_KEY"): |
|
|
print("\n⚠️ ATTENZIONE: La variabile d'ambiente OPENAI_API_KEY NON È IMPOSTATA.") |
|
|
if not os.getenv("TAVILY_API_KEY"): |
|
|
print("\n⚠️ ATTENZIONE: La variabile d'ambiente TAVILY_API_KEY NON È IMPOSTATA.") |
|
|
if not os.getenv("OPENAI_API_KEY") or not os.getenv("TAVILY_API_KEY"): |
|
|
print("Per favore, imposta le API keys mancanti come Secrets nelle impostazioni del tuo Hugging Face Space o nel tuo ambiente locale.\n") |
|
|
|
|
|
|
|
|
print("-"*(60 + len(" Avvio App ")) + "\n") |
|
|
print("Avvio Interfaccia Gradio per Valutazione Agente GAIA (con Tavily)...") |
|
|
demo.launch(share=False) |