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d2b0b7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3c4371f
3d2b0b7
 
 
 
 
 
 
 
 
 
 
 
e80aab9
3d2b0b7
 
 
 
 
 
 
 
 
 
 
 
7d65c66
e80aab9
3d2b0b7
 
 
 
 
 
 
 
 
 
 
 
 
e80aab9
 
3d2b0b7
 
 
 
 
0ee0419
e514fd7
3d2b0b7
e514fd7
3d2b0b7
 
 
 
 
e514fd7
3d2b0b7
 
e514fd7
e80aab9
 
7e4a06b
e80aab9
3d2b0b7
 
 
 
 
 
 
 
 
 
 
 
 
 
e80aab9
 
31243f4
3d2b0b7
31243f4
3d2b0b7
 
 
 
 
e80aab9
 
3d2b0b7
 
 
 
 
e80aab9
7d65c66
3d2b0b7
 
 
 
 
 
7d65c66
3d2b0b7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3c4371f
3d2b0b7
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
import os
import gradio as gr
import requests
import pandas as pd
import tempfile
import json
import subprocess
import sys
from pathlib import Path

from smolagents import (
    CodeAgent,
    HfApiModel,
    DuckDuckGoSearchTool,
    tool,
)

# ============================================================
# CONSTANTS
# ============================================================

DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"


# ============================================================
# CUSTOM TOOLS
# ============================================================

@tool
def calculate(expression: str) -> str:
    """
    Calculate a mathematical expression.

    Args:
        expression: A Python mathematical expression such as
                    "17 * 23" or "(100 / 4) + 7".

    Returns:
        The calculated result as a string.
    """
    try:
        allowed = {
            "abs": abs,
            "round": round,
            "min": min,
            "max": max,
            "sum": sum,
        }

        result = eval(
            expression,
            {"__builtins__": {}},
            allowed
        )

        return str(result)

    except Exception as e:
        return f"Calculation error: {e}"


@tool
def analyze_csv_or_excel(file_path: str, operation: str) -> str:
    """
    Analyze a CSV or Excel file.

    Args:
        file_path: Path to the CSV or Excel file.
        operation: Describe what should be calculated or inspected.

    Returns:
        A textual summary of the file and requested operation.
    """

    try:
        path = Path(file_path)

        if not path.exists():
            return "File does not exist."

        if path.suffix.lower() in [".xlsx", ".xls"]:
            df = pd.read_excel(path)
        elif path.suffix.lower() == ".csv":
            df = pd.read_csv(path)
        else:
            return "Unsupported file type."

        result = {
            "columns": list(df.columns),
            "rows": len(df),
            "preview": df.head(10).to_dict(orient="records"),
            "numeric_summary": df.describe(
                include="all"
            ).to_dict()
        }

        return json.dumps(result, default=str)

    except Exception as e:
        return f"Spreadsheet analysis error: {e}"


@tool
def read_text_file(file_path: str) -> str:
    """
    Read a text-based file.

    Args:
        file_path: Path to the text file.

    Returns:
        The contents of the file.
    """

    try:
        path = Path(file_path)

        if not path.exists():
            return "File does not exist."

        return path.read_text(
            encoding="utf-8",
            errors="ignore"
        )

    except Exception as e:
        return f"Could not read file: {e}"


@tool
def execute_python_file(file_path: str) -> str:
    """
    Execute a Python file and return its output.

    Args:
        file_path: Path to the Python file.

    Returns:
        Standard output produced by the Python program.
    """

    try:
        path = Path(file_path)

        if not path.exists():
            return "Python file does not exist."

        result = subprocess.run(
            [sys.executable, str(path)],
            capture_output=True,
            text=True,
            timeout=30
        )

        output = result.stdout.strip()

        if result.stderr:
            output += "\nSTDERR:\n" + result.stderr.strip()

        return output

    except subprocess.TimeoutExpired:
        return "Python execution timed out."

    except Exception as e:
        return f"Python execution error: {e}"


# ============================================================
# GAIA AGENT
# ============================================================

