File size: 17,950 Bytes
311c0d0
a765bf8
 
4bb25ec
6f446d0
7bbcaa3
 
5850246
 
 
316942f
5850246
 
 
 
7bbcaa3
 
311c0d0
d68dd9c
1ccc559
 
 
a765bf8
 
 
 
 
 
d68dd9c
5850246
 
 
 
1ccc559
5850246
 
 
 
 
 
 
 
 
 
 
1ccc559
5850246
 
 
 
 
 
 
1ccc559
5850246
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ccc559
5850246
 
 
1ccc559
5850246
 
 
 
1ccc559
5850246
 
 
1ccc559
5850246
 
 
1ccc559
5850246
 
 
 
 
 
 
1ccc559
5850246
 
1ccc559
a765bf8
5850246
 
 
 
 
 
1ccc559
 
a765bf8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ccc559
 
 
08e2aa5
 
 
1ccc559
a765bf8
 
 
 
 
 
 
316942f
a765bf8
 
 
593495d
5850246
 
 
 
a765bf8
 
1ccc559
7bbcaa3
 
5850246
 
1ccc559
 
 
5850246
 
a765bf8
 
5850246
8420ad2
e698212
5850246
a765bf8
5850246
 
 
 
 
 
 
 
 
a765bf8
 
 
 
5850246
7bbcaa3
e698212
5850246
 
 
 
 
 
 
 
 
 
 
 
 
 
a765bf8
 
 
 
5850246
 
 
 
 
 
7bbcaa3
6f6fcc7
1ccc559
 
 
 
 
 
08e2aa5
1ccc559
 
08e2aa5
1ccc559
6f446d0
cedc6dd
5850246
6f446d0
cedc6dd
6f446d0
1ccc559
 
 
 
 
6f446d0
cedc6dd
08e2aa5
 
d68dd9c
1ccc559
08e2aa5
 
 
6f446d0
08e2aa5
1ccc559
 
 
a765bf8
1ccc559
cb8f9c9
6f446d0
8ea0ccb
1ccc559
 
 
4bb25ec
1ccc559
 
 
8ea0ccb
08e2aa5
 
5850246
1ccc559
 
 
 
 
 
 
 
 
d68dd9c
08e2aa5
 
6f446d0
1ccc559
 
 
 
5850246
1ccc559
 
 
 
 
8ea0ccb
1ccc559
 
 
 
 
 
 
 
 
d68dd9c
1ccc559
8ea0ccb
 
1ccc559
 
 
 
08e2aa5
 
 
1ccc559
 
 
 
08e2aa5
1ccc559
 
 
 
 
 
 
 
 
 
08e2aa5
1ccc559
 
 
 
 
5850246
1ccc559
 
 
 
 
 
5850246
 
 
 
 
1ccc559
 
 
5850246
 
08e2aa5
1ccc559
 
 
5850246
 
 
 
1ccc559
 
 
5850246
 
08e2aa5
 
1ccc559
 
 
 
 
 
 
 
08e2aa5
5850246
 
 
 
 
 
1ccc559
 
 
 
 
08e2aa5
d68dd9c
8ea0ccb
1ccc559
 
 
 
d68dd9c
1ccc559
 
 
 
 
d68dd9c
 
08e2aa5
d68dd9c
 
1ccc559
 
 
 
 
 
 
d68dd9c
 
08e2aa5
 
1ccc559
d68dd9c
1ccc559
 
 
 
d68dd9c
 
1ccc559
 
 
 
d68dd9c
1ccc559
 
 
 
 
 
 
08e2aa5
8ea0ccb
08e2aa5
1ccc559
6f446d0
1ccc559
 
 
6f446d0
 
 
1ccc559
d68dd9c
1ccc559
 
 
08e2aa5
 
 
1ccc559
8ea0ccb
1ccc559
 
 
 
08e2aa5
 
 
d68dd9c
 
