File size: 6,667 Bytes
3d9164d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
234def3
 
 
 
3d9164d
 
234def3
 
 
 
 
 
 
 
 
 
 
3d9164d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
234def3
3d9164d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
234def3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""GAIA level-1 agent for the Hugging Face Agents Course (Unit 4 final assignment).

Built on smolagents' CodeAgent. The LLM backend goes through LiteLLM, so any
provider works by setting MODEL_ID and that provider's API key env var, e.g.
  MODEL_ID=anthropic/claude-sonnet-5-5   + ANTHROPIC_API_KEY
  MODEL_ID=gemini/gemini-2.5-flash       + GEMINI_API_KEY
  MODEL_ID=openai/gpt-4.1                + OPENAI_API_KEY
"""

import base64
import io
import mimetypes
import os
import re
import tempfile

import requests
from dotenv import load_dotenv
from smolagents import (
    CodeAgent,
    DuckDuckGoSearchTool,
    LiteLLMModel,
    VisitWebpageTool,
    WikipediaSearchTool,
    tool,
)

load_dotenv()

API_URL = "https://agents-course-unit4-scoring.hf.space"
MODEL_ID = os.getenv("MODEL_ID", "anthropic/claude-sonnet-5-5")
FILES_DIR = os.path.join(tempfile.gettempdir(), "gaia_files")


def download_task_file(task_id: str, file_name: str) -> str | None:
    """Download the attachment for a task and return its local path."""
    if not file_name:
        return None
    os.makedirs(FILES_DIR, exist_ok=True)
    path = os.path.join(FILES_DIR, file_name)
    if os.path.exists(path):
        return path
    resp = requests.get(f"{API_URL}/files/{task_id}", timeout=60)
    if resp.ok:
        with open(path, "wb") as f:
            f.write(resp.content)
        return path
    # The scoring server sometimes lacks the attachment; fall back to the same
    # file in the (gated) GAIA dataset. Only the attachment is fetched.
    from huggingface_hub import hf_hub_download

    return hf_hub_download(
        "gaia-benchmark/GAIA",
        f"2023/validation/{file_name}",
        repo_type="dataset",
        local_dir=FILES_DIR,
    )


def _llm_text(messages: list[dict]) -> str:
    import litellm

    resp = litellm.completion(model=MODEL_ID, messages=messages)
    return resp.choices[0].message.content


@tool
def analyze_image(image_path: str, question: str) -> str:
    """Look at a local image file with a vision model and answer a question about it.

    Args:
        image_path: Local path to the image (png, jpg, ...).
        question: What you want to know about the image. Be specific.
    """
    mime = mimetypes.guess_type(image_path)[0] or "image/png"
    with open(image_path, "rb") as f:
        b64 = base64.b64encode(f.read()).decode()
    return _llm_text([
        {
            "role": "user",
            "content": [
                {"type": "image_url", "image_url": {"url": f"data:{mime};base64,{b64}"}},
                {"type": "text", "text": question},
            ],
        }
    ])


@tool
def transcribe_audio(audio_path: str) -> str:
    """Transcribe a local audio file (mp3, wav, ...) to text with Whisper.

    Args:
        audio_path: Local path to the audio file.
    """
    import whisper  # openai-whisper, runs locally on CPU

    model = whisper.load_model(os.getenv("WHISPER_MODEL", "small"))
    return model.transcribe(audio_path)["text"]


@tool
def youtube_transcript(url: str) -> str:
    """Fetch the spoken transcript (captions) of a YouTube video.

    Args:
        url: The YouTube video URL.
    """
    from youtube_transcript_api import YouTubeTranscriptApi

    m = re.search(r"(?:v=|youtu\.be/)([\w-]{11})", url)
    if not m:
        return "Could not parse a video id from the URL."
    try:
        fetched = YouTubeTranscriptApi().fetch(m.group(1))
        return "\n".join(f"[{s.start:.0f}s] {s.text}" for s in fetched)
    except Exception as e:
        return f"Transcript unavailable: {e}"


@tool
def read_excel(path: str) -> str:
    """Read every sheet of an Excel/CSV file and return it as text tables.

    Args:
        path: Local path to the .xlsx / .xls / .csv file.
    """
    import pandas as pd

    if path.lower().endswith(".csv"):
        return pd.read_csv(path).to_string()
    sheets = pd.read_excel(path, sheet_name=None)
    return "\n\n".join(f"## Sheet: {name}\n{df.to_string()}" for name, df in sheets.items())


@tool
def read_text_file(path: str) -> str:
    """Read a local text/code file and return its content.

    Args:
        path: Local path to the file.
    """
    with open(path, encoding="utf-8", errors="replace") as f:
        return f.read()


SYSTEM_HINT = """You are a precise research assistant solving a GAIA benchmark question.
Use the tools to look things up and verify; do not guess when you can check.
Rules for the final answer (it is graded by EXACT MATCH):
- Call final_answer() with ONLY the answer: no explanation, no units unless asked, no "FINAL ANSWER" prefix.
- A number: plain digits, no thousands separators, no $ or % unless asked.
- A string: as few words as possible, no articles, no abbreviations unless asked.
- A list: comma-separated, following any ordering/format the question asks for.
"""


class GaiaAgent:
    def __init__(self):
        model = LiteLLMModel(model_id=MODEL_ID, timeout=180, num_retries=2)
        self.agent = CodeAgent(
            model=model,
            tools=[
                DuckDuckGoSearchTool(max_results=8),
                VisitWebpageTool(max_output_length=60000),
                WikipediaSearchTool(user_agent="gaia-agent (hf agents course)"),
                youtube_transcript,
                analyze_image,
                transcribe_audio,
                read_excel,
                read_text_file,
            ],
            additional_authorized_imports=[
                "pandas", "numpy", "json", "re", "math", "datetime", "collections",
                "itertools", "statistics", "requests", "bs4", "subprocess", "os",
            ],
            max_steps=15,
            verbosity_level=1,
        )

    def __call__(self, question: str, file_path: str | None = None) -> str:
        prompt = SYSTEM_HINT + "\nQuestion:\n" + question
        if file_path:
            prompt += f"\n\nThe attached file is available locally at: {file_path}"
        answer = str(self.agent.run(prompt)).strip()
        answer = re.sub(r"^\s*FINAL ANSWER:\s*", "", answer, flags=re.I).strip()
        if len(answer) > 60 or "\n" in answer or "<" in answer:
            answer = self._shorten(question, answer)
        return answer

    def _shorten(self, question: str, answer: str) -> str:
        """Reduce a wordy agent reply to the bare answer the grader expects."""
        return _llm_text([
            {
                "role": "user",
                "content": SYSTEM_HINT
                + f"\nQuestion:\n{question}\n\nDraft reply:\n{answer}\n\n"
                "Reply with ONLY the final answer extracted from the draft, nothing else.",
            }
        ]).strip()