Imnotchis commited on
Commit
5dbf488
·
verified ·
1 Parent(s): ceb6c71

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +627 -125
app.py CHANGED
@@ -1,218 +1,720 @@
1
  import os
2
  import gradio as gr
3
  import requests
4
- import inspect
5
  import pandas as pd
 
6
  from smolagents import (
7
- CodeAgent,
8
  OpenAIModel,
9
  WebSearchTool,
10
- VisitWebpageTool,
11
- FinalAnswerTool
12
  )
13
- # (Keep Constants as is)
14
- # --- Constants ---
 
 
 
15
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
16
 
17
- # --- Basic Agent Definition ---
18
- # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
 
 
 
 
 
 
 
 
 
 
19
  class BasicAgent:
20
  def __init__(self):
 
 
 
 
 
 
 
21
  self.model = OpenAIModel(
22
- model_id = "openai/gpt-oss-20b",
23
  api_base="https://api.groq.com/openai/v1",
24
  api_key=os.environ["GROQ_API_KEY"]
25
  )
26
 
 
 
 
 
 
 
27
  self.tools = [
28
  WebSearchTool(),
29
  VisitWebpageTool()
30
  ]
31
 
32
- self.agent = CodeAgent(
33
- model = self.model,
34
- tools = self.tools,
35
- max_steps = 5
 
 
 
 
 
 
 
36
  )
37
 
38
- print("BasicAgent initialized.")
 
39
  def __call__(self, question: str) -> str:
40
- print(f"Agent received question (first 50 chars): {question[:50]}...")
41
 
42
- answer = self.agent.run(question)
43
-
44
- return answer
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
 
46
- def run_and_submit_all( profile: gr.OAuthProfile | None):
47
  """
48
- Fetches all questions, runs the BasicAgent on them, submits all answers,
49
- and displays the results.
 
 
 
 
 
 
50
  """
51
- # --- Determine HF Space Runtime URL and Repo URL ---
52
- space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
 
 
 
 
 
 
53
 
54
  if profile:
55
- username= f"{profile.username}"
56
- print(f"User logged in: {username}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57
  else:
58
- print("User not logged in.")
59
- return "Please Login to Hugging Face with the button.", None
 
 
 
 
 
60
 
61
  api_url = DEFAULT_API_URL
 
62
  questions_url = f"{api_url}/questions"
63
  submit_url = f"{api_url}/submit"
64
 
65
- # 1. Instantiate Agent ( modify this part to create your agent)
 
 
 
 
 
66
  try:
 
67
  agent = BasicAgent()
 
68
  except Exception as e:
69
- print(f"Error instantiating agent: {e}")
70
- return f"Error initializing agent: {e}", None
71
- # 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)
72
- agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
73
- print(agent_code)
74
-
75
- # 2. Fetch Questions
76
- print(f"Fetching questions from: {questions_url}")
 
 
 
 
 
 
 
 
 
 
77
  try:
78
- response = requests.get(questions_url, timeout=15)
 
 
 
 
 
79
  response.raise_for_status()
 
80
  questions_data = response.json()
 
81
  if not questions_data:
82
- print("Fetched questions list is empty.")
83
- return "Fetched questions list is empty or invalid format.", None
84
- print(f"Fetched {len(questions_data)} questions.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85
  except requests.exceptions.RequestException as e:
86
- print(f"Error fetching questions: {e}")
87
- return f"Error fetching questions: {e}", None
88
- except requests.exceptions.JSONDecodeError as e:
89
- print(f"Error decoding JSON response from questions endpoint: {e}")
90
- print(f"Response text: {response.text[:500]}")
91
- return f"Error decoding server response for questions: {e}", None
 
 
 
 
 
92
  except Exception as e:
93
- print(f"An unexpected error occurred fetching questions: {e}")
94
- return f"An unexpected error occurred fetching questions: {e}", None
95
 
96
- # 3. Run your Agent
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97
  results_log = []
98
  answers_payload = []
99
- print(f"Running agent on {len(questions_data)} questions...")
100
- for item in questions_data:
 
 
 
 
101
  task_id = item.get("task_id")
102
  question_text = item.get("question")
 
103
  if not task_id or question_text is None:
104
- print(f"Skipping item with missing task_id or question: {item}")
 
 
 
 
 
 
105
  continue
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
106
  try:
107
- submitted_answer = agent(question_text)
108
- answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
109
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
110
  except Exception as e:
111
- print(f"Error running agent on task {task_id}: {e}")
112
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
113
 
114
  if not answers_payload:
115
- print("Agent did not produce any answers to submit.")
116
- return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
117
 
118
- # 4. Prepare Submission
119
- submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
120
- status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
121
- print(status_update)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
122
 
123
- # 5. Submit
124
- print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
125
  try:
126
- response = requests.post(submit_url, json=submission_data, timeout=60)
 
 
 
 
 
 
 
 
 
 
 
127
  response.raise_for_status()
 
128
  result_data = response.json()
 
129
  final_status = (
130
- f"Submission Successful!\n"
131
- f"User: {result_data.get('username')}\n"
132
- f"Overall Score: {result_data.get('score', 'N/A')}% "
133
- f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
134
- f"Message: {result_data.get('message', 'No message received.')}"
135
- )
136
- print("Submission successful.")
137
- results_df = pd.DataFrame(results_log)
138
- return final_status, results_df
 
 
 
 
 
 
 
 
 
 
 
 
 
139
  except requests.exceptions.HTTPError as e:
140
- error_detail = f"Server responded with status {e.response.status_code}."
 
 
 
 
 
141
  try:
 
142
  error_json = e.response.json()
143
- error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
144
- except requests.exceptions.JSONDecodeError:
145
- error_detail += f" Response: {e.response.text[:500]}"
146
- status_message = f"Submission Failed: {error_detail}"
147
- print(status_message)
148
- results_df = pd.DataFrame(results_log)
149
- return status_message, results_df
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
150
  except requests.exceptions.Timeout:
151
- status_message = "Submission Failed: The request timed out."
152
- print(status_message)
153
- results_df = pd.DataFrame(results_log)
154
- return status_message, results_df
 
 
 
 
 
 
 
 
155
  except requests.exceptions.RequestException as e:
156
- status_message = f"Submission Failed: Network error - {e}"
157
- print(status_message)
158
- results_df = pd.DataFrame(results_log)
159
- return status_message, results_df
 
 
 
 
 
 
 
 
160
  except Exception as e:
161
- status_message = f"An unexpected error occurred during submission: {e}"
162
- print(status_message)
163
- results_df = pd.DataFrame(results_log)
164
- return status_message, results_df
165
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
166
 
167
- # --- Build Gradio Interface using Blocks ---
168
  with gr.Blocks() as demo:
169
- gr.Markdown("# Basic Agent Evaluation Runner")
 
 
 
 
170
  gr.Markdown(
171
  """
172
- **Instructions:**
173
- 1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
174
- 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
175
- 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
176
- ---
177
- **Disclaimers:**
178
- 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).
179
- 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.
 
 
 
 
180
  """
181
  )
182
 
183
  gr.LoginButton()
184
 
185
- run_button = gr.Button("Run Evaluation & Submit All Answers")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
186
 
187
- status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
188
- # Removed max_rows=10 from DataFrame constructor
189
- results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
 
190
 
191
  run_button.click(
192
  fn=run_and_submit_all,
193
- outputs=[status_output, results_table]
 
 
 
194
  )
195
 
 
 
 
 
 
196
  if __name__ == "__main__":
197
- print("\n" + "-"*30 + " App Starting " + "-"*30)
198
- # Check for SPACE_HOST and SPACE_ID at startup for information
199
- space_host_startup = os.getenv("SPACE_HOST")
200
- space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
 
 
 
 
 
 
 
 
 
 
 
 
201
 
202
  if space_host_startup:
203
- print(f"✅ SPACE_HOST found: {space_host_startup}")
204
- print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
 
 
 
 
 
 
 
 
 
 
 
205
  else:
206
- print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
207
 
208
- if space_id_startup: # Print repo URLs if SPACE_ID is found
209
- print(f"✅ SPACE_ID found: {space_id_startup}")
210
- print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
211
- print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
212
  else:
213
- print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
214
 
215
- print("-"*(60 + len(" App Starting ")) + "\n")
 
 
 
 
 
 
 
 
 
 
 
 
 
216
 
217
- print("Launching Gradio Interface for Basic Agent Evaluation...")
218
- demo.launch(debug=True, share=False)
 
 
 
1
  import os
2
  import gradio as gr
3
  import requests
 
4
  import pandas as pd
5
+
6
  from smolagents import (
7
+ ToolCallingAgent,
8
  OpenAIModel,
9
  WebSearchTool,
10
+ VisitWebpageTool
 
11
  )
12
+
13
+ # =========================================================
14
+ # CONSTANTS
15
+ # =========================================================
16
+
17
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
18
 
19
+ # =========================================================
20
+ # TEST CONFIG
21
+ # =========================================================
22
+
23
+ TEST_MODE = True
24
+ TEST_QUESTION_COUNT = 1
25
+
26
+
27
+ # =========================================================
28
+ # BASIC AGENT
29
+ # =========================================================
30
+
31
  class BasicAgent:
32
  def __init__(self):
33
+
34
+ print("\n[INIT] Initializing BasicAgent...", flush=True)
35
+
36
+ # -------------------------------------------------
37
+ # MODEL
38
+ # -------------------------------------------------
39
+
40
  self.model = OpenAIModel(
41
+ model_id="openai/gpt-oss-20b",
42
  api_base="https://api.groq.com/openai/v1",
43
  api_key=os.environ["GROQ_API_KEY"]
44
  )
45
 
46
+ print("[INIT] Groq model initialized.", flush=True)
47
+
48
+ # -------------------------------------------------
49
+ # TOOLS
50
+ # -------------------------------------------------
51
+
52
  self.tools = [
53
  WebSearchTool(),
54
  VisitWebpageTool()
55
  ]
56
 
57
+ print("[INIT] Tools initialized.", flush=True)
58
+
59
+ # -------------------------------------------------
60
+ # AGENT
61
+ # -------------------------------------------------
62
+
63
+ self.agent = ToolCallingAgent(
64
+ model=self.model,
65
+ tools=self.tools,
66
+ max_steps=3,
67
+ verbosity_level=2
68
  )
69
 
70
+ print("[INIT] ToolCallingAgent initialized.", flush=True)
71
+
72
  def __call__(self, question: str) -> str:
 
73
 
74
+ print("\n" + "=" * 60, flush=True)
75
+ print("AGENT START", flush=True)
76
+ print("=" * 60, flush=True)
77
+
78
+ print(f"[QUESTION]\n{question}", flush=True)
79
+
80
+ try:
81
+ answer = self.agent.run(question)
82
+
83
+ print("\n[ANSWER]", flush=True)
84
+ print(answer, flush=True)
85
+
86
+ print("=" * 60, flush=True)
87
+ print("AGENT END", flush=True)
88
+ print("=" * 60 + "\n", flush=True)
89
+
90
+ return str(answer)
91
+
92
+ except Exception as e:
93
+
94
+ print("\n[AGENT ERROR]", flush=True)
95
+ print(f"{type(e).__name__}: {e}", flush=True)
96
+
97
+ print("=" * 60, flush=True)
98
+ print("AGENT FAILED", flush=True)
99
+ print("=" * 60 + "\n", flush=True)
100
+
101
+ raise
102
+
103
+
104
+ # =========================================================
105
+ # MAIN EVALUATION FUNCTION
106
+ # =========================================================
107
+
108
+ def run_and_submit_all(profile: gr.OAuthProfile | None):
109
 
 
110
  """
111
+ In TEST_MODE:
112
+ - Fetch all GAIA questions
113
+ - Run only TEST_QUESTION_COUNT questions
114
+ - Do NOT submit answers
115
+
116
+ In normal mode:
117
+ - Run all questions
118
+ - Submit answers
119
  """
120
+
121
+ print("\n" + "=" * 70, flush=True)
122
+ print("RUN STARTED", flush=True)
123
+ print("=" * 70, flush=True)
124
+
125
+ # -----------------------------------------------------
126
+ # CHECK LOGIN
127
+ # -----------------------------------------------------
128
 
129
  if profile:
130
+ username = f"{profile.username}"
131
+ print(f"[LOGIN] User logged in: {username}", flush=True)
132
+
133
+ else:
134
+ print("[LOGIN] User not logged in.", flush=True)
135
+
136
+ return (
137
+ "Please Login to Hugging Face with the button.",
138
+ None
139
+ )
140
+
141
+ # -----------------------------------------------------
142
+ # SPACE INFORMATION
143
+ # -----------------------------------------------------
144
+
145
+ space_id = os.getenv("SPACE_ID")
146
+
147
+ print(f"[SPACE_ID] {space_id}", flush=True)
148
+
149
+ if space_id:
150
+ agent_code = (
151
+ f"https://huggingface.co/spaces/"
152
+ f"{space_id}/tree/main"
153
+ )
154
  else:
155
+ agent_code = "UNKNOWN"
156
+
157
+ print(f"[AGENT CODE] {agent_code}", flush=True)
158
+
159
+ # -----------------------------------------------------
160
+ # API ENDPOINTS
161
+ # -----------------------------------------------------
162
 
163
  api_url = DEFAULT_API_URL
164
+
165
  questions_url = f"{api_url}/questions"
166
  submit_url = f"{api_url}/submit"
167
 
168
+ print(f"[QUESTIONS API] {questions_url}", flush=True)
169
+
170
+ # -----------------------------------------------------
171
+ # INITIALIZE AGENT
172
+ # -----------------------------------------------------
173
+
174
  try:
175
+
176
  agent = BasicAgent()
177
+
178
  except Exception as e:
179
+
180
+ print(
181
+ f"[INIT ERROR] "
182
+ f"{type(e).__name__}: {e}",
183
+ flush=True
184
+ )
185
+
186
+ return (
187
+ f"Error initializing agent: {e}",
188
+ None
189
+ )
190
+
191
+ # -----------------------------------------------------
192
+ # FETCH QUESTIONS
193
+ # -----------------------------------------------------
194
+
195
+ print("\n[API] Fetching questions...", flush=True)
196
+
197
  try:
198
+
199
+ response = requests.get(
200
+ questions_url,
201
+ timeout=15
202
+ )
203
+
204
  response.raise_for_status()
205
+
206
  questions_data = response.json()
207
+
208
  if not questions_data:
209
+
210
+ print(
211
+ "[API] Fetched questions list is empty.",
212
+ flush=True
213
+ )
214
+
215
+ return (
216
+ "Fetched questions list is empty.",
217
+ None
218
+ )
219
+
220
+ print(
221
+ f"[API] Fetched "
222
+ f"{len(questions_data)} questions.",
223
+ flush=True
224
+ )
225
+
226
  except requests.exceptions.RequestException as e:
227
+
228
+ print(
229
+ f"[API ERROR] {e}",
230
+ flush=True
231
+ )
232
+
233
+ return (
234
+ f"Error fetching questions: {e}",
235
+ None
236
+ )
237
+
238
  except Exception as e:
 
 
239
 
240
+ print(
241
+ f"[API ERROR] "
242
+ f"{type(e).__name__}: {e}",
243
+ flush=True
244
+ )
245
+
246
+ return (
247
+ f"Unexpected error fetching questions: {e}",
248
+ None
249
+ )
250
+
251
+ # -----------------------------------------------------
252
+ # SELECT QUESTIONS
253
+ # -----------------------------------------------------
254
+
255
+ if TEST_MODE:
256
+
257
+ questions_to_run = (
258
+ questions_data[:TEST_QUESTION_COUNT]
259
+ )
260
+
261
+ print("\n" + "=" * 70, flush=True)
262
+ print("TEST MODE ENABLED", flush=True)
263
+ print("=" * 70, flush=True)
264
+
265
+ print(
266
+ f"[TEST] Total questions from API: "
267
+ f"{len(questions_data)}",
268
+ flush=True
269
+ )
270
+
271
+ print(
272
+ f"[TEST] Questions to run: "
273
+ f"{len(questions_to_run)}",
274
+ flush=True
275
+ )
276
+
277
+ print(
278
+ "[TEST] Submission is DISABLED.",
279
+ flush=True
280
+ )
281
+
282
+ else:
283
+
284
+ questions_to_run = questions_data
285
+
286
+ print(
287
+ f"[NORMAL MODE] Running "
288
+ f"{len(questions_to_run)} questions.",
289
+ flush=True
290
+ )
291
+
292
+ # -----------------------------------------------------
293
+ # RUN AGENT
294
+ # -----------------------------------------------------
295
+
296
  results_log = []
297
  answers_payload = []
298
+
299
+ for index, item in enumerate(
300
+ questions_to_run,
301
+ start=1
302
+ ):
303
+
304
  task_id = item.get("task_id")
305
  question_text = item.get("question")
306
+
307
  if not task_id or question_text is None:
308
+
309
+ print(
310
+ f"[SKIP] Missing task_id or question: "
311
+ f"{item}",
312
+ flush=True
313
+ )
314
+
315
  continue
316
+
317
+ print("\n" + "-" * 70, flush=True)
318
+
319
+ print(
320
+ f"[TASK] "
321
+ f"{index}/{len(questions_to_run)}",
322
+ flush=True
323
+ )
324
+
325
+ print(
326
+ f"[TASK ID] {task_id}",
327
+ flush=True
328
+ )
329
+
330
+ print(
331
+ f"[QUESTION]\n{question_text}",
332
+ flush=True
333
+ )
334
+
335
+ print("-" * 70 + "\n", flush=True)
336
+
337
  try:
338
+
339
+ submitted_answer = agent(
340
+ question_text
341
+ )
342
+
343
+ answers_payload.append(
344
+ {
345
+ "task_id": task_id,
346
+ "submitted_answer": submitted_answer
347
+ }
348
+ )
349
+
350
+ results_log.append(
351
+ {
352
+ "Task ID": task_id,
353
+ "Question": question_text,
354
+ "Submitted Answer": submitted_answer
355
+ }
356
+ )
357
+
358
+ print(
359
+ f"[TASK {index}] Completed.",
360
+ flush=True
361
+ )
362
+
363
  except Exception as e:
364
+
365
+ print(
366
+ f"[TASK {index} ERROR] "
367
+ f"{type(e).__name__}: {e}",
368
+ flush=True
369
+ )
370
+
371
+ results_log.append(
372
+ {
373
+ "Task ID": task_id,
374
+ "Question": question_text,
375
+ "Submitted Answer":
376
+ f"AGENT ERROR: {e}"
377
+ }
378
+ )
379
+
380
+ # -----------------------------------------------------
381
+ # CONVERT RESULTS TO DATAFRAME
382
+ # -----------------------------------------------------
383
+
384
+ results_df = pd.DataFrame(
385
+ results_log
386
+ )
387
+
388
+ # -----------------------------------------------------
389
+ # STOP HERE IN TEST MODE
390
+ # -----------------------------------------------------
391
+
392
+ if TEST_MODE:
393
+
394
+ print("\n" + "=" * 70, flush=True)
395
+ print("TEST FINISHED", flush=True)
396
+ print("=" * 70, flush=True)
397
+
398
+ print(
399
+ "[TEST] No answers submitted.",
400
+ flush=True
401
+ )
402
+
403
+ success_count = len(
404
+ answers_payload
405
+ )
406
+
407
+ failed_count = (
408
+ len(questions_to_run)
409
+ - success_count
410
+ )
411
+
412
+ status_message = (
413
+ "TEST COMPLETED\n\n"
414
+ f"Questions fetched: "
415
+ f"{len(questions_data)}\n"
416
+ f"Questions tested: "
417
+ f"{len(questions_to_run)}\n"
418
+ f"Successful runs: "
419
+ f"{success_count}\n"
420
+ f"Failed runs: "
421
+ f"{failed_count}\n\n"
422
+ "No answers were submitted.\n"
423
+ "Check Container Logs for details."
424
+ )
425
+
426
+ return (
427
+ status_message,
428
+ results_df
429
+ )
430
+
431
+ # -----------------------------------------------------
432
+ # NORMAL MODE:
433
+ # CHECK ANSWERS
434
+ # -----------------------------------------------------
435
 
436
  if not answers_payload:
 
 
437
 
438
+ print(
439
+ "[SUBMIT] No answers produced.",
440
+ flush=True
441
+ )
442
+
443
+ return (
444
+ "Agent did not produce any answers.",
445
+ results_df
446
+ )
447
+
448
+ # -----------------------------------------------------
449
+ # PREPARE SUBMISSION
450
+ # -----------------------------------------------------
451
+
452
+ submission_data = {
453
+ "username": username.strip(),
454
+ "agent_code": agent_code,
455
+ "answers": answers_payload
456
+ }
457
+
458
+ print(
459
+ f"\n[SUBMIT] Preparing to submit "
460
+ f"{len(answers_payload)} answers.",
461
+ flush=True
462
+ )
463
+
464
+ # -----------------------------------------------------
465
+ # SUBMIT
466
+ # -----------------------------------------------------
467
 
 
 
468
  try:
469
+
470
+ print(
471
+ f"[SUBMIT API] {submit_url}",
472
+ flush=True
473
+ )
474
+
475
+ response = requests.post(
476
+ submit_url,
477
+ json=submission_data,
478
+ timeout=60
479
+ )
480
+
481
  response.raise_for_status()
482
+
483
  result_data = response.json()
484
+
485
  final_status = (
486
+ "Submission Successful!\n\n"
487
+ f"User: "
488
+ f"{result_data.get('username')}\n"
489
+ f"Overall Score: "
490
+ f"{result_data.get('score', 'N/A')}%\n"
491
+ f"Correct: "
492
+ f"{result_data.get('correct_count', '?')}/"
493
+ f"{result_data.get('total_attempted', '?')}\n"
494
+ f"Message: "
495
+ f"{result_data.get('message', '')}"
496
+ )
497
+
498
+ print(
499
+ "[SUBMIT] Submission successful.",
500
+ flush=True
501
+ )
502
+
503
+ return (
504
+ final_status,
505
+ results_df
506
+ )
507
+
508
  except requests.exceptions.HTTPError as e:
509
+
510
+ error_detail = (
511
+ f"Server responded with status "
512
+ f"{e.response.status_code}."
513
+ )
514
+
515
  try:
516
+
517
  error_json = e.response.json()
518
+
519
+ error_detail += (
520
+ f" Detail: "
521
+ f"{error_json.get('detail', e.response.text)}"
522
+ )
523
+
524
+ except Exception:
525
+
526
+ error_detail += (
527
+ f" Response: "
528
+ f"{e.response.text[:500]}"
529
+ )
530
+
531
+ print(
532
+ f"[SUBMIT ERROR] {error_detail}",
533
+ flush=True
534
+ )
535
+
536
+ return (
537
+ f"Submission Failed: {error_detail}",
538
+ results_df
539
+ )
540
+
541
  except requests.exceptions.Timeout:
542
+
543
+ print(
544
+ "[SUBMIT ERROR] Request timed out.",
545
+ flush=True
546
+ )
547
+
548
+ return (
549
+ "Submission Failed: "
550
+ "The request timed out.",
551
+ results_df
552
+ )
553
+
554
  except requests.exceptions.RequestException as e:
555
+
556
+ print(
557
+ f"[SUBMIT ERROR] Network error: {e}",
558
+ flush=True
559
+ )
560
+
561
+ return (
562
+ f"Submission Failed: "
563
+ f"Network error - {e}",
564
+ results_df
565
+ )
566
+
567
  except Exception as e:
 
 
 
 
568
 
569
+ print(
570
+ f"[SUBMIT ERROR] "
571
+ f"{type(e).__name__}: {e}",
572
+ flush=True
573
+ )
574
+
575
+ return (
576
+ f"Unexpected submission error: {e}",
577
+ results_df
578
+ )
579
+
580
+
581
+ # =========================================================
582
+ # GRADIO UI
583
+ # =========================================================
584
 
 
585
  with gr.Blocks() as demo:
586
+
587
+ gr.Markdown(
588
+ "# Basic Agent Evaluation Runner"
589
+ )
590
+
591
  gr.Markdown(
592
  """
593
+ ### Current Configuration
594
+
595
+ - Model: `openai/gpt-oss-20b`
596
+ - Provider: Groq
597
+ - Agent: `ToolCallingAgent`
598
+ - Tools:
599
+ - `WebSearchTool`
600
+ - `VisitWebpageTool`
601
+ - Max steps: 3
602
+ - Test mode: Enabled
603
+ - Test questions: 1
604
+ - Submission while testing: Disabled
605
  """
606
  )
607
 
608
  gr.LoginButton()
609
 
610
+ if TEST_MODE:
611
+
612
+ run_button = gr.Button(
613
+ "Test 1 GAIA Question - No Submission"
614
+ )
615
+
616
+ else:
617
+
618
+ run_button = gr.Button(
619
+ "Run Evaluation & Submit All Answers"
620
+ )
621
+
622
+ status_output = gr.Textbox(
623
+ label="Run Status",
624
+ lines=8,
625
+ interactive=False
626
+ )
627
 
628
+ results_table = gr.DataFrame(
629
+ label="Questions and Agent Answers",
630
+ wrap=True
631
+ )
632
 
633
  run_button.click(
634
  fn=run_and_submit_all,
635
+ outputs=[
636
+ status_output,
637
+ results_table
638
+ ]
639
  )
640
 
641
+
642
+ # =========================================================
643
+ # APPLICATION STARTUP
644
+ # =========================================================
645
+
646
  if __name__ == "__main__":
647
+
648
+ print(
649
+ "\n"
650
+ + "-" * 30
651
+ + " App Starting "
652
+ + "-" * 30,
653
+ flush=True
654
+ )
655
+
656
+ space_host_startup = os.getenv(
657
+ "SPACE_HOST"
658
+ )
659
+
660
+ space_id_startup = os.getenv(
661
+ "SPACE_ID"
662
+ )
663
 
664
  if space_host_startup:
665
+
666
+ print(
667
+ f"✅ SPACE_HOST found: "
668
+ f"{space_host_startup}",
669
+ flush=True
670
+ )
671
+
672
+ print(
673
+ f"Runtime URL should be: "
674
+ f"https://{space_host_startup}",
675
+ flush=True
676
+ )
677
+
678
  else:
 
679
 
680
+ print(
681
+ "ℹ️ SPACE_HOST not found.",
682
+ flush=True
683
+ )
684
+
685
+ if space_id_startup:
686
+
687
+ print(
688
+ f"✅ SPACE_ID found: "
689
+ f"{space_id_startup}",
690
+ flush=True
691
+ )
692
+
693
+ print(
694
+ f"Repo URL: "
695
+ f"https://huggingface.co/spaces/"
696
+ f"{space_id_startup}",
697
+ flush=True
698
+ )
699
+
700
  else:
 
701
 
702
+ print(
703
+ "ℹ️ SPACE_ID not found.",
704
+ flush=True
705
+ )
706
+
707
+ print(
708
+ "-" * 74 + "\n",
709
+ flush=True
710
+ )
711
+
712
+ print(
713
+ "Launching Gradio Interface...",
714
+ flush=True
715
+ )
716
 
717
+ demo.launch(
718
+ debug=True,
719
+ share=False
720
+ )