1ccc559
 
 
d68dd9c
1ccc559
1c3bf8f
148ab21
1ccc559
 
 
 
 
 
 
 
 
148ab21
d68dd9c
 
cedc6dd
1ccc559
 
 
5850246
1ccc559
 
 
 
 
 
 
5850246
d68dd9c
1ccc559
 
 
 
d68dd9c
a765bf8
 
d68dd9c
1ccc559
 
 
 
 
 
 
8ea0ccb
1ccc559
 
8ea0ccb
1ccc559
8ea0ccb
1ccc559
 
 
 
6f446d0
1ccc559
 
a765bf8
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
import os
import base64
import mimetypes
import requests
import pandas as pd
import gradio as gr
from dotenv import load_dotenv
from smolagents import (
    CodeAgent,
    DuckDuckGoSearchTool,
    OpenAIServerModel,
    WikipediaSearchTool,
    VisitWebpageTool,
    Tool,
)

load_dotenv()

# --- Constants ---
DEFAULT_API_URL = (
    "https://agents-course-unit4-scoring.hf.space"
)
GROQ_API_BASE = "https://api.groq.com/openai/v1"
TEXT_MODEL_ID = "llama-3.3-70b-versatile"
VISION_MODEL_ID = (
    "meta-llama/llama-4-scout-17b-16e-instruct"
)
AUDIO_MODEL_ID = "whisper-large-v3"

# Format instructions appended to every question
# so that the agent returns exact-match-friendly
# answers via final_answer().
ANSWER_FORMAT_INSTRUCTIONS = """

IMPORTANT FORMAT INSTRUCTIONS:
Your final_answer must be as concise as possible:
- If the answer is a number, return ONLY the number
  (no units, no commas, no $ or % unless asked).
- If the answer is a string, return ONLY the
  essential words (no articles like "the"/"a",
  no abbreviations for cities, write digits in
  plain text unless told otherwise).
- If the answer is a comma separated list, apply
  the rules above to each element.
Do NOT include explanations in your final_answer,
just the bare answer."""


# --------------------------------------------------
# Custom tool: download a GAIA task file
# --------------------------------------------------
class GaiaFileFetcherTool(Tool):
    """Downloads the file attached to a GAIA task."""

    name = "fetch_task_file"
    description = (
        "Downloads the file attached to a GAIA task "
        "given its task_id. Returns the local path "
        "to the downloaded file so you can read it."
    )
    inputs = {
        "task_id": {
            "type": "string",
            "description": (
                "The task_id of the GAIA question "
                "whose attached file you need."
            ),
        }
    }
    output_type = "string"

    def __init__(self, api_url: str, **kwargs):
        super().__init__(**kwargs)
        self.api_url = api_url

    def forward(self, task_id: str) -> str:
        import requests as _req
        import tempfile as _tmp
        import mimetypes as _mt

        url = f"{self.api_url}/files/{task_id}"
        resp = _req.get(url, timeout=30)
        resp.raise_for_status()

        # Derive a sensible extension from headers
        ct = resp.headers.get("Content-Type", "")
        ext = _mt.guess_extension(ct.split(";")[0]) or ""

        cd = resp.headers.get(
            "Content-Disposition", ""
        )
        fname = ""
        if "filename=" in cd:
            fname = cd.split("filename=")[-1]
            fname = fname.strip('"').strip("'")

        if not fname:
            fname = f"{task_id}{ext}"

        fname = os.path.basename(fname)
        path = os.path.join(
            _tmp.gettempdir(), fname
        )
        with open(path, "wb") as f:
            f.write(resp.content)
        return path


