Haider67 commited on
Commit
99d0043
·
verified ·
1 Parent(s): fde800a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +25 -313
app.py CHANGED
@@ -69,7 +69,6 @@ You are an intelligent and precise AI agent solving GAIA benchmark questions.
69
  Your goal is to return the most accurate answer possible.
70
 
71
  IMPORTANT RULES:
72
-
73
  1. Return only the answer requested by the question.
74
  2. Do not write "FINAL ANSWER" or introductory text.
75
  3. Do not explain your reasoning unless explicitly requested.
@@ -95,7 +94,6 @@ Return the shortest accurate answer that satisfies the question.
95
  # =========================================================
96
 
97
  def get_groq_key() -> str:
98
-
99
  api_key = (
100
  os.getenv("LLM_API_KEY")
101
  or os.getenv("GROQ_API_KEY")
@@ -116,17 +114,12 @@ def get_groq_key() -> str:
116
  # =========================================================
117
 
118
  def extract_api_error(response):
119
-
120
  try:
121
  data = response.json()
122
-
123
  error = data.get("error", {})
124
-
125
  if isinstance(error, dict):
126
  return error.get("message", response.text[:1000])
127
-
128
  return str(error)
129
-
130
  except Exception:
131
  return response.text[:1000]
132
 
@@ -136,53 +129,39 @@ def extract_api_error(response):
136
  # =========================================================
137
 
138
  def generate_groq_response(prompt: str) -> str:
139
-
 
140
  headers = {
141
- "Authorization": f"Bearer {get_groq_key()}",
142
- "Content-Type": "application/json",
143
  }
144
-
145
  payload = {
146
  "model": GROQ_MODEL,
147
  "messages": [
148
- {
149
- "role": "system",
150
- "content": SYSTEM_PROMPT,
151
- },
152
- {
153
- "role": "user",
154
- "content": prompt,
155
- },
156
  ],
157
- "temperature": 0,
158
- "max_completion_tokens": 3000,
159
- "reasoning_effort": "low",
160
  }
161
 
162
  for attempt in range(MAX_RETRIES + 1):
163
-
164
  try:
165
-
166
  response = SESSION.post(
167
  GROQ_CHAT_URL,
168
  headers=headers,
169
  json=payload,
170
  timeout=REQUEST_TIMEOUT,
171
  )
172
-
173
  except requests.RequestException as error:
174
-
175
  if attempt >= MAX_RETRIES:
176
  raise RuntimeError(
177
  f"Groq network error after retries: {error}"
178
  ) from error
179
 
180
  wait_time = min(2 ** attempt * 5, 30)
181
-
182
- print(
183
- f"Network error. Retrying in {wait_time} seconds..."
184
- )
185
-
186
  time.sleep(wait_time)
187
  continue
188
 
@@ -194,7 +173,6 @@ def generate_groq_response(prompt: str) -> str:
194
 
195
  # Authentication errors must stop immediately
196
  if response.status_code in (401, 403):
197
-
198
  raise RuntimeError(
199
  f"Groq authentication/permission error: "
200
  f"{response.status_code}: {error_message}"
@@ -202,16 +180,13 @@ def generate_groq_response(prompt: str) -> str:
202
 
203
  # Invalid request or model configuration
204
  if response.status_code == 400:
205
-
206
  raise RuntimeError(
207
  f"Groq rejected the request: {error_message}"
208
  )
209
 
210
  # Rate limit
211
  if response.status_code == 429:
212
-
213
  if attempt >= MAX_RETRIES:
214
-
215
  raise RuntimeError(
216
  "Groq rate limit reached after retries. "
217
  "No answers were submitted.\n"
@@ -219,35 +194,25 @@ def generate_groq_response(prompt: str) -> str:
219
  )
220
 
221
  retry_after = response.headers.get("Retry-After")
222
-
223
  try:
224
  wait_time = float(retry_after)
225
  except (TypeError, ValueError):
226
  wait_time = min(2 ** attempt * 15, 60)
227
 
228
- print(
229
- f"Groq rate limit. Waiting {wait_time} seconds..."
230
- )
231
-
232
  time.sleep(wait_time)
233
  continue
234
 
235
  # Temporary server errors
236
  if response.status_code >= 500:
237
-
238
  if attempt >= MAX_RETRIES:
239
-
240
  raise RuntimeError(
241
  f"Groq server error after retries: "
242
  f"{response.status_code}: {error_message}"
243
  )
244
 
245
  wait_time = min(2 ** attempt * 5, 30)
246
-
247
- print(
248
- f"Groq server error. Retrying in {wait_time} seconds..."
249
- )
250
-
251
  time.sleep(wait_time)
252
  continue
253
 
@@ -255,33 +220,27 @@ def generate_groq_response(prompt: str) -> str:
255
  f"Groq request failed ({response.status_code}): "
256
  f"{error_message}"
257
  )
258
-
259
  else:
260
  raise RuntimeError("Groq request failed after all retries.")
261
 
262
  # Parse JSON response
263
  try:
264
  result = response.json()
265
-
266
  except ValueError as error:
267
-
268
  raise RuntimeError(
269
  f"Groq returned invalid JSON: {response.text[:500]}"
270
  ) from error
271
 
272
  choices = result.get("choices") or []
273
-
274
  if not choices:
275
  raise RuntimeError("Groq returned no response choices.")
276
 
277
  choice = choices[0] or {}
278
  message = choice.get("message") or {}
279
-
280
  answer = message.get("content")
281
 
282
  # Support structured content responses
283
  if isinstance(answer, list):
284
-
285
  answer = "".join(
286
  block.get("text", "")
287
  for block in answer
@@ -292,13 +251,13 @@ def generate_groq_response(prompt: str) -> str:
292
  return answer.strip()
293
 
294
  finish_reason = choice.get("finish_reason", "unknown")
295
-
296
- raise RuntimeError(
297
- "Groq returned no visible answer text.\n"
298
- f"Model: {GROQ_MODEL}\n"
299
- f"Finish reason: {finish_reason}\n"
300
- f"Response ID: {result.get('id', 'unknown')}"
301
  )
 
302
 
303
 
304
  # =========================================================
@@ -306,20 +265,15 @@ def generate_groq_response(prompt: str) -> str:
306
  # =========================================================
307
 
308
  def clean_answer(answer: str) -> str:
309
-
310
  answer = answer.strip()
311
-
312
  answer = re.sub(
313
  r"^(final answer|answer)\s*:\s*",
314
  "",
315
  answer,
316
  flags=re.IGNORECASE,
317
  )
318
-
319
  answer = answer.strip()
320
-
321
  answer = answer.strip('"').strip("'").strip()
322
-
323
  return answer
324
 
325
 
@@ -328,31 +282,25 @@ def clean_answer(answer: str) -> str:
328
  # =========================================================
329
 
330
  def generate_answers(prompts: list[str]) -> list[str]:
331
-
332
  answers = []
333
 
334
  for index, user_prompt in enumerate(prompts, start=1):
335
-
336
  print(
337
  f"\nGenerating answer {index}/{len(prompts)} "
338
  f"using {GROQ_MODEL}"
339
  )
340
 
341
  try:
342
-
343
  raw_answer = generate_groq_response(user_prompt)
344
-
345
  answer = clean_answer(raw_answer)
346
 
347
  if not answer:
348
- raise RuntimeError("The generated answer is empty.")
349
 
350
  answers.append(answer)
351
-
352
  print(f"Answer {index}: {answer[:200]}")
353
 
354
  except Exception as error:
355
-
356
  raise RuntimeError(
357
  f"Answer generation failed for question "
358
  f"{index}/{len(prompts)}.\n"
@@ -362,7 +310,6 @@ def generate_answers(prompts: list[str]) -> list[str]:
362
 
363
  # Avoid unnecessary waiting after the final question
364
  if index < len(prompts):
365
-
366
  time.sleep(PAUSE_SECONDS)
367
 
368
  return answers
@@ -374,7 +321,6 @@ def generate_answers(prompts: list[str]) -> list[str]:
374
 
375
  @spaces.GPU(duration=60)
376
  def zerogpu_compatibility_check():
377
-
378
  return "ZeroGPU compatibility handler registered."
379
 
380
 
@@ -383,14 +329,12 @@ def zerogpu_compatibility_check():
383
  # =========================================================
384
 
385
  def download_file(task_id: str, file_name: str) -> str | None:
386
-
387
  if not file_name:
388
  return None
389
 
390
  url = f"{DEFAULT_API_URL}/files/{task_id}"
391
 
392
  try:
393
-
394
  response = SESSION.get(
395
  url,
396
  timeout=30,
@@ -406,31 +350,22 @@ def download_file(task_id: str, file_name: str) -> str | None:
406
  return None
407
 
408
  if len(response.content) > MAX_FILE_SIZE:
409
-
410
  raise RuntimeError(
411
  f"Attachment exceeds {MAX_FILE_SIZE // (1024 * 1024)} MB."
412
  )
413
 
414
  safe_name = os.path.basename(file_name)
415
-
416
  temp_dir = tempfile.mkdtemp(prefix="gaia_")
417
-
418
  file_path = os.path.join(temp_dir, safe_name)
419
 
420
  with open(file_path, "wb") as file:
421
-
422
  file.write(response.content)
423
 
424
  print(f"Downloaded attachment: {safe_name}")
425
-
426
  return file_path
427
 
428
  except Exception as error:
429
-
430
- print(
431
- f"File download error for task {task_id}: {error}"
432
- )
433
-
434
  return None
435
 
436
 
@@ -439,19 +374,14 @@ def download_file(task_id: str, file_name: str) -> str | None:
439
  # =========================================================
440
 
441
  def read_python_file(file_path: str) -> str:
442
-
443
  with open(
444
  file_path,
445
  "r",
446
  encoding="utf-8",
447
  errors="replace",
448
  ) as file:
449
-
450
  code = file.read()
451
 
452
- # Never execute downloaded Python files.
453
- # Give their source code to the LLM for analysis.
454
-
455
  return (
456
  "Python Source Code:\n"
457
  "The following is an attached Python program. "
@@ -466,13 +396,9 @@ def read_python_file(file_path: str) -> str:
466
  # =========================================================
467
 
468
  def read_excel_file(file_path: str) -> str:
469
-
470
  df = pd.read_excel(file_path)
471
-
472
  numeric_columns = df.select_dtypes(include="number")
473
-
474
  totals = numeric_columns.sum().round(4)
475
-
476
  averages = numeric_columns.mean().round(4)
477
 
478
  output = (
@@ -484,7 +410,6 @@ def read_excel_file(file_path: str) -> str:
484
  + "\n\nExcel Table:\n"
485
  + df.to_string(index=False)[:5000]
486
  )
487
-
488
  return output
489
 
490
 
@@ -493,33 +418,25 @@ def read_excel_file(file_path: str) -> str:
493
  # =========================================================
494
 
495
  def read_pdf_file(file_path: str) -> str:
496
-
497
  try:
498
  from pypdf import PdfReader
499
-
500
  except ImportError:
501
-
502
  return (
503
  "PDF reader dependency is missing. "
504
  "Install pypdf in requirements.txt."
505
  )
506
 
507
  reader = PdfReader(file_path)
508
-
509
  pages = []
510
 
511
  for page_number, page in enumerate(reader.pages, start=1):
512
-
513
  text = page.extract_text() or ""
514
-
515
  if text.strip():
516
-
517
  pages.append(
518
  f"\n--- Page {page_number} ---\n{text}"
519
  )
520
 
521
  if not pages:
522
-
523
  return (
524
  "No extractable text found in the PDF. "
525
  "It may be a scanned document requiring OCR."
@@ -536,39 +453,30 @@ def read_pdf_file(file_path: str) -> str:
536
  # =========================================================
537
 
538
  def read_docx_file(file_path: str) -> str:
539
-
540
  try:
541
  from docx import Document
542
-
543
  except ImportError:
544
-
545
  return (
546
  "DOCX reader dependency is missing. "
547
  "Install python-docx in requirements.txt."
548
  )
549
 
550
  document = Document(file_path)
551
-
552
  paragraphs = [
553
  paragraph.text
554
  for paragraph in document.paragraphs
555
  if paragraph.text.strip()
556
  ]
557
-
558
  tables = []
559
 
560
  for table in document.tables:
561
-
562
  for row in table.rows:
563
-
564
  tables.append(
565
  " | ".join(cell.text for cell in row.cells)
566
  )
567
 
568
  content = "\n".join(paragraphs)
569
-
570
  if tables:
571
-
572
  content += "\n\nTABLE DATA:\n" + "\n".join(tables)
573
 
574
  return (
@@ -582,13 +490,11 @@ def read_docx_file(file_path: str) -> str:
582
  # =========================================================
583
 
584
  def read_audio_file(file_path: str) -> str:
585
-
586
  headers = {
587
  "Authorization": f"Bearer {get_groq_key()}"
588
  }
589
 
590
  with open(file_path, "rb") as audio_file:
591
-
592
  response = SESSION.post(
593
  GROQ_AUDIO_URL,
594
  headers=headers,
@@ -605,7 +511,6 @@ def read_audio_file(file_path: str) -> str:
605
  )
606
 
607
  if not response.ok:
608
-
609
  raise RuntimeError(
610
  "Groq audio transcription failed: "
611
  f"{response.status_code}: "
@@ -613,9 +518,7 @@ def read_audio_file(file_path: str) -> str:
613
  )
614
 
615
  transcript = response.json().get("text", "").strip()
616
-
617
  if not transcript:
618
-
619
  return "Audio transcription returned an empty transcript."
620
 
621
  return (
@@ -629,68 +532,41 @@ def read_audio_file(file_path: str) -> str:
629
  # =========================================================
630
 
631
  def read_attached_file(file_path: str) -> str:
632
-
633
  if not file_path or not os.path.exists(file_path):
634
  return ""
635
 
636
  extension = Path(file_path).suffix.lower()
637
 
638
  try:
639
-
640
- # Python source code
641
  if extension == ".py":
642
-
643
  return read_python_file(file_path)
644
-
645
- # Excel
646
  elif extension in [".xlsx", ".xls"]:
647
-
648
  return read_excel_file(file_path)
649
-
650
- # PDF
651
  elif extension == ".pdf":
652
-
653
  return read_pdf_file(file_path)
654
-
655
- # Word
656
  elif extension == ".docx":
657
-
658
  return read_docx_file(file_path)
659
-
660
- # Audio
661
  elif extension in [
662
- ".mp3",
663
- ".wav",
664
- ".m4a",
665
- ".ogg",
666
- ".webm",
667
- ".flac",
668
- ".aac",
669
  ]:
670
-
671
  return read_audio_file(file_path)
672
-
673
- # Text, CSV and JSON
674
  elif extension in [".txt", ".csv", ".json"]:
675
-
676
  with open(
677
  file_path,
678
  "r",
679
  encoding="utf-8",
680
  errors="replace",
681
  ) as file:
682
-
683
  content = file.read()
684
 
685
  if extension == ".json":
686
-
687
  try:
688
  content = json.dumps(
689
  json.loads(content),
690
  indent=2,
691
  ensure_ascii=False,
692
  )
693
-
694
  except json.JSONDecodeError:
695
  pass
696
 
@@ -698,32 +574,21 @@ def read_attached_file(file_path: str) -> str:
698
  f"ATTACHED {extension.upper()} FILE:\n"
699
  + content[:7000]
700
  )
701
-
702
- # Images require a vision-capable model
703
  elif extension in [
704
- ".png",
705
- ".jpg",
706
- ".jpeg",
707
- ".webp",
708
- ".gif",
709
  ]:
710
-
711
  return (
712
  "An image attachment was provided, but this version "
713
  "does not have image-understanding enabled. "
714
  "Do not invent its contents."
715
  )
716
-
717
  except Exception as error:
718
-
719
  return (
720
  f"File reading error "
721
  f"({os.path.basename(file_path)}): {error}"
722
  )
723
 
724
- return (
725
- f"Unsupported attachment format: {extension}"
726
- )
727
 
728
 
729
  # =========================================================
@@ -731,13 +596,11 @@ def read_attached_file(file_path: str) -> str:
731
  # =========================================================
732
 
733
  def build_clean_query(question: str) -> str:
734
-
735
  query = re.sub(
736
  r"https?://\S+",
737
  "",
738
  question,
739
  )
740
-
741
  stop_words = {
742
  "the", "and", "for", "that", "this", "with",
743
  "what", "who", "how", "many", "was", "were",
@@ -746,7 +609,6 @@ def build_clean_query(question: str) -> str:
746
  "which", "when", "where", "does", "did",
747
  "find", "tell", "about", "name", "according",
748
  }
749
-
750
  words = [
751
  word
752
  for word in re.findall(
@@ -756,7 +618,6 @@ def build_clean_query(question: str) -> str:
756
  if len(word) > 2
757
  and word.lower() not in stop_words
758
  ]
759
-
760
  return " ".join(words[:20])
761
 
762
 
@@ -765,85 +626,57 @@ def build_clean_query(question: str) -> str:
765
  # =========================================================
766
 
767
  def search_web_and_wiki(question: str) -> str:
768
-
769
  query = build_clean_query(question)
770
-
771
  if not query:
772
  return ""
773
 
774
  snippets = []
775
 
776
- # -----------------------------------------------------
777
  # DuckDuckGo
778
- # -----------------------------------------------------
779
-
780
  try:
781
-
782
  print(f"Searching DuckDuckGo: {query}")
783
-
784
  ddg_results = DDGS().text(
785
  query,
786
  max_results=5,
787
  )
788
-
789
  for result in ddg_results or []:
790
-
791
  title = result.get("title", "")
792
-
793
  body = result.get("body", "")
794
-
795
  href = result.get("href", "")
796
-
797
  snippets.append(
798
  f"[Web Search]\n"
799
  f"Title: {title}\n"
800
  f"URL: {href}\n"
801
  f"Content: {body}"
802
  )
803
-
804
  except Exception as error:
805
-
806
  print(f"DuckDuckGo search error: {error}")
807
 
808
- # -----------------------------------------------------
809
  # Wikipedia
810
- # -----------------------------------------------------
811
-
812
  try:
813
-
814
  print(f"Searching Wikipedia: {query}")
815
-
816
  titles = wikipedia.search(
817
  query,
818
  results=2,
819
  )
820
-
821
  for title in titles:
822
-
823
  try:
824
-
825
  page = wikipedia.page(
826
  title,
827
  auto_suggest=False,
828
  )
829
-
830
  content = page.content
831
-
832
  snippets.append(
833
  f"[Wikipedia: {title}]\n"
834
  f"URL: {page.url}\n"
835
  f"{content[:2500]}"
836
  )
837
-
838
  except Exception as page_error:
839
-
840
  print(
841
  f"Wikipedia page error for {title}: "
842
  f"{page_error}"
843
  )
844
-
845
  except Exception as error:
846
-
847
  print(f"Wikipedia search error: {error}")
848
 
849
  return "\n\n".join(snippets)[:MAX_CONTEXT_CHARS]
@@ -854,18 +687,15 @@ def search_web_and_wiki(question: str) -> str:
854
  # =========================================================
855
 
856
  def reversed_text_hint(question: str) -> str:
857
-
858
  if (
859
  question.strip().startswith(".")
860
  or "rewsna" in question.lower()
861
  ):
862
-
863
  return (
864
  "The question may be written backwards.\n"
865
  "Reversed text:\n"
866
  + question[::-1]
867
  )
868
-
869
  return ""
870
 
871
 
@@ -874,14 +704,12 @@ def reversed_text_hint(question: str) -> str:
874
  # =========================================================
875
 
876
  def build_prompt(question: str, context: str) -> str:
877
-
878
  prompt = (
879
  "GAIA QUESTION:\n"
880
  + question
881
  )
882
 
883
  if context:
884
-
885
  prompt += (
886
  "\n\n"
887
  "SUPPORTING INFORMATION:\n"
@@ -895,7 +723,6 @@ def build_prompt(question: str, context: str) -> str:
895
  "Analyze the question and supporting evidence carefully. "
896
  "Return only the exact requested answer."
897
  )
898
-
899
  return prompt
900
 
901
 
@@ -906,37 +733,22 @@ def build_prompt(question: str, context: str) -> str:
906
  def run_and_submit_all(
907
  profile: gr.OAuthProfile | None,
908
  ):
909
-
910
  try:
911
-
912
- # -------------------------------------------------
913
- # CHECK AUTHENTICATION
914
- # -------------------------------------------------
915
-
916
  if not profile:
917
-
918
  return (
919
  "Please log in using the Hugging Face Login button.",
920
  None,
921
  )
922
 
923
  username = profile.username
924
-
925
  if not username:
926
-
927
  return (
928
  "Could not identify the Hugging Face username.",
929
  None,
930
  )
931
 
932
- # -------------------------------------------------
933
- # CHECK SPACE ID
934
- # -------------------------------------------------
935
-
936
  space_id = os.getenv("SPACE_ID")
937
-
938
  if not space_id:
939
-
940
  return (
941
  "Error: SPACE_ID environment variable is missing.",
942
  None,
@@ -944,45 +756,27 @@ def run_and_submit_all(
944
 
945
  space_id = space_id.strip("/")
946
 
947
- # -------------------------------------------------
948
- # API ENDPOINTS
949
- # -------------------------------------------------
950
-
951
  questions_url = f"{DEFAULT_API_URL}/questions"
952
-
953
  submit_url = f"{DEFAULT_API_URL}/submit"
954
-
955
  agent_code = (
956
  f"https://huggingface.co/spaces/"
957
  f"{space_id}/tree/main"
958
  )
959
 
960
- # -------------------------------------------------
961
- # CHECK GROQ KEY
962
- # -------------------------------------------------
963
-
964
  get_groq_key()
965
 
966
- # -------------------------------------------------
967
- # FETCH QUESTIONS
968
- # -------------------------------------------------
969
-
970
  print("\nFetching GAIA questions...")
971
-
972
  response = SESSION.get(
973
  questions_url,
974
  timeout=30,
975
  )
976
-
977
  response.raise_for_status()
978
-
979
  questions_data = response.json()
980
 
981
  if (
982
  not isinstance(questions_data, list)
983
  or not questions_data
984
  ):
985
-
986
  return (
987
  "Error: Evaluation API returned no valid questions.",
988
  None,
@@ -992,142 +786,84 @@ def run_and_submit_all(
992
  f"Successfully fetched {len(questions_data)} questions."
993
  )
994
 
995
- # -------------------------------------------------
996
- # PREPARE QUESTIONS
997
- # -------------------------------------------------
998
-
999
  valid_items = []
1000
-
1001
  prompts = []
1002
 
1003
  for index, item in enumerate(
1004
  questions_data,
1005
  start=1,
1006
  ):
1007
-
1008
  task_id = item.get("task_id")
1009
-
1010
  question_text = item.get("question")
1011
-
1012
  file_name = item.get("file_name", "")
1013
 
1014
  if not task_id or question_text is None:
1015
-
1016
- print(
1017
- f"Skipping invalid question {index}."
1018
- )
1019
-
1020
  continue
1021
 
1022
  print(
1023
  f"\nPreparing question {index}/"
1024
  f"{len(questions_data)}"
1025
  )
1026
-
1027
  print(f"Task ID: {task_id}")
1028
-
1029
  print(f"Question: {question_text[:250]}")
1030
 
1031
- # Download attachment
1032
  file_path = download_file(
1033
  task_id,
1034
  file_name,
1035
  )
1036
 
1037
- # -------------------------------------------------
1038
- # CONTEXT SELECTION
1039
- # -------------------------------------------------
1040
-
1041
  context = ""
1042
-
1043
- # Reversed question
1044
  hint = reversed_text_hint(question_text)
1045
 
1046
  if hint:
1047
-
1048
  context = hint
1049
-
1050
- # Attachment
1051
  elif file_path:
1052
-
1053
  context = read_attached_file(file_path)
1054
-
1055
- # Web search fallback
1056
  else:
1057
-
1058
  context = search_web_and_wiki(
1059
  question_text
1060
  )
1061
 
1062
- # Build prompt
1063
  user_prompt = build_prompt(
1064
  question_text,
1065
  context,
1066
  )
1067
-
1068
  valid_items.append(item)
1069
-
1070
  prompts.append(user_prompt)
1071
 
1072
  if not prompts:
1073
-
1074
  return (
1075
  "Error: No valid questions were prepared.",
1076
  None,
1077
  )
1078
 
1079
- # -------------------------------------------------
1080
- # GENERATE ANSWERS
1081
- # -------------------------------------------------
1082
-
1083
  print(
1084
  f"\nStarting Groq generation for "
1085
  f"{len(prompts)} questions..."
1086
  )
1087
-
1088
  final_answers = generate_answers(prompts)
1089
 
1090
- # -------------------------------------------------
1091
- # VALIDATE ANSWERS
1092
- # -------------------------------------------------
1093
-
1094
  if len(final_answers) != len(valid_items):
1095
-
1096
  raise RuntimeError(
1097
  "Answer count does not match question count."
1098
  )
1099
 
1100
- if any(
1101
- not isinstance(answer, str) or not answer.strip()
1102
- for answer in final_answers
1103
- ):
1104
-
1105
- raise RuntimeError(
1106
- "One or more answers are empty. Submission cancelled."
1107
- )
1108
-
1109
  print("\nAll answers generated successfully.")
1110
 
1111
- # -------------------------------------------------
1112
- # PREPARE SUBMISSION
1113
- # -------------------------------------------------
1114
-
1115
  answers_payload = []
1116
-
1117
  results_log = []
1118
 
1119
  for item, answer in zip(
1120
  valid_items,
1121
  final_answers,
1122
  ):
1123
-
1124
  answers_payload.append(
1125
  {
1126
  "task_id": item["task_id"],
1127
  "submitted_answer": answer,
1128
  }
1129
  )
1130
-
1131
  results_log.append(
1132
  {
1133
  "Task ID": item["task_id"],
@@ -1142,35 +878,22 @@ def run_and_submit_all(
1142
  "answers": answers_payload,
1143
  }
1144
 
1145
- # -------------------------------------------------
1146
- # SUBMIT TO GAIA
1147
- # -------------------------------------------------
1148
-
1149
  print("\nSubmitting answers to GAIA scoring API...")
1150
-
1151
  response = SESSION.post(
1152
  submit_url,
1153
  json=submission_data,
1154
  timeout=60,
1155
  )
1156
-
1157
  response.raise_for_status()
1158
 
1159
  try:
1160
-
1161
  result_data = response.json()
1162
-
1163
  except ValueError:
1164
-
1165
  raise RuntimeError(
1166
  "Scoring API returned invalid JSON: "
1167
  + response.text[:1000]
1168
  )
1169
 
1170
- # -------------------------------------------------
1171
- # DISPLAY RESULTS
1172
- # -------------------------------------------------
1173
-
1174
  final_status = (
1175
  "SUBMISSION SUCCESSFUL!\n\n"
1176
  f"User: {result_data.get('username', username)}\n"
@@ -1184,18 +907,13 @@ def run_and_submit_all(
1184
  )
1185
 
1186
  print("\n" + final_status)
1187
-
1188
  results_df = pd.DataFrame(results_log)
1189
-
1190
  return final_status, results_df
1191
 
1192
  except Exception as error:
1193
-
1194
  error_details = traceback.format_exc()
1195
-
1196
  print("\nEVALUATION ERROR:")
1197
  print(error_details)
1198
-
1199
  return (
1200
  f"Evaluation failed.\n\n"
1201
  f"Error: {str(error)}\n\n"
@@ -1209,7 +927,6 @@ def run_and_submit_all(
1209
  # =========================================================
1210
 
1211
  with gr.Blocks() as demo:
1212
-
1213
  gr.Markdown(
1214
  """
1215
  # Multi-Modal GAIA Agent Evaluation Runner
@@ -1222,7 +939,6 @@ with gr.Blocks() as demo:
1222
  )
1223
 
1224
  gr.LoginButton()
1225
-
1226
  gr.Markdown("---")
1227
 
1228
  run_button = gr.Button(
@@ -1241,12 +957,10 @@ with gr.Blocks() as demo:
1241
  wrap=True,
1242
  )
1243
 
1244
- # ZeroGPU compatibility
1245
  compatibility_button = gr.Button(
1246
  "ZeroGPU Compatibility",
1247
  visible=False,
1248
  )
1249
-
1250
  compatibility_output = gr.Textbox(
1251
  visible=False
1252
  )
@@ -1257,7 +971,6 @@ with gr.Blocks() as demo:
1257
  outputs=compatibility_output,
1258
  )
1259
 
1260
- # Main evaluation
1261
  run_button.click(
1262
  fn=run_and_submit_all,
1263
  inputs=[],
@@ -1273,5 +986,4 @@ with gr.Blocks() as demo:
1273
  # =========================================================
1274
 
1275
  if __name__ == "__main__":
1276
-
1277
  demo.launch()
 
69
  Your goal is to return the most accurate answer possible.
70
 
71
  IMPORTANT RULES:
 
72
  1. Return only the answer requested by the question.
73
  2. Do not write "FINAL ANSWER" or introductory text.
74
  3. Do not explain your reasoning unless explicitly requested.
 
94
  # =========================================================
95
 
96
  def get_groq_key() -> str:
 
97
  api_key = (
98
  os.getenv("LLM_API_KEY")
99
  or os.getenv("GROQ_API_KEY")
 
114
  # =========================================================
115
 
116
  def extract_api_error(response):
 
117
  try:
118
  data = response.json()
 
119
  error = data.get("error", {})
 
120
  if isinstance(error, dict):
121
  return error.get("message", response.text[:1000])
 
122
  return str(error)
 
123
  except Exception:
124
  return response.text[:1000]
125
 
 
129
  # =========================================================
130
 
131
  def generate_groq_response(prompt: str) -> str:
132
+ api_key = get_groq_key()
133
+
134
  headers = {
135
+ "Authorization": f"Bearer {api_key}",
136
+ "Content-Type": "application/json"
137
  }
138
+
139
  payload = {
140
  "model": GROQ_MODEL,
141
  "messages": [
142
+ {"role": "system", "content": SYSTEM_PROMPT},
143
+ {"role": "user", "content": prompt}
 
 
 
 
 
 
144
  ],
145
+ "temperature": 0.0,
146
+ "max_tokens": 2048
 
147
  }
148
 
149
  for attempt in range(MAX_RETRIES + 1):
 
150
  try:
 
151
  response = SESSION.post(
152
  GROQ_CHAT_URL,
153
  headers=headers,
154
  json=payload,
155
  timeout=REQUEST_TIMEOUT,
156
  )
 
157
  except requests.RequestException as error:
 
158
  if attempt >= MAX_RETRIES:
159
  raise RuntimeError(
160
  f"Groq network error after retries: {error}"
161
  ) from error
162
 
163
  wait_time = min(2 ** attempt * 5, 30)
164
+ print(f"Network error. Retrying in {wait_time} seconds...")
 
 
 
 
165
  time.sleep(wait_time)
166
  continue
167
 
 
173
 
174
  # Authentication errors must stop immediately
175
  if response.status_code in (401, 403):
 
176
  raise RuntimeError(
177
  f"Groq authentication/permission error: "
178
  f"{response.status_code}: {error_message}"
 
180
 
181
  # Invalid request or model configuration
182
  if response.status_code == 400:
 
183
  raise RuntimeError(
184
  f"Groq rejected the request: {error_message}"
185
  )
186
 
187
  # Rate limit
188
  if response.status_code == 429:
 
189
  if attempt >= MAX_RETRIES:
 
190
  raise RuntimeError(
191
  "Groq rate limit reached after retries. "
192
  "No answers were submitted.\n"
 
194
  )
195
 
196
  retry_after = response.headers.get("Retry-After")
 
197
  try:
198
  wait_time = float(retry_after)
199
  except (TypeError, ValueError):
200
  wait_time = min(2 ** attempt * 15, 60)
201
 
202
+ print(f"Groq rate limit. Waiting {wait_time} seconds...")
 
 
 
203
  time.sleep(wait_time)
204
  continue
205
 
206
  # Temporary server errors
207
  if response.status_code >= 500:
 
208
  if attempt >= MAX_RETRIES:
 
209
  raise RuntimeError(
210
  f"Groq server error after retries: "
211
  f"{response.status_code}: {error_message}"
212
  )
213
 
214
  wait_time = min(2 ** attempt * 5, 30)
215
+ print(f"Groq server error. Retrying in {wait_time} seconds...")
 
 
 
 
216
  time.sleep(wait_time)
217
  continue
218
 
 
220
  f"Groq request failed ({response.status_code}): "
221
  f"{error_message}"
222
  )
 
223
  else:
224
  raise RuntimeError("Groq request failed after all retries.")
225
 
226
  # Parse JSON response
227
  try:
228
  result = response.json()
 
229
  except ValueError as error:
 
230
  raise RuntimeError(
231
  f"Groq returned invalid JSON: {response.text[:500]}"
232
  ) from error
233
 
234
  choices = result.get("choices") or []
 
235
  if not choices:
236
  raise RuntimeError("Groq returned no response choices.")
237
 
238
  choice = choices[0] or {}
239
  message = choice.get("message") or {}
 
240
  answer = message.get("content")
241
 
242
  # Support structured content responses
243
  if isinstance(answer, list):
 
244
  answer = "".join(
245
  block.get("text", "")
246
  for block in answer
 
251
  return answer.strip()
252
 
253
  finish_reason = choice.get("finish_reason", "unknown")
254
+
255
+ # Graceful fallback instead of hard-crashing entire evaluation
256
+ print(
257
+ f"Warning: Groq returned empty content. "
258
+ f"Model: {GROQ_MODEL}, Finish reason: {finish_reason}"
 
259
  )
260
+ return "No answer generated"
261
 
262
 
263
  # =========================================================
 
265
  # =========================================================
266
 
267
  def clean_answer(answer: str) -> str:
 
268
  answer = answer.strip()
 
269
  answer = re.sub(
270
  r"^(final answer|answer)\s*:\s*",
271
  "",
272
  answer,
273
  flags=re.IGNORECASE,
274
  )
 
275
  answer = answer.strip()
 
276
  answer = answer.strip('"').strip("'").strip()
 
277
  return answer
278
 
279
 
 
282
  # =========================================================
283
 
284
  def generate_answers(prompts: list[str]) -> list[str]:
 
285
  answers = []
286
 
287
  for index, user_prompt in enumerate(prompts, start=1):
 
288
  print(
289
  f"\nGenerating answer {index}/{len(prompts)} "
290
  f"using {GROQ_MODEL}"
291
  )
292
 
293
  try:
 
294
  raw_answer = generate_groq_response(user_prompt)
 
295
  answer = clean_answer(raw_answer)
296
 
297
  if not answer:
298
+ answer = "No answer generated"
299
 
300
  answers.append(answer)
 
301
  print(f"Answer {index}: {answer[:200]}")
302
 
303
  except Exception as error:
 
304
  raise RuntimeError(
305
  f"Answer generation failed for question "
306
  f"{index}/{len(prompts)}.\n"
 
310
 
311
  # Avoid unnecessary waiting after the final question
312
  if index < len(prompts):
 
313
  time.sleep(PAUSE_SECONDS)
314
 
315
  return answers
 
321
 
322
  @spaces.GPU(duration=60)
323
  def zerogpu_compatibility_check():
 
324
  return "ZeroGPU compatibility handler registered."
325
 
326
 
 
329
  # =========================================================
330
 
331
  def download_file(task_id: str, file_name: str) -> str | None:
 
332
  if not file_name:
333
  return None
334
 
335
  url = f"{DEFAULT_API_URL}/files/{task_id}"
336
 
337
  try:
 
338
  response = SESSION.get(
339
  url,
340
  timeout=30,
 
350
  return None
351
 
352
  if len(response.content) > MAX_FILE_SIZE:
 
353
  raise RuntimeError(
354
  f"Attachment exceeds {MAX_FILE_SIZE // (1024 * 1024)} MB."
355
  )
356
 
357
  safe_name = os.path.basename(file_name)
 
358
  temp_dir = tempfile.mkdtemp(prefix="gaia_")
 
359
  file_path = os.path.join(temp_dir, safe_name)
360
 
361
  with open(file_path, "wb") as file:
 
362
  file.write(response.content)
363
 
364
  print(f"Downloaded attachment: {safe_name}")
 
365
  return file_path
366
 
367
  except Exception as error:
368
+ print(f"File download error for task {task_id}: {error}")
 
 
 
 
369
  return None
370
 
371
 
 
374
  # =========================================================
375
 
376
  def read_python_file(file_path: str) -> str:
 
377
  with open(
378
  file_path,
379
  "r",
380
  encoding="utf-8",
381
  errors="replace",
382
  ) as file:
 
383
  code = file.read()
384
 
 
 
 
385
  return (
386
  "Python Source Code:\n"
387
  "The following is an attached Python program. "
 
396
  # =========================================================
397
 
398
  def read_excel_file(file_path: str) -> str:
 
399
  df = pd.read_excel(file_path)
 
400
  numeric_columns = df.select_dtypes(include="number")
 
401
  totals = numeric_columns.sum().round(4)
 
402
  averages = numeric_columns.mean().round(4)
403
 
404
  output = (
 
410
  + "\n\nExcel Table:\n"
411
  + df.to_string(index=False)[:5000]
412
  )
 
413
  return output
414
 
415
 
 
418
  # =========================================================
419
 
420
  def read_pdf_file(file_path: str) -> str:
 
421
  try:
422
  from pypdf import PdfReader
 
423
  except ImportError:
 
424
  return (
425
  "PDF reader dependency is missing. "
426
  "Install pypdf in requirements.txt."
427
  )
428
 
429
  reader = PdfReader(file_path)
 
430
  pages = []
431
 
432
  for page_number, page in enumerate(reader.pages, start=1):
 
433
  text = page.extract_text() or ""
 
434
  if text.strip():
 
435
  pages.append(
436
  f"\n--- Page {page_number} ---\n{text}"
437
  )
438
 
439
  if not pages:
 
440
  return (
441
  "No extractable text found in the PDF. "
442
  "It may be a scanned document requiring OCR."
 
453
  # =========================================================
454
 
455
  def read_docx_file(file_path: str) -> str:
 
456
  try:
457
  from docx import Document
 
458
  except ImportError:
 
459
  return (
460
  "DOCX reader dependency is missing. "
461
  "Install python-docx in requirements.txt."
462
  )
463
 
464
  document = Document(file_path)
 
465
  paragraphs = [
466
  paragraph.text
467
  for paragraph in document.paragraphs
468
  if paragraph.text.strip()
469
  ]
 
470
  tables = []
471
 
472
  for table in document.tables:
 
473
  for row in table.rows:
 
474
  tables.append(
475
  " | ".join(cell.text for cell in row.cells)
476
  )
477
 
478
  content = "\n".join(paragraphs)
 
479
  if tables:
 
480
  content += "\n\nTABLE DATA:\n" + "\n".join(tables)
481
 
482
  return (
 
490
  # =========================================================
491
 
492
  def read_audio_file(file_path: str) -> str:
 
493
  headers = {
494
  "Authorization": f"Bearer {get_groq_key()}"
495
  }
496
 
497
  with open(file_path, "rb") as audio_file:
 
498
  response = SESSION.post(
499
  GROQ_AUDIO_URL,
500
  headers=headers,
 
511
  )
512
 
513
  if not response.ok:
 
514
  raise RuntimeError(
515
  "Groq audio transcription failed: "
516
  f"{response.status_code}: "
 
518
  )
519
 
520
  transcript = response.json().get("text", "").strip()
 
521
  if not transcript:
 
522
  return "Audio transcription returned an empty transcript."
523
 
524
  return (
 
532
  # =========================================================
533
 
534
  def read_attached_file(file_path: str) -> str:
 
535
  if not file_path or not os.path.exists(file_path):
536
  return ""
537
 
538
  extension = Path(file_path).suffix.lower()
539
 
540
  try:
 
 
541
  if extension == ".py":
 
542
  return read_python_file(file_path)
 
 
543
  elif extension in [".xlsx", ".xls"]:
 
544
  return read_excel_file(file_path)
 
 
545
  elif extension == ".pdf":
 
546
  return read_pdf_file(file_path)
 
 
547
  elif extension == ".docx":
 
548
  return read_docx_file(file_path)
 
 
549
  elif extension in [
550
+ ".mp3", ".wav", ".m4a", ".ogg",
551
+ ".webm", ".flac", ".aac",
 
 
 
 
 
552
  ]:
 
553
  return read_audio_file(file_path)
 
 
554
  elif extension in [".txt", ".csv", ".json"]:
 
555
  with open(
556
  file_path,
557
  "r",
558
  encoding="utf-8",
559
  errors="replace",
560
  ) as file:
 
561
  content = file.read()
562
 
563
  if extension == ".json":
 
564
  try:
565
  content = json.dumps(
566
  json.loads(content),
567
  indent=2,
568
  ensure_ascii=False,
569
  )
 
570
  except json.JSONDecodeError:
571
  pass
572
 
 
574
  f"ATTACHED {extension.upper()} FILE:\n"
575
  + content[:7000]
576
  )
 
 
577
  elif extension in [
578
+ ".png", ".jpg", ".jpeg", ".webp", ".gif",
 
 
 
 
579
  ]:
 
580
  return (
581
  "An image attachment was provided, but this version "
582
  "does not have image-understanding enabled. "
583
  "Do not invent its contents."
584
  )
 
585
  except Exception as error:
 
586
  return (
587
  f"File reading error "
588
  f"({os.path.basename(file_path)}): {error}"
589
  )
590
 
591
+ return f"Unsupported attachment format: {extension}"
 
 
592
 
593
 
594
  # =========================================================
 
596
  # =========================================================
597
 
598
  def build_clean_query(question: str) -> str:
 
599
  query = re.sub(
600
  r"https?://\S+",
601
  "",
602
  question,
603
  )
 
604
  stop_words = {
605
  "the", "and", "for", "that", "this", "with",
606
  "what", "who", "how", "many", "was", "were",
 
609
  "which", "when", "where", "does", "did",
610
  "find", "tell", "about", "name", "according",
611
  }
 
612
  words = [
613
  word
614
  for word in re.findall(
 
618
  if len(word) > 2
619
  and word.lower() not in stop_words
620
  ]
 
621
  return " ".join(words[:20])
622
 
623
 
 
626
  # =========================================================
627
 
628
  def search_web_and_wiki(question: str) -> str:
 
629
  query = build_clean_query(question)
 
630
  if not query:
631
  return ""
632
 
633
  snippets = []
634
 
 
635
  # DuckDuckGo
 
 
636
  try:
 
637
  print(f"Searching DuckDuckGo: {query}")
 
638
  ddg_results = DDGS().text(
639
  query,
640
  max_results=5,
641
  )
 
642
  for result in ddg_results or []:
 
643
  title = result.get("title", "")
 
644
  body = result.get("body", "")
 
645
  href = result.get("href", "")
 
646
  snippets.append(
647
  f"[Web Search]\n"
648
  f"Title: {title}\n"
649
  f"URL: {href}\n"
650
  f"Content: {body}"
651
  )
 
652
  except Exception as error:
 
653
  print(f"DuckDuckGo search error: {error}")
654
 
 
655
  # Wikipedia
 
 
656
  try:
 
657
  print(f"Searching Wikipedia: {query}")
 
658
  titles = wikipedia.search(
659
  query,
660
  results=2,
661
  )
 
662
  for title in titles:
 
663
  try:
 
664
  page = wikipedia.page(
665
  title,
666
  auto_suggest=False,
667
  )
 
668
  content = page.content
 
669
  snippets.append(
670
  f"[Wikipedia: {title}]\n"
671
  f"URL: {page.url}\n"
672
  f"{content[:2500]}"
673
  )
 
674
  except Exception as page_error:
 
675
  print(
676
  f"Wikipedia page error for {title}: "
677
  f"{page_error}"
678
  )
 
679
  except Exception as error:
 
680
  print(f"Wikipedia search error: {error}")
681
 
682
  return "\n\n".join(snippets)[:MAX_CONTEXT_CHARS]
 
687
  # =========================================================
688
 
689
  def reversed_text_hint(question: str) -> str:
 
690
  if (
691
  question.strip().startswith(".")
692
  or "rewsna" in question.lower()
693
  ):
 
694
  return (
695
  "The question may be written backwards.\n"
696
  "Reversed text:\n"
697
  + question[::-1]
698
  )
 
699
  return ""
700
 
701
 
 
704
  # =========================================================
705
 
706
  def build_prompt(question: str, context: str) -> str:
 
707
  prompt = (
708
  "GAIA QUESTION:\n"
709
  + question
710
  )
711
 
712
  if context:
 
713
  prompt += (
714
  "\n\n"
715
  "SUPPORTING INFORMATION:\n"
 
723
  "Analyze the question and supporting evidence carefully. "
724
  "Return only the exact requested answer."
725
  )
 
726
  return prompt
727
 
728
 
 
733
  def run_and_submit_all(
734
  profile: gr.OAuthProfile | None,
735
  ):
 
736
  try:
 
 
 
 
 
737
  if not profile:
 
738
  return (
739
  "Please log in using the Hugging Face Login button.",
740
  None,
741
  )
742
 
743
  username = profile.username
 
744
  if not username:
 
745
  return (
746
  "Could not identify the Hugging Face username.",
747
  None,
748
  )
749
 
 
 
 
 
750
  space_id = os.getenv("SPACE_ID")
 
751
  if not space_id:
 
752
  return (
753
  "Error: SPACE_ID environment variable is missing.",
754
  None,
 
756
 
757
  space_id = space_id.strip("/")
758
 
 
 
 
 
759
  questions_url = f"{DEFAULT_API_URL}/questions"
 
760
  submit_url = f"{DEFAULT_API_URL}/submit"
 
761
  agent_code = (
762
  f"https://huggingface.co/spaces/"
763
  f"{space_id}/tree/main"
764
  )
765
 
 
 
 
 
766
  get_groq_key()
767
 
 
 
 
 
768
  print("\nFetching GAIA questions...")
 
769
  response = SESSION.get(
770
  questions_url,
771
  timeout=30,
772
  )
 
773
  response.raise_for_status()
 
774
  questions_data = response.json()
775
 
776
  if (
777
  not isinstance(questions_data, list)
778
  or not questions_data
779
  ):
 
780
  return (
781
  "Error: Evaluation API returned no valid questions.",
782
  None,
 
786
  f"Successfully fetched {len(questions_data)} questions."
787
  )
788
 
 
 
 
 
789
  valid_items = []
 
790
  prompts = []
791
 
792
  for index, item in enumerate(
793
  questions_data,
794
  start=1,
795
  ):
 
796
  task_id = item.get("task_id")
 
797
  question_text = item.get("question")
 
798
  file_name = item.get("file_name", "")
799
 
800
  if not task_id or question_text is None:
801
+ print(f"Skipping invalid question {index}.")
 
 
 
 
802
  continue
803
 
804
  print(
805
  f"\nPreparing question {index}/"
806
  f"{len(questions_data)}"
807
  )
 
808
  print(f"Task ID: {task_id}")
 
809
  print(f"Question: {question_text[:250]}")
810
 
 
811
  file_path = download_file(
812
  task_id,
813
  file_name,
814
  )
815
 
 
 
 
 
816
  context = ""
 
 
817
  hint = reversed_text_hint(question_text)
818
 
819
  if hint:
 
820
  context = hint
 
 
821
  elif file_path:
 
822
  context = read_attached_file(file_path)
 
 
823
  else:
 
824
  context = search_web_and_wiki(
825
  question_text
826
  )
827
 
 
828
  user_prompt = build_prompt(
829
  question_text,
830
  context,
831
  )
 
832
  valid_items.append(item)
 
833
  prompts.append(user_prompt)
834
 
835
  if not prompts:
 
836
  return (
837
  "Error: No valid questions were prepared.",
838
  None,
839
  )
840
 
 
 
 
 
841
  print(
842
  f"\nStarting Groq generation for "
843
  f"{len(prompts)} questions..."
844
  )
 
845
  final_answers = generate_answers(prompts)
846
 
 
 
 
 
847
  if len(final_answers) != len(valid_items):
 
848
  raise RuntimeError(
849
  "Answer count does not match question count."
850
  )
851
 
 
 
 
 
 
 
 
 
 
852
  print("\nAll answers generated successfully.")
853
 
 
 
 
 
854
  answers_payload = []
 
855
  results_log = []
856
 
857
  for item, answer in zip(
858
  valid_items,
859
  final_answers,
860
  ):
 
861
  answers_payload.append(
862
  {
863
  "task_id": item["task_id"],
864
  "submitted_answer": answer,
865
  }
866
  )
 
867
  results_log.append(
868
  {
869
  "Task ID": item["task_id"],
 
878
  "answers": answers_payload,
879
  }
880
 
 
 
 
 
881
  print("\nSubmitting answers to GAIA scoring API...")
 
882
  response = SESSION.post(
883
  submit_url,
884
  json=submission_data,
885
  timeout=60,
886
  )
 
887
  response.raise_for_status()
888
 
889
  try:
 
890
  result_data = response.json()
 
891
  except ValueError:
 
892
  raise RuntimeError(
893
  "Scoring API returned invalid JSON: "
894
  + response.text[:1000]
895
  )
896
 
 
 
 
 
897
  final_status = (
898
  "SUBMISSION SUCCESSFUL!\n\n"
899
  f"User: {result_data.get('username', username)}\n"
 
907
  )
908
 
909
  print("\n" + final_status)
 
910
  results_df = pd.DataFrame(results_log)
 
911
  return final_status, results_df
912
 
913
  except Exception as error:
 
914
  error_details = traceback.format_exc()
 
915
  print("\nEVALUATION ERROR:")
916
  print(error_details)
 
917
  return (
918
  f"Evaluation failed.\n\n"
919
  f"Error: {str(error)}\n\n"
 
927
  # =========================================================
928
 
929
  with gr.Blocks() as demo:
 
930
  gr.Markdown(
931
  """
932
  # Multi-Modal GAIA Agent Evaluation Runner
 
939
  )
940
 
941
  gr.LoginButton()
 
942
  gr.Markdown("---")
943
 
944
  run_button = gr.Button(
 
957
  wrap=True,
958
  )
959
 
 
960
  compatibility_button = gr.Button(
961
  "ZeroGPU Compatibility",
962
  visible=False,
963
  )
 
964
  compatibility_output = gr.Textbox(
965
  visible=False
966
  )
 
971
  outputs=compatibility_output,
972
  )
973
 
 
974
  run_button.click(
975
  fn=run_and_submit_all,
976
  inputs=[],
 
986
  # =========================================================
987
 
988
  if __name__ == "__main__":
 
989
  demo.launch()