ghanemfaouri commited on
Commit
c86d0ef
·
verified ·
1 Parent(s): 674bcd6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +157 -9
app.py CHANGED
@@ -151,19 +151,167 @@ class AdvancedAgent:
151
 
152
  # --- Updated Submission Function ---
153
  def run_and_submit_all(profile: gr.OAuthProfile | None):
154
- # ... [The rest of your existing function remains unchanged] ...
155
- # Only change: use AdvancedAgent instead of BasicAgent
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
156
  try:
157
- agent = AdvancedAgent() # This is the only change in this function
158
  except Exception as e:
159
  print(f"Error instantiating agent: {e}")
160
  return f"Error initializing agent: {e}", None
161
-
162
- # ... rest of the function ...
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
163
 
164
- # --- Gradio Interface (unchanged) ---
 
165
  with gr.Blocks() as demo:
166
- # ... [Your existing Gradio interface code] ...
167
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
168
  if __name__ == "__main__":
169
- # ... [Your existing main block] ...
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
151
 
152
  # --- Updated Submission Function ---
153
  def run_and_submit_all(profile: gr.OAuthProfile | None):
154
+ """
155
+ Fetches all questions, runs the AdvancedAgent on them, submits all answers,
156
+ and displays the results.
157
+ """
158
+ # --- Determine HF Space Runtime URL and Repo URL ---
159
+ space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
160
+
161
+ if profile:
162
+ username= f"{profile.username}"
163
+ print(f"User logged in: {username}")
164
+ else:
165
+ print("User not logged in.")
166
+ return "Please Login to Hugging Face with the button.", None
167
+
168
+ api_url = DEFAULT_API_URL
169
+ questions_url = f"{api_url}/questions"
170
+ submit_url = f"{api_url}/submit"
171
+
172
+ # 1. Instantiate Agent
173
  try:
174
+ agent = AdvancedAgent()
175
  except Exception as e:
176
  print(f"Error instantiating agent: {e}")
177
  return f"Error initializing agent: {e}", None
178
+ # In the case of an app running as a hugging Face space, this link points toward your codebase ( usefull for others so please keep it public)
179
+ agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
180
+ print(agent_code)
181
+
182
+ # 2. Fetch Questions
183
+ print(f"Fetching questions from: {questions_url}")
184
+ try:
185
+ response = requests.get(questions_url, timeout=15)
186
+ response.raise_for_status()
187
+ questions_data = response.json()
188
+ if not questions_data:
189
+ print("Fetched questions list is empty.")
190
+ return "Fetched questions list is empty or invalid format.", None
191
+ print(f"Fetched {len(questions_data)} questions.")
192
+ except requests.exceptions.RequestException as e:
193
+ print(f"Error fetching questions: {e}")
194
+ return f"Error fetching questions: {e}", None
195
+ except requests.exceptions.JSONDecodeError as e:
196
+ print(f"Error decoding JSON response from questions endpoint: {e}")
197
+ print(f"Response text: {response.text[:500]}")
198
+ return f"Error decoding server response for questions: {e}", None
199
+ except Exception as e:
200
+ print(f"An unexpected error occurred fetching questions: {e}")
201
+ return f"An unexpected error occurred fetching questions: {e}", None
202
+
203
+ # 3. Run your Agent
204
+ results_log = []
205
+ answers_payload = []
206
+ print(f"Running agent on {len(questions_data)} questions...")
207
+ for item in questions_data:
208
+ task_id = item.get("task_id")
209
+ question_text = item.get("question")
210
+ if not task_id or question_text is None:
211
+ print(f"Skipping item with missing task_id or question: {item}")
212
+ continue
213
+ try:
214
+ submitted_answer = agent(question_text)
215
+ answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
216
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
217
+ except Exception as e:
218
+ print(f"Error running agent on task {task_id}: {e}")
219
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
220
+
221
+ if not answers_payload:
222
+ print("Agent did not produce any answers to submit.")
223
+ return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
224
+
225
+ # 4. Prepare Submission
226
+ submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
227
+ status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
228
+ print(status_update)
229
+
230
+ # 5. Submit
231
+ print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
232
+ try:
233
+ response = requests.post(submit_url, json=submission_data, timeout=60)
234
+ response.raise_for_status()
235
+ result_data = response.json()
236
+ final_status = (
237
+ f"Submission Successful!\n"
238
+ f"User: {result_data.get('username')}\n"
239
+ f"Overall Score: {result_data.get('score', 'N/A')}% "
240
+ f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
241
+ f"Message: {result_data.get('message', 'No message received.')}"
242
+ )
243
+ print("Submission successful.")
244
+ results_df = pd.DataFrame(results_log)
245
+ return final_status, results_df
246
+ except requests.exceptions.HTTPError as e:
247
+ error_detail = f"Server responded with status {e.response.status_code}."
248
+ try:
249
+ error_json = e.response.json()
250
+ error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
251
+ except requests.exceptions.JSONDecodeError:
252
+ error_detail += f" Response: {e.response.text[:500]}"
253
+ status_message = f"Submission Failed: {error_detail}"
254
+ print(status_message)
255
+ results_df = pd.DataFrame(results_log)
256
+ return status_message, results_df
257
+ except requests.exceptions.Timeout:
258
+ status_message = "Submission Failed: The request timed out."
259
+ print(status_message)
260
+ results_df = pd.DataFrame(results_log)
261
+ return status_message, results_df
262
+ except requests.exceptions.RequestException as e:
263
+ status_message = f"Submission Failed: Network error - {e}"
264
+ print(status_message)
265
+ results_df = pd.DataFrame(results_log)
266
+ return status_message, results_df
267
+ except Exception as e:
268
+ status_message = f"An unexpected error occurred during submission: {e}"
269
+ print(status_message)
270
+ results_df = pd.DataFrame(results_log)
271
+ return status_message, results_df
272
 
273
+
274
+ # --- Build Gradio Interface using Blocks ---
275
  with gr.Blocks() as demo:
276
+ gr.Markdown("# GAIA Benchmark Agent")
277
+ gr.Markdown(
278
+ "This agent is optimized for the GAIA benchmark. Log in with your Hugging Face account, "
279
+ "then click 'Run Evaluation & Submit All Answers' to test against 20 questions."
280
+ )
281
+
282
+ gr.LoginButton()
283
+
284
+ run_button = gr.Button("Run Evaluation & Submit All Answers")
285
+
286
+ status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
287
+ results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
288
+
289
+ run_button.click(
290
+ fn=run_and_submit_all,
291
+ outputs=[status_output, results_table]
292
+ )
293
+
294
+
295
  if __name__ == "__main__":
296
+ print("\n" + "-"*30 + " GAIA Agent Starting " + "-"*30)
297
+ # Check for SPACE_HOST and SPACE_ID at startup for information
298
+ space_host_startup = os.getenv("SPACE_HOST")
299
+ space_id_startup = os.getenv("SPACE_ID")
300
+
301
+ if space_host_startup:
302
+ print(f"✅ SPACE_HOST found: {space_host_startup}")
303
+ print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
304
+ else:
305
+ print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
306
+
307
+ if space_id_startup:
308
+ print(f"✅ SPACE_ID found: {space_id_startup}")
309
+ print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
310
+ print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
311
+ else:
312
+ print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
313
+
314
+ print("-"*(60 + len(" GAIA Agent Starting ")) + "\n")
315
+
316
+ print("Launching Gradio Interface for GAIA Benchmark Agent...")
317
+ demo.launch(debug=True, share=False)