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