class GroqAudioTranscriptionTool(Tool):
    """Transcribes an audio file with Groq Whisper."""

    name = "transcribe_audio_file"
    description = (
        "Transcribes a local audio file path, such as an "
        "MP3 downloaded with fetch_task_file. Returns the "
        "plain transcript text."
    )
    inputs = {
        "file_path": {
            "type": "string",
            "description": "Local path to the audio file.",
        }
    }
    output_type = "string"

    def forward(self, file_path: str) -> str:
        api_key = os.getenv("GROQ_API_KEY")
        if not api_key:
            raise RuntimeError(
                "GROQ_API_KEY is required for audio transcription."
            )

        with open(file_path, "rb") as audio_file:
            response = requests.post(
                f"{GROQ_API_BASE}/audio/transcriptions",
                headers={
                    "Authorization": f"Bearer {api_key}",
                },
                files={
                    "file": (
                        os.path.basename(file_path),
                        audio_file,
                    )
                },
                data={
                    "model": AUDIO_MODEL_ID,
                    "response_format": "json",
                    "temperature": "0",
                },
                timeout=120,
            )
        response.raise_for_status()
        return response.json().get("text", "").strip()


class GroqImageAnalysisTool(Tool):
    """Answers questions about a local image with Groq vision."""

    name = "analyze_image_file"
    description = (
        "Analyzes a local image file path and answers a "
        "specific visual question about it."
    )
    inputs = {
        "file_path": {
            "type": "string",
            "description": "Local path to the image file.",
        },
        "question": {
            "type": "string",
            "description": "The question to answer about the image.",
        },
    }
    output_type = "string"

    def forward(self, file_path: str, question: str) -> str:
        api_key = os.getenv("GROQ_API_KEY")
        if not api_key:
            raise RuntimeError(
                "GROQ_API_KEY is required for image analysis."
            )

        mime_type = (
            mimetypes.guess_type(file_path)[0]
            or "application/octet-stream"
        )
        with open(file_path, "rb") as image_file:
            encoded = base64.b64encode(
                image_file.read()
            ).decode("ascii")

        response = requests.post(
            f"{GROQ_API_BASE}/chat/completions",
            headers={
                "Authorization": f"Bearer {api_key}",
                "Content-Type": "application/json",
            },
            json={
                "model": VISION_MODEL_ID,
                "messages": [
                    {
                        "role": "user",
                        "content": [
                            {
                                "type": "text",
                                "text": question,
                            },
                            {
                                "type": "image_url",
                                "image_url": {
                                    "url": (
                                        f"data:{mime_type};"
                                        f"base64,{encoded}"
                                    )
                                },
                            },
                        ],
                    }
                ],
                "temperature": 0.1,
                "max_completion_tokens": 512,
            },
            timeout=120,
        )
        response.raise_for_status()
        return (
            response.json()["choices"][0]["message"]
            ["content"]
            .strip()
        )


# --------------------------------------------------
# Agent wrapper
# --------------------------------------------------
class BasicAgent:
    def __init__(self):
        print("BasicAgent initialized.")

        groq_api_key = os.getenv("GROQ_API_KEY")
        if not groq_api_key:
            raise RuntimeError(
                "Missing GROQ_API_KEY. Add it to your "
                "Hugging Face Space secrets or local .env file."
            )

        model = OpenAIServerModel(
            model_id=TEXT_MODEL_ID,
            api_base=GROQ_API_BASE,
            api_key=groq_api_key,
        )

        self.file_tool = GaiaFileFetcherTool(
            api_url=DEFAULT_API_URL,
        )
        self.audio_tool = GroqAudioTranscriptionTool()
        self.image_tool = GroqImageAnalysisTool()

        self.agent = CodeAgent(
            model=model,
            tools=[
                DuckDuckGoSearchTool(),
                WikipediaSearchTool(
                    user_agent="GaiaAgent/1.0"
                ),
                VisitWebpageTool(),
                self.file_tool,
                self.audio_tool,
                self.image_tool,
            ],
            max_steps=15,
            verbosity_level=0,
            additional_authorized_imports=[
                "base64",
                "json",
                "re",
                "csv",
                "math",
                "statistics",
                "datetime",
                "collections",
                "itertools",
                "os",
                "pathlib",
                "mimetypes",
                "pandas",
                "openpyxl",
            ],
        )

    def __call__(
        self,
        question: str,
        task_id: str,
        has_file: bool = False,
    ) -> str:
        # Build the prompt for the agent
        prompt = question

        if has_file:
            prompt += (
                f"\n\n[This question has an attached "
                f"file. Use the fetch_task_file tool "
                f"with task_id='{task_id}' to "
                f"download it. If it is audio, use "
                f"transcribe_audio_file. If it is an "
                f"image, use analyze_image_file. If it "
                f"is a spreadsheet, read it with pandas.]"
            )

        prompt += ANSWER_FORMAT_INSTRUCTIONS

        raw = str(self.agent.run(prompt))
        return raw.strip()