class BasicAgent:

    def __init__(self):

        print("=" * 60)
        print("Initializing GAIA Agent...")
        print("=" * 60)

        # ----------------------------------------------------
        # Hugging Face model
        # ----------------------------------------------------

        self.model = HfApiModel(
            model_id="Qwen/Qwen2.5-Coder-32B-Instruct"
        )

        # ----------------------------------------------------
        # Web search
        # ----------------------------------------------------

        self.search_tool = DuckDuckGoSearchTool()

        # ----------------------------------------------------
        # Agent
        # ----------------------------------------------------

        self.agent = CodeAgent(

            model=self.model,

            tools=[
                self.search_tool,
                calculate,
                analyze_csv_or_excel,
                read_text_file,
                execute_python_file,
            ],

            additional_authorized_imports=[
                "requests",
                "bs4",
                "datetime",
                "pandas",
                "math",
                "statistics",
                "json",
                "re",
            ],

            max_steps=15,

            verbosity_level=1,
        )

        print("GAIA Agent initialized successfully.")


    # --------------------------------------------------------
    # Clean final answer
    # --------------------------------------------------------

    def clean_answer(self, answer):

        if answer is None:
            return "unknown"

        answer = str(answer).strip()

        # Remove common unwanted prefixes
        prefixes = [
            "FINAL ANSWER:",
            "Final Answer:",
            "FINAL ANSWER",
            "Final answer:",
            "Answer:",
            "answer:",
        ]

        for prefix in prefixes:

            if answer.startswith(prefix):
                answer = answer[len(prefix):].strip()

        # Remove markdown code fences
        answer = answer.replace("```", "").strip()

        # Remove accidental surrounding quotes
        if (
            len(answer) >= 2
            and answer[0] == '"'
            and answer[-1] == '"'
        ):
            answer = answer[1:-1].strip()

        return answer


    # --------------------------------------------------------
    # Run Agent
    # --------------------------------------------------------

    def __call__(self, question: str) -> str:

        print("\n" + "=" * 70)
        print("QUESTION")
        print(question)
        print("=" * 70)

        prompt = f"""
You are a highly capable general-purpose AI agent solving a
GAIA Level-1 benchmark question.

Your goal is to obtain the CORRECT final answer.

You have access to:

1. Web search
2. Python calculations
3. Spreadsheet analysis
4. Python file execution
5. Text file reading

GENERAL RULES:

- Carefully understand the question.
- Do not guess if you can verify the information.
- Use web search for factual/current/research questions.
- Use Python for calculations, sorting, counting and data processing.
- Use spreadsheet tools for Excel/CSV questions.
- Use the Python execution tool when a Python file is provided.
- Perform multi-step reasoning when necessary.
- Verify important results before answering.

IMPORTANT OUTPUT RULE:

The benchmark uses exact matching.

Therefore your FINAL RESPONSE must contain ONLY the answer.

Do NOT write:

"FINAL ANSWER:"

Do NOT write:

"The answer is..."

Do NOT explain your reasoning.

Do NOT add unnecessary punctuation.

Examples:

If the answer is a number:

391

If the answer is a name:

Smith

If the question asks for a comma-separated list:

apples, bananas, oranges

Question:

{question}
"""

        try:

            result = self.agent.run(prompt)

            answer = self.clean_answer(result)

            print("\nAGENT ANSWER:")
            print(answer)

            return answer

        except Exception as e:

            print("\nAGENT ERROR:")
            print(e)

            return "unknown"


# ============================================================
# DOWNLOAD ATTACHED GAIA FILE
# ============================================================

def download_task_file(task_id):

    file_url = f"{DEFAULT_API_URL}/files/{task_id}"

    try:

        response = requests.get(
            file_url,
            timeout=30
        )

        if response.status_code != 200:
            return None

        # Try to determine extension from headers
        content_type = response.headers.get(
            "content-type",
            ""
        ).lower()

        extension = ".bin"

        if "png" in content_type:
            extension = ".png"

        elif "jpeg" in content_type:
            extension = ".jpg"

        elif "audio" in content_type:
            extension = ".mp3"

        elif "excel" in content_type:
            extension = ".xlsx"

        elif "csv" in content_type:
            extension = ".csv"

        elif "python" in content_type:
            extension = ".py"

        # Temporary file
        temp = tempfile.NamedTemporaryFile(
            delete=False,
            suffix=extension
        )

        temp.write(response.content)
        temp.close()

        print(
            f"Downloaded task file: {temp.name}"
        )

        return temp.name

    except Exception as e:

        print(
            f"Could not download task file: {e}"
        )

        return None


