Files changed (1) hide show
  1. app.py +929 -114
app.py CHANGED
@@ -1,196 +1,1011 @@
 
1
  import os
2
  import gradio as gr
3
  import requests
4
- import inspect
5
  import pandas as pd
6
 
7
- # (Keep Constants as is)
8
- # --- Constants ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
10
 
11
- # --- Basic Agent Definition ---
12
- # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
 
 
 
13
  class BasicAgent:
 
14
  def __init__(self):
15
- print("BasicAgent initialized.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
  def __call__(self, question: str) -> str:
17
- print(f"Agent received question (first 50 chars): {question[:50]}...")
18
- fixed_answer = "This is a default answer."
19
- print(f"Agent returning fixed answer: {fixed_answer}")
20
- return fixed_answer
21
 
22
- def run_and_submit_all( profile: gr.OAuthProfile | None):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
  """
24
- Fetches all questions, runs the BasicAgent on them, submits all answers,
 
 
25
  and displays the results.
26
  """
27
- # --- Determine HF Space Runtime URL and Repo URL ---
28
- space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
 
 
29
 
30
  if profile:
31
- username= f"{profile.username}"
32
- print(f"User logged in: {username}")
 
 
 
 
 
33
  else:
34
- print("User not logged in.")
35
- return "Please Login to Hugging Face with the button.", None
 
 
 
 
 
 
 
 
 
 
36
 
37
  api_url = DEFAULT_API_URL
 
38
  questions_url = f"{api_url}/questions"
 
39
  submit_url = f"{api_url}/submit"
40
 
41
- # 1. Instantiate Agent ( modify this part to create your agent)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
  try:
 
43
  agent = BasicAgent()
 
44
  except Exception as e:
45
- print(f"Error instantiating agent: {e}")
46
- return f"Error initializing agent: {e}", None
47
- # 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)
48
- agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
49
- print(agent_code)
50
-
51
- # 2. Fetch Questions
52
- print(f"Fetching questions from: {questions_url}")
 
 
 
 
 
 
 
 
 
 
 
 
53
  try:
54
- response = requests.get(questions_url, timeout=15)
 
 
 
 
 
55
  response.raise_for_status()
 
56
  questions_data = response.json()
 
57
  if not questions_data:
58
- print("Fetched questions list is empty.")
59
- return "Fetched questions list is empty or invalid format.", None
60
- print(f"Fetched {len(questions_data)} questions.")
 
 
 
 
 
 
 
 
 
61
  except requests.exceptions.RequestException as e:
62
- print(f"Error fetching questions: {e}")
63
- return f"Error fetching questions: {e}", None
64
- except requests.exceptions.JSONDecodeError as e:
65
- print(f"Error decoding JSON response from questions endpoint: {e}")
66
- print(f"Response text: {response.text[:500]}")
67
- return f"Error decoding server response for questions: {e}", None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68
  except Exception as e:
69
- print(f"An unexpected error occurred fetching questions: {e}")
70
- return f"An unexpected error occurred fetching questions: {e}", None
71
 
72
- # 3. Run your Agent
 
 
 
 
 
 
 
 
 
 
 
 
 
73
  results_log = []
 
74
  answers_payload = []
75
- print(f"Running agent on {len(questions_data)} questions...")
76
- for item in questions_data:
77
- task_id = item.get("task_id")
78
- question_text = item.get("question")
79
- if not task_id or question_text is None:
80
- print(f"Skipping item with missing task_id or question: {item}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81
  continue
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82
  try:
83
- submitted_answer = agent(question_text)
84
- answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
85
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
  except Exception as e:
87
- print(f"Error running agent on task {task_id}: {e}")
88
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89
 
90
  if not answers_payload:
91
- print("Agent did not produce any answers to submit.")
92
- return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
93
 
94
- # 4. Prepare Submission
95
- submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
96
- status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97
  print(status_update)
98
 
99
- # 5. Submit
100
- print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
 
 
 
 
 
 
 
 
101
  try:
102
- response = requests.post(submit_url, json=submission_data, timeout=60)
 
 
 
 
 
 
103
  response.raise_for_status()
 
104
  result_data = response.json()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
105
  final_status = (
106
- f"Submission Successful!\n"
107
- f"User: {result_data.get('username')}\n"
108
- f"Overall Score: {result_data.get('score', 'N/A')}% "
109
- f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
110
- f"Message: {result_data.get('message', 'No message received.')}"
111
- )
112
- print("Submission successful.")
113
- results_df = pd.DataFrame(results_log)
114
- return final_status, results_df
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
115
  except requests.exceptions.HTTPError as e:
116
- error_detail = f"Server responded with status {e.response.status_code}."
 
 
 
 
 
117
  try:
 
118
  error_json = e.response.json()
119
- error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
120
- except requests.exceptions.JSONDecodeError:
121
- error_detail += f" Response: {e.response.text[:500]}"
122
- status_message = f"Submission Failed: {error_detail}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
123
  print(status_message)
124
- results_df = pd.DataFrame(results_log)
125
- return status_message, results_df
 
 
 
 
 
 
 
 
 
 
126
  except requests.exceptions.Timeout:
127
- status_message = "Submission Failed: The request timed out."
 
 
 
 
 
128
  print(status_message)
129
- results_df = pd.DataFrame(results_log)
130
- return status_message, results_df
 
 
 
 
 
 
 
 
 
 
131
  except requests.exceptions.RequestException as e:
132
- status_message = f"Submission Failed: Network error - {e}"
 
 
 
 
 
133
  print(status_message)
134
- results_df = pd.DataFrame(results_log)
135
- return status_message, results_df
 
 
 
 
 
 
 
 
 
 
136
  except Exception as e:
137
- status_message = f"An unexpected error occurred during submission: {e}"
 
 
 
 
 
138
  print(status_message)
139
- results_df = pd.DataFrame(results_log)
140
- return status_message, results_df
141
 
142
 
143
- # --- Build Gradio Interface using Blocks ---
 
 
 
 
 
 
 
 
 
144
  with gr.Blocks() as demo:
145
- gr.Markdown("# Basic Agent Evaluation Runner")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
146
  gr.Markdown(
147
  """
148
- **Instructions:**
149
 
150
- 1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
151
- 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
152
- 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
 
 
153
 
154
- ---
155
- **Disclaimers:**
156
- 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).
157
- 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.
158
  """
159
  )
160
 
 
 
 
 
 
161
  gr.LoginButton()
162
 
163
- run_button = gr.Button("Run Evaluation & Submit All Answers")
164
 
165
- status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
166
- # Removed max_rows=10 from DataFrame constructor
167
- results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
168
 
169
  run_button.click(
170
  fn=run_and_submit_all,
171
- outputs=[status_output, results_table]
 
 
 
172
  )
173
 
 
 
 
 
 
174
  if __name__ == "__main__":
175
- print("\n" + "-"*30 + " App Starting " + "-"*30)
176
- # Check for SPACE_HOST and SPACE_ID at startup for information
177
- space_host_startup = os.getenv("SPACE_HOST")
178
- space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
179
 
180
  if space_host_startup:
181
- print(f"✅ SPACE_HOST found: {space_host_startup}")
182
- print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
 
 
 
 
 
 
 
 
 
 
 
 
183
  else:
184
- print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
185
 
186
- if space_id_startup: # Print repo URLs if SPACE_ID is found
187
- print(f" SPACE_ID found: {space_id_startup}")
188
- print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
189
- print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
190
  else:
191
- print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
192
 
193
- print("-"*(60 + len(" App Starting ")) + "\n")
 
 
 
 
 
 
 
 
 
 
 
 
194
 
195
- print("Launching Gradio Interface for Basic Agent Evaluation...")
196
- demo.launch(debug=True, share=False)
 
 
 
1
+
2
  import os
3
  import gradio as gr
4
  import requests
 
5
  import pandas as pd
6
 
7
+ from smolagents import (
8
+ CodeAgent,
9
+ InferenceClientModel,
10
+ DuckDuckGoSearchTool,
11
+ VisitWebpageTool,
12
+ WikipediaSearchTool,
13
+ PythonInterpreterTool,
14
+ )
15
+
16
+
17
+ # ============================================================
18
+ # CONSTANTS
19
+ # ============================================================
20
+
21
+ # IMPORTANT:
22
+ # DO NOT CHANGE THIS URL.
23
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
24
 
25
+
26
+ # ============================================================
27
+ # GENERAL PURPOSE GAIA AGENT
28
+ # ============================================================
29
+
30
  class BasicAgent:
31
+
32
  def __init__(self):
33
+
34
+ print("=" * 60)
35
+ print("Initializing General Purpose GAIA Agent...")
36
+ print("=" * 60)
37
+
38
+ # ----------------------------------------------------
39
+ # Hugging Face token
40
+ # ----------------------------------------------------
41
+
42
+ hf_token = os.getenv("HF_TOKEN")
43
+
44
+ if not hf_token:
45
+
46
+ raise RuntimeError(
47
+ "HF_TOKEN is missing.\n"
48
+ "Go to Space Settings -> Secrets and create:\n"
49
+ "Name: HF_TOKEN\n"
50
+ "Value: Your Hugging Face token"
51
+ )
52
+
53
+ # ----------------------------------------------------
54
+ # MODEL
55
+ # ----------------------------------------------------
56
+
57
+ self.model = InferenceClientModel(
58
+ model_id="Qwen/Qwen3-Next-80B-A3B-Thinking",
59
+ token=hf_token,
60
+ temperature=0.1,
61
+ max_tokens=3000,
62
+ )
63
+
64
+ # ----------------------------------------------------
65
+ # WEB SEARCH TOOL
66
+ # ----------------------------------------------------
67
+
68
+ self.search_tool = DuckDuckGoSearchTool(
69
+ max_results=8,
70
+ rate_limit=1.0
71
+ )
72
+
73
+ # ----------------------------------------------------
74
+ # WEBPAGE TOOL
75
+ # ----------------------------------------------------
76
+
77
+ self.webpage_tool = VisitWebpageTool(
78
+ max_output_length=40000
79
+ )
80
+
81
+ # ----------------------------------------------------
82
+ # WIKIPEDIA TOOL
83
+ # ----------------------------------------------------
84
+
85
+ self.wikipedia_tool = WikipediaSearchTool(
86
+ user_agent="StructuralGPT-GAIA-Agent/1.0",
87
+ language="en",
88
+ content_type="text",
89
+ extract_format="WIKI"
90
+ )
91
+
92
+ # ----------------------------------------------------
93
+ # PYTHON / CALCULATION TOOL
94
+ # ----------------------------------------------------
95
+
96
+ self.python_tool = PythonInterpreterTool(
97
+ authorized_imports=[
98
+ "math",
99
+ "statistics",
100
+ "datetime",
101
+ "json",
102
+ "re",
103
+ "decimal"
104
+ ],
105
+ timeout_seconds=30
106
+ )
107
+
108
+ # ----------------------------------------------------
109
+ # SYSTEM INSTRUCTIONS
110
+ # ----------------------------------------------------
111
+
112
+ self.instructions = """
113
+ You are a highly capable general-purpose AI agent designed
114
+ to solve GAIA benchmark questions.
115
+
116
+ Your objective is to provide the CORRECT answer to the
117
+ user's question.
118
+
119
+ IMPORTANT RULES
120
+ ===============
121
+
122
+ 1. READ THE COMPLETE QUESTION CAREFULLY.
123
+
124
+ 2. Determine exactly what the question is asking.
125
+
126
+ 3. Use tools whenever they are useful.
127
+
128
+ 4. Use web search for:
129
+ - current information
130
+ - factual information
131
+ - obscure information
132
+ - information that should be verified
133
+ - people, companies, events, dates, statistics, etc.
134
+
135
+ 5. Use the webpage tool when the question provides a URL
136
+ or when you need the contents of a webpage.
137
+
138
+ 6. Use Wikipedia search when the question specifically
139
+ refers to Wikipedia or historical/general information.
140
+
141
+ 7. Use Python for:
142
+ - arithmetic
143
+ - percentages
144
+ - dates
145
+ - counting
146
+ - comparisons
147
+ - numerical reasoning
148
+ - data processing
149
+
150
+ 8. NEVER guess a numerical answer when you can calculate it.
151
+
152
+ 9. When a question contains several steps:
153
+ solve every required step before giving the answer.
154
+
155
+ 10. Verify important facts whenever possible.
156
+
157
+ 11. Do not invent information.
158
+
159
+ 12. Pay close attention to:
160
+ - exact dates
161
+ - names
162
+ - numbers
163
+ - units
164
+ - percentages
165
+ - spelling
166
+ - requested formats
167
+
168
+ 13. If the question asks:
169
+ "How many?"
170
+ return the number.
171
+
172
+ 14. If it asks:
173
+ "Who?"
174
+ return the person's name.
175
+
176
+ 15. If it asks:
177
+ "When?"
178
+ return the date/year.
179
+
180
+ 16. If it asks for a calculation,
181
+ calculate it using Python.
182
+
183
+ 17. If the question asks for a specific list,
184
+ provide exactly the requested list.
185
+
186
+ 18. If the question contains a URL,
187
+ investigate the URL rather than guessing.
188
+
189
+ 19. Do not include citations unless the question asks for them.
190
+
191
+ 20. Do not say "FINAL ANSWER".
192
+
193
+ 21. Do not write:
194
+ "Here is the answer:"
195
+ "The answer is:"
196
+ or unnecessary explanations.
197
+
198
+ 22. The final response must contain ONLY the answer
199
+ required by the question.
200
+
201
+ 23. The GAIA evaluator uses exact matching, so be precise
202
+ and concise.
203
+
204
+ 24. Think through the problem carefully before producing
205
+ the final response.
206
+
207
+ 25. NEVER intentionally return a generic response.
208
+
209
+ SPECIAL CASES
210
+ =============
211
+
212
+ For calculations:
213
+ - Use Python.
214
+ - Verify the result.
215
+ - Give the exact required number.
216
+
217
+ For web research:
218
+ - Search using precise keywords.
219
+ - Open useful results.
220
+ - Compare information when needed.
221
+
222
+ For Wikipedia questions:
223
+ - Use Wikipedia search.
224
+ - Pay attention to the requested Wikipedia version/date.
225
+
226
+ For questions involving a webpage:
227
+ - Visit the webpage.
228
+ - Extract the relevant information.
229
+ - Answer only what is requested.
230
+
231
+ For civil/structural engineering questions:
232
+ - You may use engineering knowledge.
233
+ - Use Indian Standards when appropriate.
234
+ - Keep the final answer focused on what was requested.
235
+
236
+ FINAL RESPONSE
237
+ ==============
238
+
239
+ Return ONLY the concise answer.
240
+ """
241
+
242
+
243
+ # ----------------------------------------------------
244
+ # CREATE AGENT
245
+ # ----------------------------------------------------
246
+
247
+ self.agent = CodeAgent(
248
+ model=self.model,
249
+
250
+ tools=[
251
+ self.search_tool,
252
+ self.webpage_tool,
253
+ self.wikipedia_tool,
254
+ self.python_tool,
255
+ ],
256
+
257
+ max_steps=12,
258
+
259
+ instructions=self.instructions,
260
+
261
+ add_base_tools=True
262
+ )
263
+
264
+ print("GAIA Agent initialized successfully.")
265
+ print("=" * 60)
266
+
267
+
268
+ # ========================================================
269
+ # AGENT CALL
270
+ # ========================================================
271
+
272
  def __call__(self, question: str) -> str:
 
 
 
 
273
 
274
+ print("\n")
275
+ print("=" * 70)
276
+ print("NEW GAIA QUESTION")
277
+ print("=" * 70)
278
+ print(question)
279
+ print("=" * 70)
280
+
281
+ try:
282
+
283
+ result = self.agent.run(question)
284
+
285
+ answer = str(result).strip()
286
+
287
+ # ------------------------------------------------
288
+ # Remove accidental answer labels
289
+ # ------------------------------------------------
290
+
291
+ unwanted_prefixes = [
292
+ "FINAL ANSWER:",
293
+ "FINAL ANSWER",
294
+ "Answer:",
295
+ "ANSWER:",
296
+ "The answer is:",
297
+ "The answer is"
298
+ ]
299
+
300
+ for prefix in unwanted_prefixes:
301
+
302
+ if answer.lower().startswith(prefix.lower()):
303
+
304
+ answer = answer[len(prefix):].strip()
305
+
306
+ print("\nAGENT ANSWER:")
307
+ print(answer)
308
+ print("=" * 70)
309
+
310
+ return answer
311
+
312
+ except Exception as e:
313
+
314
+ print("\nAGENT ERROR:")
315
+ print(str(e))
316
+ print("=" * 70)
317
+
318
+ return f"Agent execution error: {e}"
319
+
320
+
321
+ # ============================================================
322
+ # RUN AND SUBMIT ALL QUESTIONS
323
+ # ============================================================
324
+
325
+ def run_and_submit_all(profile: gr.OAuthProfile | None):
326
+
327
  """
328
+ Fetches all GAIA questions,
329
+ runs the General Purpose Agent,
330
+ submits all answers,
331
  and displays the results.
332
  """
333
+
334
+ # --------------------------------------------------------
335
+ # 1. CHECK HUGGING FACE LOGIN
336
+ # --------------------------------------------------------
337
 
338
  if profile:
339
+
340
+ username = profile.username
341
+
342
+ print(
343
+ f"User logged in: {username}"
344
+ )
345
+
346
  else:
347
+
348
+ print("User is not logged in.")
349
+
350
+ return (
351
+ "Please Login to Hugging Face with the button.",
352
+ None
353
+ )
354
+
355
+
356
+ # --------------------------------------------------------
357
+ # 2. SCORING API URLS
358
+ # --------------------------------------------------------
359
 
360
  api_url = DEFAULT_API_URL
361
+
362
  questions_url = f"{api_url}/questions"
363
+
364
  submit_url = f"{api_url}/submit"
365
 
366
+
367
+ # --------------------------------------------------------
368
+ # 3. GET SPACE CODE URL
369
+ # --------------------------------------------------------
370
+
371
+ space_id = os.getenv("SPACE_ID")
372
+
373
+ if not space_id:
374
+
375
+ print(
376
+ "WARNING: SPACE_ID was not found."
377
+ )
378
+
379
+ agent_code = "SPACE_ID_NOT_FOUND"
380
+
381
+ else:
382
+
383
+ agent_code = (
384
+ f"https://huggingface.co/spaces/"
385
+ f"{space_id}/tree/main"
386
+ )
387
+
388
+ print(
389
+ f"Agent code URL: {agent_code}"
390
+ )
391
+
392
+
393
+ # --------------------------------------------------------
394
+ # 4. CREATE AGENT
395
+ # --------------------------------------------------------
396
+
397
  try:
398
+
399
  agent = BasicAgent()
400
+
401
  except Exception as e:
402
+
403
+ print(
404
+ f"Error initializing agent: {e}"
405
+ )
406
+
407
+ return (
408
+ f"Error initializing agent: {e}",
409
+ None
410
+ )
411
+
412
+
413
+ # --------------------------------------------------------
414
+ # 5. FETCH QUESTIONS
415
+ # --------------------------------------------------------
416
+
417
+ print("\n")
418
+ print("=" * 70)
419
+ print("FETCHING GAIA QUESTIONS")
420
+ print("=" * 70)
421
+
422
  try:
423
+
424
+ response = requests.get(
425
+ questions_url,
426
+ timeout=30
427
+ )
428
+
429
  response.raise_for_status()
430
+
431
  questions_data = response.json()
432
+
433
  if not questions_data:
434
+
435
+ print("Questions list is empty.")
436
+
437
+ return (
438
+ "Fetched questions list is empty.",
439
+ None
440
+ )
441
+
442
+ print(
443
+ f"Fetched {len(questions_data)} questions."
444
+ )
445
+
446
  except requests.exceptions.RequestException as e:
447
+
448
+ print(
449
+ f"Error fetching questions: {e}"
450
+ )
451
+
452
+ return (
453
+ f"Error fetching questions: {e}",
454
+ None
455
+ )
456
+
457
+ except ValueError as e:
458
+
459
+ print(
460
+ f"Invalid JSON response: {e}"
461
+ )
462
+
463
+ return (
464
+ f"Invalid JSON response: {e}",
465
+ None
466
+ )
467
+
468
  except Exception as e:
 
 
469
 
470
+ print(
471
+ f"Unexpected error fetching questions: {e}"
472
+ )
473
+
474
+ return (
475
+ f"Unexpected error fetching questions: {e}",
476
+ None
477
+ )
478
+
479
+
480
+ # --------------------------------------------------------
481
+ # 6. RUN AGENT ON EVERY QUESTION
482
+ # --------------------------------------------------------
483
+
484
  results_log = []
485
+
486
  answers_payload = []
487
+
488
+ total_questions = len(questions_data)
489
+
490
+ print("\n")
491
+ print("=" * 70)
492
+ print("RUNNING GENERAL PURPOSE AGENT")
493
+ print("=" * 70)
494
+
495
+
496
+ for number, item in enumerate(
497
+ questions_data,
498
+ start=1
499
+ ):
500
+
501
+ task_id = item.get(
502
+ "task_id"
503
+ )
504
+
505
+ question_text = item.get(
506
+ "question"
507
+ )
508
+
509
+ # ----------------------------------------------------
510
+ # Validate question
511
+ # ----------------------------------------------------
512
+
513
+ if not task_id:
514
+
515
+ print(
516
+ f"Skipping question {number}: "
517
+ "missing task_id."
518
+ )
519
+
520
+ continue
521
+
522
+ if question_text is None:
523
+
524
+ print(
525
+ f"Skipping question {number}: "
526
+ "missing question text."
527
+ )
528
+
529
  continue
530
+
531
+
532
+ print("\n")
533
+ print(
534
+ f"QUESTION {number}/{total_questions}"
535
+ )
536
+ print(
537
+ f"TASK ID: {task_id}"
538
+ )
539
+
540
+
541
+ # ----------------------------------------------------
542
+ # Run agent
543
+ # ----------------------------------------------------
544
+
545
  try:
546
+
547
+ submitted_answer = agent(
548
+ question_text
549
+ )
550
+
551
+ answers_payload.append(
552
+ {
553
+ "task_id": task_id,
554
+ "submitted_answer": submitted_answer
555
+ }
556
+ )
557
+
558
+ results_log.append(
559
+ {
560
+ "Task ID": task_id,
561
+ "Question": question_text,
562
+ "Submitted Answer":
563
+ submitted_answer
564
+ }
565
+ )
566
+
567
  except Exception as e:
568
+
569
+ error_message = (
570
+ f"AGENT ERROR: {e}"
571
+ )
572
+
573
+ print(error_message)
574
+
575
+ results_log.append(
576
+ {
577
+ "Task ID": task_id,
578
+ "Question": question_text,
579
+ "Submitted Answer":
580
+ error_message
581
+ }
582
+ )
583
+
584
+
585
+ # --------------------------------------------------------
586
+ # 7. CHECK ANSWERS
587
+ # --------------------------------------------------------
588
 
589
  if not answers_payload:
 
 
590
 
591
+ print(
592
+ "Agent did not produce any answers."
593
+ )
594
+
595
+ return (
596
+ "Agent did not produce any answers.",
597
+ pd.DataFrame(results_log)
598
+ )
599
+
600
+
601
+ print("\n")
602
+ print("=" * 70)
603
+ print(
604
+ f"Agent produced {len(answers_payload)} "
605
+ f"answers."
606
+ )
607
+ print("=" * 70)
608
+
609
+
610
+ # --------------------------------------------------------
611
+ # 8. PREPARE SUBMISSION
612
+ # --------------------------------------------------------
613
+
614
+ submission_data = {
615
+
616
+ "username":
617
+ username.strip(),
618
+
619
+ "agent_code":
620
+ agent_code,
621
+
622
+ "answers":
623
+ answers_payload
624
+ }
625
+
626
+
627
+ status_update = (
628
+ f"Agent finished.\n"
629
+ f"Submitting {len(answers_payload)} answers "
630
+ f"for user '{username}'..."
631
+ )
632
+
633
  print(status_update)
634
 
635
+
636
+ # --------------------------------------------------------
637
+ # 9. SUBMIT ANSWERS
638
+ # --------------------------------------------------------
639
+
640
+ print("\n")
641
+ print("=" * 70)
642
+ print("SUBMITTING TO GAIA SCORING SERVER")
643
+ print("=" * 70)
644
+
645
  try:
646
+
647
+ response = requests.post(
648
+ submit_url,
649
+ json=submission_data,
650
+ timeout=120
651
+ )
652
+
653
  response.raise_for_status()
654
+
655
  result_data = response.json()
656
+
657
+
658
+ # ----------------------------------------------------
659
+ # SCORE
660
+ # ----------------------------------------------------
661
+
662
+ score = result_data.get(
663
+ "score",
664
+ "N/A"
665
+ )
666
+
667
+ correct_count = result_data.get(
668
+ "correct_count",
669
+ "?"
670
+ )
671
+
672
+ total_attempted = result_data.get(
673
+ "total_attempted",
674
+ "?"
675
+ )
676
+
677
+ message = result_data.get(
678
+ "message",
679
+ "No message received."
680
+ )
681
+
682
+
683
  final_status = (
684
+
685
+ "Submission Successful!\n\n"
686
+
687
+ f"User: "
688
+ f"{result_data.get('username', username)}\n"
689
+
690
+ f"Overall Score: "
691
+ f"{score}%\n"
692
+
693
+ f"Correct: "
694
+ f"{correct_count}/"
695
+ f"{total_attempted}\n\n"
696
+
697
+ f"Message: "
698
+ f"{message}"
699
+ )
700
+
701
+
702
+ print(final_status)
703
+
704
+
705
+ results_df = pd.DataFrame(
706
+ results_log
707
+ )
708
+
709
+
710
+ return (
711
+ final_status,
712
+ results_df
713
+ )
714
+
715
+
716
+ # --------------------------------------------------------
717
+ # HTTP ERROR
718
+ # --------------------------------------------------------
719
+
720
  except requests.exceptions.HTTPError as e:
721
+
722
+ error_detail = (
723
+ f"Server responded with "
724
+ f"status {e.response.status_code}."
725
+ )
726
+
727
  try:
728
+
729
  error_json = e.response.json()
730
+
731
+ error_detail += (
732
+ f" Detail: "
733
+ f"{error_json.get('detail', '')}"
734
+ )
735
+
736
+ except Exception:
737
+
738
+ error_detail += (
739
+ f" Response: "
740
+ f"{e.response.text[:500]}"
741
+ )
742
+
743
+
744
+ status_message = (
745
+ f"Submission Failed: "
746
+ f"{error_detail}"
747
+ )
748
+
749
  print(status_message)
750
+
751
+
752
+ return (
753
+ status_message,
754
+ pd.DataFrame(results_log)
755
+ )
756
+
757
+
758
+ # --------------------------------------------------------
759
+ # TIMEOUT
760
+ # --------------------------------------------------------
761
+
762
  except requests.exceptions.Timeout:
763
+
764
+ status_message = (
765
+ "Submission Failed: "
766
+ "The request timed out."
767
+ )
768
+
769
  print(status_message)
770
+
771
+
772
+ return (
773
+ status_message,
774
+ pd.DataFrame(results_log)
775
+ )
776
+
777
+
778
+ # --------------------------------------------------------
779
+ # NETWORK ERROR
780
+ # --------------------------------------------------------
781
+
782
  except requests.exceptions.RequestException as e:
783
+
784
+ status_message = (
785
+ f"Submission Failed: "
786
+ f"Network error - {e}"
787
+ )
788
+
789
  print(status_message)
790
+
791
+
792
+ return (
793
+ status_message,
794
+ pd.DataFrame(results_log)
795
+ )
796
+
797
+
798
+ # --------------------------------------------------------
799
+ # OTHER ERROR
800
+ # --------------------------------------------------------
801
+
802
  except Exception as e:
803
+
804
+ status_message = (
805
+ f"Unexpected error during submission: "
806
+ f"{e}"
807
+ )
808
+
809
  print(status_message)
 
 
810
 
811
 
812
+ return (
813
+ status_message,
814
+ pd.DataFrame(results_log)
815
+ )
816
+
817
+
818
+ # ============================================================
819
+ # GRADIO INTERFACE
820
+ # ============================================================
821
+
822
  with gr.Blocks() as demo:
823
+
824
+ gr.Markdown(
825
+ """
826
+ # 🤖 General Purpose GAIA Agent
827
+
828
+ This agent uses:
829
+
830
+ - Qwen through Hugging Face
831
+ - Web Search
832
+ - Webpage retrieval
833
+ - Wikipedia
834
+ - Python calculations
835
+ - Multi-step reasoning
836
+
837
+ It is designed for the Hugging Face Agents Course
838
+ Unit 4 GAIA evaluation.
839
+ """
840
+ )
841
+
842
+
843
  gr.Markdown(
844
  """
845
+ ### Instructions
846
 
847
+ 1. Log in to your Hugging Face account.
848
+ 2. Make sure `HF_TOKEN` is configured as a Space Secret.
849
+ 3. Click **Run Evaluation & Submit All Answers**.
850
+ 4. Wait while the agent processes all questions.
851
+ 5. Your score will appear below.
852
 
853
+ **Important:** The evaluation can take several minutes
854
+ because the agent processes each question individually.
 
 
855
  """
856
  )
857
 
858
+
859
+ # --------------------------------------------------------
860
+ # LOGIN
861
+ # --------------------------------------------------------
862
+
863
  gr.LoginButton()
864
 
 
865
 
866
+ # --------------------------------------------------------
867
+ # RUN BUTTON
868
+ # --------------------------------------------------------
869
+
870
+ run_button = gr.Button(
871
+ "Run Evaluation & Submit All Answers",
872
+ variant="primary"
873
+ )
874
+
875
+
876
+ # --------------------------------------------------------
877
+ # STATUS
878
+ # --------------------------------------------------------
879
+
880
+ status_output = gr.Textbox(
881
+ label="Run Status / Submission Result",
882
+ lines=8,
883
+ interactive=False
884
+ )
885
+
886
+
887
+ # --------------------------------------------------------
888
+ # RESULTS
889
+ # --------------------------------------------------------
890
+
891
+ results_table = gr.DataFrame(
892
+ label="Questions and Agent Answers",
893
+ wrap=True
894
+ )
895
+
896
+
897
+ # --------------------------------------------------------
898
+ # BUTTON ACTION
899
+ # --------------------------------------------------------
900
 
901
  run_button.click(
902
  fn=run_and_submit_all,
903
+ outputs=[
904
+ status_output,
905
+ results_table
906
+ ]
907
  )
908
 
909
+
910
+ # ============================================================
911
+ # START APPLICATION
912
+ # ============================================================
913
+
914
  if __name__ == "__main__":
915
+
916
+ print(
917
+ "\n" +
918
+ "-" * 30 +
919
+ " App Starting " +
920
+ "-" * 30
921
+ )
922
+
923
+
924
+ # --------------------------------------------------------
925
+ # SPACE INFORMATION
926
+ # --------------------------------------------------------
927
+
928
+ space_host_startup = os.getenv(
929
+ "SPACE_HOST"
930
+ )
931
+
932
+ space_id_startup = os.getenv(
933
+ "SPACE_ID"
934
+ )
935
+
936
+
937
+ # --------------------------------------------------------
938
+ # SPACE HOST
939
+ # --------------------------------------------------------
940
 
941
  if space_host_startup:
942
+
943
+ print(
944
+ f"SPACE_HOST found: "
945
+ f"{space_host_startup}"
946
+ )
947
+
948
+ print(
949
+ "Runtime URL:"
950
+ )
951
+
952
+ print(
953
+ f"https://{space_host_startup}.hf.space"
954
+ )
955
+
956
  else:
 
957
 
958
+ print(
959
+ "SPACE_HOST not found."
960
+ )
961
+
962
+
963
+ # --------------------------------------------------------
964
+ # SPACE ID
965
+ # --------------------------------------------------------
966
+
967
+ if space_id_startup:
968
+
969
+ print(
970
+ f"SPACE_ID found: "
971
+ f"{space_id_startup}"
972
+ )
973
+
974
+ print(
975
+ "Repository URL:"
976
+ )
977
+
978
+ print(
979
+ f"https://huggingface.co/spaces/"
980
+ f"{space_id_startup}"
981
+ )
982
+
983
+ print(
984
+ "Code URL:"
985
+ )
986
+
987
+ print(
988
+ f"https://huggingface.co/spaces/"
989
+ f"{space_id_startup}/tree/main"
990
+ )
991
+
992
  else:
 
993
 
994
+ print(
995
+ "SPACE_ID not found."
996
+ )
997
+
998
+
999
+ print(
1000
+ "\nLaunching General Purpose GAIA Agent..."
1001
+ )
1002
+
1003
+
1004
+ # --------------------------------------------------------
1005
+ # LAUNCH
1006
+ # --------------------------------------------------------
1007
 
1008
+ demo.launch(
1009
+ debug=True,
1010
+ share=False
1011
+ )