Frazer2810 commited on
Commit
ba4670d
·
verified ·
1 Parent(s): 80710dc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +123 -88
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 agent import GaiaAgent
7
-
8
- # --- Constants ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
10
 
11
- # --- Build Agent ---
12
  def run_and_submit_all(profile: gr.OAuthProfile | None):
13
  """
14
- Fetches all questions, runs the GaiaAgent on them, submits all answers,
15
- and displays the results.
16
  """
17
- # --- Determine HF Space Runtime URL and Repo URL ---
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"User logged in: {username}")
23
  else:
24
- print("User not logged in.")
25
- return "Please Login to Hugging Face with the button.", None
 
 
 
 
 
 
 
26
 
27
  api_url = DEFAULT_API_URL
28
  questions_url = f"{api_url}/questions"
29
  submit_url = f"{api_url}/submit"
30
 
31
- # 1. Instantiate Agent
32
  try:
33
- agent = GaiaAgent()
 
 
 
34
  except Exception as e:
35
- print(f"Error instantiating agent: {e}")
36
- return f"Error initializing agent: {e}", None
37
- # In the case of an app running as a hugging Face space, this link points toward your codebase
38
- agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
39
- print(agent_code)
40
-
41
- # 2. Fetch Questions
42
- print(f"Fetching questions from: {questions_url}")
43
  try:
44
- response = requests.get(questions_url, timeout=15)
45
  response.raise_for_status()
46
  questions_data = response.json()
47
  if not questions_data:
48
- print("Fetched questions list is empty.")
49
- return "Fetched questions list is empty or invalid format.", None
50
- print(f"Fetched {len(questions_data)} questions.")
51
  except requests.exceptions.RequestException as e:
52
- print(f"Error fetching questions: {e}")
53
- return f"Error fetching questions: {e}", None
54
  except requests.exceptions.JSONDecodeError as e:
55
- print(f"Error decoding JSON response from questions endpoint: {e}")
56
- print(f"Response text: {response.text[:500]}")
57
- return f"Error decoding server response for questions: {e}", None
58
  except Exception as e:
59
- print(f"An unexpected error occurred fetching questions: {e}")
60
- return f"An unexpected error occurred fetching questions: {e}", None
61
 
62
- # 3. Run your Agent
63
  results_log = []
64
  answers_payload = []
65
- print(f"Running agent on {len(questions_data)} questions...")
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"Skipping item with missing task_id or question: {item}")
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
- print(f"Error running agent on task {task_id}: {e}")
78
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
 
 
79
 
80
  if not answers_payload:
81
- print("Agent did not produce any answers to submit.")
82
- return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
83
 
84
- # 4. Prepare Submission
85
  submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
86
- status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
87
  print(status_update)
88
 
89
- # 5. Submit
90
- print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
91
  try:
92
- response = requests.post(submit_url, json=submission_data, timeout=60)
93
  response.raise_for_status()
94
  result_data = response.json()
95
  final_status = (
96
- f"Submission Successful!\n"
97
- f"User: {result_data.get('username')}\n"
98
- f"Overall Score: {result_data.get('score', 'N/A')}% "
99
- f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
100
- f"Message: {result_data.get('message', 'No message received.')}"
101
  )
102
- print("Submission successful.")
103
  results_df = pd.DataFrame(results_log)
104
  return final_status, results_df
105
  except requests.exceptions.HTTPError as e:
106
- error_detail = f"Server responded with status {e.response.status_code}."
107
  try:
108
  error_json = e.response.json()
109
- error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
110
  except requests.exceptions.JSONDecodeError:
111
- error_detail += f" Response: {e.response.text[:500]}"
112
- status_message = f"Submission Failed: {error_detail}"
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 = "Submission Failed: The request timed out."
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"Submission Failed: Network error - {e}"
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"An unexpected error occurred during submission: {e}"
128
  print(status_message)
129
  results_df = pd.DataFrame(results_log)
130
  return status_message, results_df
131
 
132
 
133
- # --- Build Gradio Interface using Blocks ---
134
- with gr.Blocks() as demo:
135
- gr.Markdown("# GAIA Test Level 1 Agent Evaluation")
136
  gr.Markdown(
137
  """
138
- **Instructions:**
139
 
140
- 1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
141
- 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
142
- 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
 
143
 
144
  ---
145
- **Disclaimers:**
146
- Once clicking on the "submit button, it can take quite some time ( this is the time for the agent to go through all the questions).
147
- This space provides a basic setup and is intentionally sub-optimal to encourage you to develop your own, more robust solution. For instance for the delay process of the submit button, a solution could be to cache the answers and submit in a seperate action or even to answer the questions in async.
148
  """
149
  )
150
 
151
  gr.LoginButton()
152
 
153
- run_button = gr.Button("Run Evaluation & Submit All Answers")
154
 
155
- status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
156
- results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
157
 
158
  run_button.click(
159
  fn=run_and_submit_all,
160
- outputs=[status_output, results_table]
 
 
161
  )
162
 
163
  if __name__ == "__main__":
164
- print("\n" + "-"*30 + " App Starting " + "-"*30)
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") # Get SPACE_ID at startup
168
 
169
  if space_host_startup:
170
- print(f"✅ SPACE_HOST found: {space_host_startup}")
171
- print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
172
  else:
173
- print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
174
 
175
- if space_id_startup: # Print repo URLs if SPACE_ID is found
176
- print(f"✅ SPACE_ID found: {space_id_startup}")
177
- print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
178
- print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
179
  else:
180
- print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
 
 
 
 
181
 
182
- print("-"*(60 + len(" App Starting ")) + "\n")
183
 
184
- print("Launching Gradio Interface for GAIA Test Level 1 Agent...")
185
- demo.launch(debug=True, share=False)
 
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