# ============================================================
# MAIN EVALUATION FUNCTION
# ============================================================

def run_and_submit_all(
    profile: gr.OAuthProfile | None
):

    """
    Fetch all GAIA questions,
    run the Agent,
    and submit answers.
    """

    # --------------------------------------------------------
    # Get username
    # --------------------------------------------------------

    space_id = os.getenv("SPACE_ID")

    if profile:

        username = f"{profile.username}"

        print(
            f"User logged in: {username}"
        )

    else:

        print("User not logged in.")

        return (
            "Please Login to Hugging Face with the button.",
            None
        )


    # --------------------------------------------------------
    # API endpoints
    # --------------------------------------------------------

    api_url = DEFAULT_API_URL

    questions_url = f"{api_url}/questions"

    submit_url = f"{api_url}/submit"


    # --------------------------------------------------------
    # Create Agent
    # --------------------------------------------------------

    try:

        agent = BasicAgent()

    except Exception as e:

        print(
            f"Error initializing agent: {e}"
        )

        return (
            f"Error initializing agent: {e}",
            None
        )


    # --------------------------------------------------------
    # Code link
    # --------------------------------------------------------

    agent_code = (
        f"https://huggingface.co/spaces/"
        f"{space_id}/tree/main"
    )

    print(
        f"Agent code: {agent_code}"
    )


    # --------------------------------------------------------
    # Fetch questions
    # --------------------------------------------------------

    print(
        f"Fetching questions from: {questions_url}"
    )

    try:

        response = requests.get(
            questions_url,
            timeout=30
        )

        response.raise_for_status()

        questions_data = response.json()

        if not questions_data:

            return (
                "Question list is empty.",
                None
            )

        print(
            f"Fetched {len(questions_data)} questions."
        )

    except Exception as e:

        print(
            f"Error fetching questions: {e}"
        )

        return (
            f"Error fetching questions: {e}",
            None
        )


    # --------------------------------------------------------
    # Run Agent
    # --------------------------------------------------------

    results_log = []

    answers_payload = []

    print(
        f"\nRunning Agent on "
        f"{len(questions_data)} questions..."
    )


    for index, item in enumerate(
        questions_data,
        start=1
    ):

        task_id = item.get("task_id")

        question_text = item.get(
            "question"
        )

        file_name = item.get(
            "file_name",
            ""
        )


        if not task_id or question_text is None:

            print(
                "Skipping invalid question."
            )

            continue


        print("\n")
        print("#" * 80)
        print(
            f"QUESTION {index}/{len(questions_data)}"
        )
        print(
            f"TASK ID: {task_id}"
        )

        if file_name:

            print(
                f"ATTACHED FILE: {file_name}"
            )


        # ----------------------------------------------------
        # Handle attached file
        # ----------------------------------------------------

        enhanced_question = question_text

        if file_name:

            file_path = download_task_file(
                task_id
            )

            if file_path:

                enhanced_question += f"""

IMPORTANT:

This GAIA question has an attached file.

Original file name:
{file_name}

The file has been downloaded locally to:

{file_path}

You MUST use the appropriate tool to inspect this file
when the question requires information from it.

For an Excel/CSV file:
use analyze_csv_or_excel.

For a Python file:
use execute_python_file.

For a text file:
use read_text_file.

Do not ignore the attached file.
"""

            else:

                enhanced_question += f"""

IMPORTANT:

The question references this attached file:

{file_name}

The file could not be downloaded automatically.
Try to solve the question using the information available
in the question or other available tools.
"""


        # ----------------------------------------------------
        # Run Agent
        # ----------------------------------------------------

        try:

            submitted_answer = agent(
                enhanced_question
            )

            submitted_answer = str(
                submitted_answer
            ).strip()

            answers_payload.append(
                {
                    "task_id": task_id,
                    "submitted_answer": submitted_answer
                }
            )

            results_log.append(
                {
                    "Task ID": task_id,
                    "Question": question_text,
                    "File": file_name,
                    "Submitted Answer": submitted_answer
                }
            )

            print(
                f"FINAL ANSWER: {submitted_answer}"
            )


        except Exception as e:

            print(
                f"Agent failed on task "
                f"{task_id}: {e}"
            )

            results_log.append(
                {
                    "Task ID": task_id,
                    "Question": question_text,
                    "File": file_name,
                    "Submitted Answer":
                        f"AGENT ERROR: {e}"
                }
            )


    # --------------------------------------------------------
    # Check answers
    # --------------------------------------------------------

    if not answers_payload:

        return (
            "Agent did not produce any answers.",
            pd.DataFrame(results_log)
        )


    # --------------------------------------------------------
    # Prepare submission
    # --------------------------------------------------------

    submission_data = {

        "username":
            username.strip(),

        "agent_code":
            agent_code,

        "answers":
            answers_payload
    }


    status_update = (
        f"Agent finished.\n"
        f"Submitting {len(answers_payload)} "
        f"answers for user '{username}'..."
    )

    print(status_update)


    # --------------------------------------------------------
    # Submit
    # --------------------------------------------------------

    try:

        response = requests.post(

            submit_url,

            json=submission_data,

            timeout=180
        )

        response.raise_for_status()

        result_data = response.json()


        final_status = (

            "Submission Successful!\n\n"

            f"User: "
            f"{result_data.get('username')}\n"

            f"Overall Score: "
            f"{result_data.get('score', 'N/A')}%\n"

            f"Correct: "
            f"{result_data.get('correct_count', '?')}/"
            f"{result_data.get('total_attempted', '?')}\n\n"

            f"Message: "
            f"{result_data.get('message', '')}"
        )


        print(final_status)


        results_df = pd.DataFrame(
            results_log
        )


        return (
            final_status,
            results_df
        )


    except requests.exceptions.HTTPError as e:

        error_detail = (
            f"Server responded with "
            f"status {e.response.status_code}."
        )

        try:

            error_json = e.response.json()

            error_detail += (
                f" Detail: "
                f"{error_json.get('detail', '')}"
            )

        except Exception:

            error_detail += (
                f" Response: "
                f"{e.response.text[:500]}"
            )


        status_message = (
            f"Submission Failed: "
            f"{error_detail}"
        )


        return (
            status_message,
            pd.DataFrame(results_log)
        )


    except requests.exceptions.Timeout:

        status_message = (
            "Submission Failed: "
            "The request timed out."
        )

        return (
            status_message,
            pd.DataFrame(results_log)
        )


    except requests.exceptions.RequestException as e:

        status_message = (
            f"Submission Failed: "
            f"Network error - {e}"
        )

        return (
            status_message,
            pd.DataFrame(results_log)
        )


    except Exception as e:

        status_message = (
            f"Unexpected submission error: {e}"
        )

        return (
            status_message,
            pd.DataFrame(results_log)
        )


