File size: 15,189 Bytes
10e9b7d
293c15d
d622670
 
 
 
10e9b7d
eccf8e4
3c4371f
d622670
293c15d
 
 
 
 
 
 
 
 
10e9b7d
3db6293
98b84f1
d622670
a6cb456
d622670
 
 
 
98b84f1
d622670
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a54ce93
 
 
 
d622670
 
 
 
 
 
a97fd15
d622670
 
 
 
 
a97fd15
d622670
 
 
a97fd15
 
d622670
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98b84f1
 
d622670
 
 
 
 
 
 
 
 
 
 
98b84f1
 
d622670
 
 
e80aab9
293c15d
d622670
a97fd15
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
293c15d
d622670
a97fd15
 
293c15d
 
d622670
31243f4
a97fd15
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
293c15d
a97fd15
 
 
 
293c15d
 
 
a97fd15
d622670
a97fd15
 
293c15d
 
a97fd15
 
31243f4
d622670
 
 
 
 
293c15d
d622670
 
a97fd15
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
293c15d
 
 
d622670
 
 
293c15d
 
d622670
 
293c15d
d622670
 
 
 
293c15d
 
 
d622670
 
293c15d
 
 
d622670
293c15d
d622670
293c15d
 
d622670
 
 
 
 
 
 
 
 
 
293c15d
 
 
 
d622670
98b84f1
 
 
d622670
98b84f1
293c15d
d622670
 
293c15d
d622670
98b84f1
d622670
a54ce93
293c15d
 
 
d622670
 
 
 
 
 
 
 
 
 
 
293c15d
a54ce93
 
d622670
 
 
 
 
 
 
 
 
293c15d
3c4371f
293c15d
 
 
 
 
98b84f1
 
e80aab9
31243f4
293c15d
31243f4
 
36ed51a
3c4371f
eccf8e4
d622670
7d65c66
31243f4
7d65c66
293c15d
e80aab9
d622670
293c15d
31243f4
d622670
31243f4
 
d622670
 
 
 
 
 
 
 
 
 
293c15d
 
31243f4
7d65c66
e80aab9
d622670
e80aab9
293c15d
 
 
 
 
 
e80aab9
293c15d
7d65c66
293c15d
e80aab9
 
 
293c15d
0ee0419
d622670
 
 
e80aab9
7e4a06b
31243f4
9088b99
7d65c66
293c15d
e80aab9
 
293c15d
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
import os
import re
import json
import time
import base64
import threading
import gradio as gr
import requests
import pandas as pd
from smolagents import CodeAgent, OpenAIServerModel, VisitWebpageTool, tool

try:  # ZeroGPU Spaces require at least one @spaces.GPU function to start
    import spaces

    @spaces.GPU
    def _gpu_placeholder():
        return None
except Exception:
    pass

DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
GEMINI_BASE = "https://generativelanguage.googleapis.com/v1beta/openai/"
GEMINI_NATIVE = "https://generativelanguage.googleapis.com/v1beta/models"
MODEL_ID = os.getenv("MODEL_ID", "gemini-flash-lite-latest")
MIN_SECONDS_BETWEEN_CALLS = float(os.getenv("MIN_SECONDS_BETWEEN_CALLS", "6"))  # free tier: 15 RPM
FILES_DIR = "/tmp/task_files"
CACHE_PATH = "/tmp/answers_cache.json"
os.makedirs(FILES_DIR, exist_ok=True)

# ---------------------------------------------------------------- rate limiting
_lock = threading.Lock()
_last_call = [0.0]


def _throttle():
    with _lock:
        wait = MIN_SECONDS_BETWEEN_CALLS - (time.time() - _last_call[0])
        if wait > 0:
            time.sleep(wait)
        _last_call[0] = time.time()


def _is_rate_limit(e: Exception) -> bool:
    s = str(e).lower()
    return "429" in s or "rate" in s or "quota" in s or "resource_exhausted" in s