# --------------------------------------------------
# Gradio: run all & submit
# --------------------------------------------------
def run_and_submit_all(
    profile: gr.OAuthProfile | None,
):
    """
    Fetches all questions, runs the agent,
    submits answers, and displays results.
    """
    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_url = DEFAULT_API_URL
    questions_url = f"{api_url}/questions"
    submit_url = f"{api_url}/submit"

    # 1. Instantiate Agent
    try:
        agent = BasicAgent()
    except Exception as e:
        print(f"Error instantiating agent: {e}")
        return f"Error initializing agent: {e}", None

    agent_code = (
        f"https://huggingface.co/spaces/"
        f"{space_id or 'unknown-space'}/tree/main"
    )
    print(agent_code)

    # 2. Fetch Questions
    print(
        f"Fetching questions from: {questions_url}"
    )
    try:
        response = requests.get(
            questions_url, timeout=15
        )
        response.raise_for_status()
        questions_data = response.json()
        if not questions_data:
            print("Fetched questions list is empty.")
            return (
                "Fetched questions list is empty "
                "or invalid format.",
                None,
            )
        print(
            f"Fetched {len(questions_data)} "
            f"questions."
        )
    except requests.exceptions.RequestException as e:
        print(f"Error fetching questions: {e}")
        return f"Error fetching questions: {e}", None
    except requests.exceptions.JSONDecodeError as e:
        print(
            "Error decoding JSON from questions "
            f"endpoint: {e}"
        )
        print(f"Response text: {response.text[:500]}")
        return (
            "Error decoding server response "
            f"for questions: {e}",
            None,
        )
    except Exception as e:
        print(
            "Unexpected error fetching "
            f"questions: {e}"
        )
        return (
            "Unexpected error fetching "
            f"questions: {e}",
            None,
        )

    # 3. Run Agent on each question
    results_log = []
    answers_payload = []
    total = len(questions_data)
    print(f"Running agent on {total} questions...")

    for i, item in enumerate(questions_data):
        task_id = item.get("task_id")
        question_text = item.get("question")
        if not task_id or question_text is None:
            print(
                "Skipping item with missing "
                f"task_id or question: {item}"
            )
            continue

        # Check if the question has a file
        file_name = item.get("file_name", "")
        has_file = bool(file_name)

        print(
            f"[{i+1}/{total}] Task {task_id}"
            f"{' (has file)' if has_file else ''}"
        )

        try:
            submitted_answer = agent(
                question_text,
                task_id,
                has_file,
            )
            answers_payload.append(
                {
                    "task_id": task_id,
                    "submitted_answer": (
                        submitted_answer
                    ),
                }
            )
            results_log.append(
                {
                    "Task ID": task_id,
                    "Question": question_text,
                    "Submitted Answer": (
                        submitted_answer
                    ),
                }
            )
        except Exception as e:
            print(
                f"Error on task {task_id}: {e}"
            )
            results_log.append(
                {
                    "Task ID": task_id,
                    "Question": question_text,
                    "Submitted Answer": (
                        f"AGENT ERROR: {e}"
                    ),
                }
            )

    if not answers_payload:
        print(
            "Agent did not produce any answers."
        )
        return (
            "Agent did not produce any answers "
            "to submit.",
            pd.DataFrame(results_log),
        )

    # 4. Prepare Submission
    submission_data = {
        "username": username.strip(),
        "agent_code": agent_code,
        "answers": answers_payload,
    }
    status_update = (
        f"Agent finished. Submitting "
        f"{len(answers_payload)} answers for "
        f"user '{username}'..."
    )
    print(status_update)

    # 5. Submit
    print(
        f"Submitting {len(answers_payload)} "
        f"answers to: {submit_url}"
    )
    try:
        response = requests.post(
            submit_url,
            json=submission_data,
            timeout=60,
        )
        response.raise_for_status()
        result_data = response.json()
        final_status = (
            f"Submission Successful!\n"
            f"User: {result_data.get('username')}\n"
            f"Overall Score: "
            f"{result_data.get('score', 'N/A')}% "
            f"({result_data.get('correct_count', '?')}"
            f"/{result_data.get('total_attempted', '?')}"
            f" correct)\n"
            f"Message: "
            f"{result_data.get('message', 'N/A')}"
        )
        print("Submission successful.")
        results_df = pd.DataFrame(results_log)
        return final_status, results_df

    except requests.exceptions.HTTPError as e:
        error_detail = (
            "Server responded with status "
            f"{e.response.status_code}."
        )
        try:
            error_json = e.response.json()
            error_detail += (
                " Detail: "
                f"{error_json.get('detail', e.response.text)}"
            )
        except requests.exceptions.JSONDecodeError:
            error_detail += (
                f" Response: "
                f"{e.response.text[:500]}"
            )
        status_message = (
            f"Submission Failed: {error_detail}"
        )
        print(status_message)
        results_df = pd.DataFrame(results_log)
        return status_message, results_df

    except requests.exceptions.Timeout:
        status_message = (
            "Submission Failed: Request timed out."
        )
        print(status_message)
        results_df = pd.DataFrame(results_log)
        return status_message, results_df

    except requests.exceptions.RequestException as e:
        status_message = (
            f"Submission Failed: Network error - {e}"
        )
        print(status_message)
        results_df = pd.DataFrame(results_log)
        return status_message, results_df

    except Exception as e:
        status_message = (
            "Unexpected error during "
            f"submission: {e}"
        )
        print(status_message)
        results_df = pd.DataFrame(results_log)
        return status_message, results_df