# ============================================================
# GRADIO INTERFACE
# ============================================================

with gr.Blocks() as demo:

    gr.Markdown(
        "# πŸ€– GAIA Agent Evaluation Runner"
    )

    gr.Markdown(
        """
        ## Instructions

        1. Log in to your Hugging Face account.
        2. Your Agent will receive the GAIA evaluation questions.
        3. Your Agent will use tools to solve them.
        4. The answers will automatically be submitted.
        5. Your score will be displayed below.

        **Important:** The benchmark uses exact matching,
        so the Agent should return only the final answer.
        """
    )

    gr.LoginButton()

    run_button = gr.Button(
        "πŸš€ Run Evaluation & Submit All Answers"
    )

    status_output = gr.Textbox(
        label="Run Status / Submission Result",
        lines=7,
        interactive=False
    )

    results_table = gr.DataFrame(
        label="Questions and Agent Answers",
        wrap=True
    )


    run_button.click(

        fn=run_and_submit_all,

        outputs=[
            status_output,
            results_table
        ]
    )


# ============================================================
# START
# ============================================================

if __name__ == "__main__":

    print(
        "\n" +
        "=" * 60 +
        "\n GAIA AGENT STARTING \n" +
        "=" * 60
    )

    space_id = os.getenv(
        "SPACE_ID"
    )

    if space_id:

        print(
            f"Space ID: {space_id}"
        )

        print(
            "Code URL: "
            f"https://huggingface.co/spaces/"
            f"{space_id}/tree/main"
        )

    demo.launch(
        debug=True,
        share=False
    )