class ThrottledGeminiModel(OpenAIServerModel):
    """Gemini via its OpenAI-compatible endpoint, spaced out and retried to fit the free tier."""

    def generate(self, *args, **kwargs):
        for attempt in range(8):
            _throttle()
            try:
                out = super().generate(*args, **kwargs)
                if not (out.content or "").strip() and attempt < 7:
                    continue  # empty reply: ask again
                return out
            except Exception as e:
                if not _is_rate_limit(e) or attempt == 7:
                    raise
                time.sleep(20 * (attempt + 1))


def _gemini_native(parts: list, tools: list | None = None, retries: int = 8) -> str:
    """Calls Gemini's native generateContent API (needed for audio, YouTube and search grounding)."""
    body = {"contents": [{"role": "user", "parts": parts}]}
    if tools:
        body["tools"] = tools
    url = f"{GEMINI_NATIVE}/{MODEL_ID}:generateContent"
    for attempt in range(retries):
        _throttle()
        r = requests.post(url, params={"key": os.getenv("GEMINI_API_KEY")}, json=body, timeout=300)
        if r.status_code == 429 or r.status_code >= 500:
            if attempt < retries - 1:
                time.sleep(20 * (attempt + 1))
            continue
        r.raise_for_status()
        cands = r.json().get("candidates") or []
        if not cands:
            return "No response."
        return "".join(p.get("text", "") for p in cands[0].get("content", {}).get("parts", []))
    return "Model unavailable (rate limited)."


# ---------------------------------------------------------------- attachments
def fetch_task_file(task_id: str, file_name: str) -> str | None:
    """Downloads a task's attachment. The scoring API's /files route is tried first; it currently
    returns 404, so the same attachment is fetched from the gated GAIA dataset (attachment only)."""
    if not file_name:
        return None
    path = os.path.join(FILES_DIR, file_name)
    if os.path.exists(path):
        return path
    try:
        r = requests.get(f"{DEFAULT_API_URL}/files/{task_id}", timeout=60)
        if r.status_code == 200 and r.content:
            open(path, "wb").write(r.content)
            return path
    except Exception:
        pass
    try:
        from huggingface_hub import hf_hub_download

        return hf_hub_download(
            repo_id="gaia-benchmark/GAIA",
            repo_type="dataset",
            filename=f"2023/validation/{file_name}",
            token=os.getenv("HF_TOKEN"),
            local_dir=FILES_DIR,
        )
    except Exception as e:
        print(f"Could not fetch attachment {file_name}: {e}")
        return None


def file_preview(path: str) -> str:
    low = path.lower()
    try:
        if low.endswith((".py", ".txt", ".csv", ".json", ".md")):
            return open(path, encoding="utf-8", errors="replace").read()[:6000]
        if low.endswith((".xlsx", ".xls")):
            sheets = pd.read_excel(path, sheet_name=None)
            return "\n\n".join(f"[sheet {k}]\n{v.to_string()}" for k, v in sheets.items())[:8000]
    except Exception as e:
        return f"(preview failed: {e})"
    return ""


_MIME = {".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".webp": "image/webp",
         ".mp3": "audio/mp3", ".wav": "audio/wav", ".m4a": "audio/mp4", ".flac": "audio/flac",
         ".pdf": "application/pdf"}


# ---------------------------------------------------------------- tools
_grounding_ok = [True]


def _wiki_search(query: str) -> str:
    r = requests.get(
        "https://en.wikipedia.org/w/api.php",
        params={"action": "query", "list": "search", "srsearch": query, "srlimit": 6, "format": "json"},
        headers={"User-Agent": "gaia-agent-course/1.0"},
        timeout=60,
    ).json()
    hits = r.get("query", {}).get("search", [])
    return "\n\n".join(
        f"Wikipedia: {h['title']}\n{re.sub(r'<[^>]+>', '', h['snippet'])}" for h in hits
    )