# --------------------------------------------------
# Gradio UI
# --------------------------------------------------
with gr.Blocks() as demo:
    gr.Markdown("# GAIA Agent Evaluation Runner")
    gr.Markdown(
        """
**Instructions:**
1. Clone this space and customise the agent.
2. Log in with the button below.
3. Click **Run Evaluation & Submit All Answers**.

---
*Processing all 20 questions will take several
minutes. The agent uses web search, Wikipedia,
page fetching, and file download tools.*
        """
    )

    gr.LoginButton()
    run_button = gr.Button(
        "Run Evaluation & Submit All Answers"
    )
    status_output = gr.Textbox(
        label="Run Status / Submission Result",
        lines=5,
        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],
    )

demo.queue()

if __name__ == "__main__":
    print(
        "\n" + "-" * 30
        + " App Starting "
        + "-" * 30
    )
    space_host = os.getenv("SPACE_HOST")
    space_id = os.getenv("SPACE_ID")

    if space_host:
        print(f"✅ SPACE_HOST: {space_host}")
    else:
        print("ℹ️  SPACE_HOST not found.")

    if space_id:
        print(f"✅ SPACE_ID: {space_id}")
    else:
        print("ℹ️  SPACE_ID not found.")

    print("-" * 74 + "\n")
    print("Launching Gradio Interface...")
    demo.launch(debug=True, share=False)