@tool
def web_search(query: str) -> str:
    """Searches the web and returns results with source URLs (plus matching Wikipedia articles).
    Use specific queries. Open the returned URLs with visit_webpage or wikipedia_page to verify details.

    Args:
        query: The search query.
    """
    out = []
    if _grounding_ok[0]:
        try:
            text = _gemini_native(
                [{"text": f"Search the web and report the facts relevant to: {query}\n"
                          "Quote exact numbers, names and dates, and list the source URLs."}],
                tools=[{"google_search": {}}],
                retries=1,
            )
            if text and "rate limited" not in text:
                out.append(text[:5000])
            else:
                _grounding_ok[0] = False  # quota exhausted: stop trying for this run
        except Exception as e:
            print(f"grounded search failed: {e}")
            _grounding_ok[0] = False
    if not out:
        try:
            from duckduckgo_search import DDGS

            res = DDGS().text(query, max_results=6)
            out.append("\n\n".join(f"{r['title']}\n{r['href']}\n{r['body']}" for r in res))
        except Exception as e:
            print(f"ddg failed: {e}")
    try:
        out.append(_wiki_search(query))
    except Exception:
        pass
    return "\n\n---\n\n".join(o for o in out if o) or "No results."


@tool
def wikipedia_page(title: str, section: str = "") -> str:
    """Returns the wikitext of an English Wikipedia page (tables and lists included). Good for
    discographies, rosters and statistics. Long pages are cut, so pass section (a heading such as
    'Discography' or 'Studio albums') to get that section in full; the list of headings is always shown.

    Args:
        title: The exact Wikipedia article title, e.g. 'Mercedes Sosa'.
        section: Optional heading to return in full (case-insensitive substring match).
    """
    r = requests.get(
        "https://en.wikipedia.org/w/api.php",
        params={"action": "parse", "page": title, "prop": "wikitext", "format": "json", "redirects": 1},
        headers={"User-Agent": "gaia-agent-course/1.0"},
        timeout=60,
    )
    data = r.json()
    if "error" in data:
        return f"Page not found. Matching articles:\n{_wiki_search(title)}"
    text = data["parse"]["wikitext"]["*"]
    heads = re.findall(r"^(=+)\s*(.+?)\s*\1\s*$", text, flags=re.M)
    toc = "Sections: " + " | ".join(h[1] for h in heads)
    if section:
        m = None
        for lvl, h in heads:
            if section.lower() in h.lower():
                m = re.search(rf"^{lvl}\s*{re.escape(h)}\s*{lvl}\s*$", text, flags=re.M)
                break
        if m:
            rest = text[m.end():]
            nxt = re.search(rf"^={{2,{len(lvl)}}}[^=].*?={{2,{len(lvl)}}}\s*$", rest, flags=re.M)
            return toc + "\n\n" + rest[: nxt.start() if nxt else len(rest)][:25000]
        return toc + f"\n\n(No section matching '{section}'.)"
    return toc + "\n\n" + text[:15000]


@tool
def analyze_file(path: str, question: str) -> str:
    """Asks a multimodal model about a local image, audio or PDF file (e.g. describe a chess
    board position square by square, transcribe an audio recording, read a document).

    Args:
        path: Local path of the file.
        question: What to ask about the file.
    """
    ext = os.path.splitext(path)[1].lower()
    mime = _MIME.get(ext, "application/octet-stream")
    data = base64.b64encode(open(path, "rb").read()).decode()
    return _gemini_native([{"inline_data": {"mime_type": mime, "data": data}}, {"text": question}])


@tool
def youtube_video(url: str, question: str) -> str:
    """Watches a YouTube video (images and audio) and answers a question about it.

    Args:
        url: The YouTube video URL.
        question: What to find out from the video.
    """
    return _gemini_native([{"file_data": {"file_uri": url}}, {"text": question}])


INSTRUCTIONS = """You answer GAIA benchmark questions. Work step by step with tools; never guess.
- Facts: web_search, then open the best sources with visit_webpage or wikipedia_page and read the exact data.
  For Wikipedia questions prefer wikipedia_page. Count or compute with Python code, not in your head.
- Attachments: the prompt gives the local path. Read .py/.xlsx/.csv with Python (pandas for Excel);
  for images, audio and PDFs use analyze_file. For YouTube links use youtube_video.
- Read the question literally (it may be reversed text, a puzzle, or have tricky constraints) and
  check your answer against every constraint before finishing.
- Call final_answer with ONLY the answer: a number (no units or thousands separators unless asked),
  a few words (no articles or abbreviations unless asked), or a comma-separated list in the requested
  order and format. Never include 'FINAL ANSWER', explanations or trailing punctuation."""


class GaiaAgent:
    def __init__(self):
        model = ThrottledGeminiModel(
            model_id=MODEL_ID,
            api_base=GEMINI_BASE,
            api_key=os.getenv("GEMINI_API_KEY"),
            client_kwargs={"max_retries": 2},
        )
        self.agent = CodeAgent(
            tools=[web_search, wikipedia_page, VisitWebpageTool(max_output_length=12000),
                   analyze_file, youtube_video],
            model=model,
            additional_authorized_imports=["*"],
            max_steps=10,
            max_print_outputs_length=6000,
            code_block_tags="markdown",
            instructions=INSTRUCTIONS,
        )

    def __call__(self, question: str, task_id: str = "", file_name: str = "") -> str:
        prompt = f"Question: {question}"
        if file_name:
            path = fetch_task_file(task_id, file_name)
            if path:
                prompt += f"\n\nAttached file '{file_name}' is saved at: {path}"
                prev = file_preview(path)
                if prev:
                    prompt += f"\nFile contents preview:\n{prev}"
            else:
                prompt += f"\n\n(The attached file '{file_name}' could not be downloaded.)"
        ans = str(self.agent.run(prompt)).strip()
        if not ans or "```" in ans or re.search(r"\w+\(.*\)", ans) and "=" in ans or ans == "None":
            ans = str(self.agent.run(prompt)).strip()  # answer looked like code: one more attempt
        ans = re.sub(r"(?i)^final answer\s*:\s*", "", ans).strip().strip('"').strip()
        return ans.rstrip(".")


def _load_cache() -> dict:
    try:
        return json.load(open(CACHE_PATH))
    except Exception:
        return {}


def run_and_submit_all(profile: gr.OAuthProfile | None):
    space_id = os.getenv("SPACE_ID")
    if not profile:
        return "Please Login to Hugging Face with the button.", None
    username = f"{profile.username}"
    if not os.getenv("GEMINI_API_KEY"):
        return "GEMINI_API_KEY secret is missing in the Space settings.", None

    try:
        agent = GaiaAgent()
    except Exception as e:
        return f"Error initializing agent: {e}", None
    agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"

    try:
        response = requests.get(f"{DEFAULT_API_URL}/questions", timeout=30)
        response.raise_for_status()
        questions_data = response.json()
    except Exception as e:
        return f"Error fetching questions: {e}", None

    cache = _load_cache()  # answers from an interrupted earlier run in this session are reused
    results_log, answers_payload = [], []
    for item in questions_data:
        task_id, question_text = item.get("task_id"), item.get("question")
        if not task_id or question_text is None:
            continue
        if task_id in cache and not cache[task_id].startswith("AGENT ERROR"):
            ans = cache[task_id]
        else:
            try:
                ans = agent(question_text, task_id, item.get("file_name", ""))
            except Exception as e:
                ans = f"AGENT ERROR: {e}"
            cache[task_id] = ans
            json.dump(cache, open(CACHE_PATH, "w"))
        print(f"[{task_id}] -> {ans}")
        answers_payload.append({"task_id": task_id, "submitted_answer": ans})
        results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": ans})

    submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
    try:
        response = requests.post(f"{DEFAULT_API_URL}/submit", json=submission_data, timeout=120)
        response.raise_for_status()
        r = response.json()
        status = (
            f"Submission Successful!\nUser: {r.get('username')}\n"
            f"Overall Score: {r.get('score', 'N/A')}% "
            f"({r.get('correct_count', '?')}/{r.get('total_attempted', '?')} correct)\n"
            f"Message: {r.get('message', '')}"
        )
        return status, pd.DataFrame(results_log)
    except Exception as e:
        return f"Submission Failed: {e}", pd.DataFrame(results_log)


with gr.Blocks() as demo:
    gr.Markdown("# GAIA Agent Evaluation Runner")
    gr.Markdown(
        "smolagents CodeAgent on Gemini (free tier) with web search, Wikipedia, webpage, file and video tools.\n\n"
        "1. Add GEMINI_API_KEY (and HF_TOKEN with gated-repo read access) as Space secrets.\n"
        "2. Log in below.\n3. Click run: the agent answers all questions and submits."
    )
    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])

if __name__ == "__main__":
    demo.launch(debug=True, share=False)