File size: 18,799 Bytes
10e9b7d
7a3173f
c443382
fa3508d
c443382
 
eccf8e4
3c4371f
82deeac
7c03318
10e9b7d
19ef337
 
 
 
 
7c03318
19ef337
7a3173f
f922cd6
c443382
 
 
 
 
 
 
 
 
e80aab9
fa3508d
f922cd6
fa3508d
82deeac
fa3508d
 
 
f922cd6
19ef337
 
f922cd6
 
 
fa3508d
19ef337
 
7c03318
f922cd6
c443382
7a3173f
19ef337
 
 
7c03318
 
 
 
19ef337
 
 
 
7a3173f
7c03318
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fa3508d
 
 
 
 
db2634a
31243f4
f922cd6
 
c443382
fa3508d
f922cd6
fa3508d
f922cd6
c443382
fa3508d
f922cd6
 
 
 
 
 
 
 
 
 
7c03318
f922cd6
19ef337
f922cd6
 
19ef337
 
 
 
 
f922cd6
 
 
 
19ef337
fa3508d
1412e99
f922cd6
fa3508d
f922cd6
 
 
 
7a3173f
fa3508d
f922cd6
 
 
 
19ef337
 
 
 
 
 
 
 
 
f922cd6
19ef337
7c03318
7a3173f
7c03318
fa3508d
7a3173f
f922cd6
 
19ef337
 
 
 
 
 
 
 
 
 
 
db2634a
c443382
7a3173f
f922cd6
7a3173f
fa3508d
7a3173f
c443382
f922cd6
7c03318
 
19ef337
7c03318
f922cd6
 
19ef337
7a3173f
fa3508d
 
c443382
7a3173f
fa3508d
 
c443382
fa3508d
 
c443382
 
 
 
19ef337
 
 
 
 
 
 
 
 
c443382
 
 
 
 
 
 
 
 
 
 
 
 
f922cd6
 
c443382
 
 
f922cd6
 
c443382
f922cd6
c443382
 
 
 
 
19ef337
f922cd6
19ef337
 
 
 
 
f922cd6
 
c443382
 
19ef337
c443382
 
19ef337
 
c443382
 
19ef337
 
 
 
 
7c03318
19ef337
 
f922cd6
 
7c03318
c443382
fa3508d
 
 
 
 
 
c443382
fa3508d
 
c443382
fa3508d
 
c443382
 
fa3508d
 
 
 
 
 
31243f4
 
fa3508d
 
 
c443382
fa3508d
c443382
fa3508d
 
eccf8e4
c443382
7d65c66
fa3508d
 
 
 
 
c443382
fa3508d
 
 
7d65c66
fa3508d
c443382
19ef337
 
fa3508d
 
31243f4
fa3508d
c443382
fa3508d
 
31243f4
fa3508d
c443382
fa3508d
 
c443382
fa3508d
 
19ef337
c443382
19ef337
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fa3508d
c443382
 
 
 
 
 
 
 
fa3508d
c443382
fa3508d
 
 
19ef337
 
 
 
 
 
 
 
 
c443382
 
fa3508d
 
 
 
c443382
fa3508d
 
e80aab9
fa3508d
c443382
e80aab9
fa3508d
 
 
 
 
c443382
 
 
19ef337
 
fa3508d
e80aab9
fa3508d
c443382
fa3508d
 
 
 
c443382
fa3508d
c443382
fa3508d
 
 
 
 
 
 
 
 
0ee0419
e514fd7
fa3508d
e514fd7
7c03318
e514fd7
fa3508d
 
c443382
7c03318
19ef337
e514fd7
e80aab9
 
7e4a06b
e80aab9
c443382
e80aab9
c443382
fa3508d
c443382
e80aab9
31243f4
 
fa3508d
c443382
e80aab9
 
fa3508d
e80aab9
fa3508d
 
 
 
 
 
 
c443382
 
 
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
import os
import re
import time
import traceback
from typing import Optional

import requests
import pandas as pd
import gradio as gr
from bs4 import BeautifulSoup

from smolagents import (
    ToolCallingAgent,
    OpenAIModel,
    VisitWebpageTool,
    PythonInterpreterTool,
    tool,
)

# Harmless on CPU hardware; avoids "No @spaces.GPU function detected" on ZeroGPU.
try:
    import spaces

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


# =========================================================
# CONFIGURATION (GROQ ONLY)
# =========================================================

GROQ_API_URL = "https://api.groq.com/openai/v1"
GAIA_API_URL = "https://agents-course-unit4-scoring.hf.space"

MODEL_CANDIDATES = [
    "openai/gpt-oss-120b",
    "qwen/qwen3.8-27b",
    "openai/gpt-oss-20b",
]

REQUEST_TIMEOUT = 60
SLEEP_BETWEEN_QUESTIONS = 5
MAX_ATTEMPTS = 6
RATE_LIMIT_WAIT = 65
FALLBACK_ANSWER = "unknown"
FILES_DIR = "/tmp/gaia_files"

UNSOLVABLE_EXTENSIONS = (".mp3", ".wav", ".png", ".jpg", ".jpeg", ".gif", ".mp4")
UNSOLVABLE_PATTERNS = ("youtube.com", "youtu.be")

HTTP_HEADERS = {
    "User-Agent": "GAIA-Agent-Course/1.0 (educational project; contact: huggingface.co)"
}


class AllModelsExhausted(Exception):
    pass


# =========================================================
# TOOLS
# =========================================================

@tool
def wikipedia_search(query: str) -> str:
    """Search English Wikipedia and return the best matching page titles with short snippets.

    Args:
        query: The search terms, for example "Mercedes Sosa discography".
    """
    try:
        r = requests.get(
            "https://en.wikipedia.org/w/api.php",
            params={
                "action": "query",
                "list": "search",
                "srsearch": query,
                "format": "json",
                "srlimit": 6,
            },
            headers=HTTP_HEADERS,
            timeout=30,
        )
        r.raise_for_status()
        hits = r.json().get("query", {}).get("search", [])
        if not hits:
            return "No Wikipedia results. Try different search terms."
        lines = []
        for h in hits:
            snippet = re.sub(r"<[^>]+>", "", h.get("snippet", ""))
            lines.append(f"- {h['title']}: {snippet}")
        return "\n".join(lines)
    except Exception as e:
        return f"Wikipedia search error: {e}"


@tool
def wikipedia_page(title: str, start: int = 0) -> str:
    """Read an English Wikipedia page as plain text, including tables (rows shown with | separators).
    Returns up to 7000 characters. If the page is longer, call again with a larger start value.

    Args:
        title: The exact Wikipedia page title, for example "Mercedes Sosa".
        start: Character offset to start reading from. Use 0 first.
    """
    try:
        r = requests.get(
            "https://en.wikipedia.org/w/index.php",
            params={"title": title, "action": "render"},
            headers=HTTP_HEADERS,
            timeout=30,
        )
        r.raise_for_status()
        soup = BeautifulSoup(r.text, "html.parser")

        for el in soup.select("sup, style, script, .reference, .mw-editsection, .navbox, .hatnote, .noprint"):
            el.decompose()

        # Turn tables into "cell | cell | cell" rows
        for table in soup.find_all("table"):
            rows = []
            for tr in table.find_all("tr"):
                cells = [c.get_text(" ", strip=True) for c in tr.find_all(["th", "td"])]
                if cells:
                    rows.append(" | ".join(cells))
            table.replace_with(soup.new_string("\n" + "\n".join(rows) + "\n"))

        text = soup.get_text("\n")
        text = re.sub(r"\n\s*\n+", "\n", text).strip()
        if not text:
            return "Page is empty or not found. Use wikipedia_search to find the exact title."

        start = max(int(start or 0), 0)
        chunk = text[start:start + 7000]
        more = "" if start + 7000 >= len(text) else f"\n[... more text; call again with start={start + 7000}]"
        return chunk + more
    except Exception as e:
        return f"Wikipedia page error: {e}. Use wikipedia_search to find the exact title."


@tool
def web_search(query: str) -> str:
    """Search the web and return titles, links and snippets of the top results.

    Args:
        query: The search query.
    """
    # 1. Tavily (optional, set TAVILY_API_KEY in Space Secrets; free tier available)
    tavily_key = os.environ.get("TAVILY_API_KEY")
    if tavily_key:
        try:
            r = requests.post(
                "https://api.tavily.com/search",
                json={"api_key": tavily_key, "query": query, "max_results": 5},
                timeout=30,
            )
            r.raise_for_status()
            results = r.json().get("results", [])
            if results:
                return "\n\n".join(
                    f"{x.get('title', '')}\n{x.get('url', '')}\n{x.get('content', '')[:500]}"
                    for x in results
                )
        except Exception as e:
            print(f"Tavily failed: {e}")

    # 2. DuckDuckGo with several backends
    try:
        try:
            from ddgs import DDGS
        except ImportError:
            from duckduckgo_search import DDGS
    except ImportError:
        return "Search library not installed. Use wikipedia_search or visit_webpage instead."

    for backend in ("auto", "html", "lite"):
        try:
            results = DDGS().text(query, max_results=5, backend=backend)
            if results:
                return "\n\n".join(
                    f"{x.get('title', '')}\n{x.get('href', '')}\n{x.get('body', '')[:500]}"
                    for x in results
                )
        except Exception as e:
            print(f"DDG backend {backend} failed: {type(e).__name__}: {str(e)[:100]}")
            time.sleep(1)

    return ("Web search returned nothing. Do NOT repeat the same search. "
            "Use wikipedia_search / wikipedia_page, or visit_webpage on a known URL.")


# =========================================================
# AGENT
# =========================================================

class BasicAgent:

    def __init__(self):
        self.api_key = os.environ.get("GROQ_API_KEY")
        if not self.api_key:
            raise RuntimeError("GROQ_API_KEY is missing. Add it in Space Secrets.")

        r = requests.get(
            f"{GROQ_API_URL}/models",
            headers={"Authorization": f"Bearer {self.api_key}"},
            timeout=REQUEST_TIMEOUT,
        )
        r.raise_for_status()
        available = {m["id"] for m in r.json().get("data", [])}
        print("Groq models available:", sorted(available))

        self.models = [m for m in MODEL_CANDIDATES if m in available]
        if not self.models:
            raise RuntimeError(
                f"None of {MODEL_CANDIDATES} are available. Got: {sorted(available)}"
            )

        self.exhausted = set()
        self.model_index = 0
        self.agent = self._build_agent(self.models[0])
        print("GROQ AGENT INITIALIZED SUCCESSFULLY")

    @property
    def current_model(self) -> str:
        return self.models[self.model_index]

    def _build_agent(self, model_id: str) -> ToolCallingAgent:
        print(f"Using model: {model_id}")

        extra = {}
        if "gpt-oss" in model_id:
            extra["reasoning_effort"] = "low"

        model = OpenAIModel(
            model_id=model_id,
            api_base=GROQ_API_URL,
            api_key=self.api_key,
            max_tokens=3000,
            client_kwargs={"timeout": 120, "max_retries": 1},
            **extra,
        )

        try:
            visit = VisitWebpageTool(max_output_length=4000)
        except TypeError:
            visit = VisitWebpageTool()
        try:
            python_tool = PythonInterpreterTool(
                authorized_imports=[
                    "math", "statistics", "datetime", "collections", "re",
                    "json", "csv", "itertools", "pandas", "numpy",
                ]
            )
        except TypeError:
            python_tool = PythonInterpreterTool()

        return ToolCallingAgent(
            tools=[wikipedia_search, wikipedia_page, web_search, visit, python_tool],
            model=model,
            max_steps=8,
            verbosity_level=1,
        )

    def switch_model(self):
        for _ in range(len(self.models)):
            self.model_index = (self.model_index + 1) % len(self.models)
            if self.current_model not in self.exhausted:
                self.agent = self._build_agent(self.current_model)
                return
        raise AllModelsExhausted("All Groq models reached their daily token limit.")

    def mark_exhausted_and_switch(self):
        self.exhausted.add(self.current_model)
        print(f"Daily limit reached for {self.current_model}. Exhausted: {self.exhausted}")
        self.switch_model()

    def __call__(self, question: str, file_context: str = "") -> str:
        prompt = f"""
You are solving a GAIA benchmark question. Be efficient: use as few steps as possible.

QUESTION:
{question}
{file_context}
RULES:
- For anything that Wikipedia can answer, use wikipedia_search then wikipedia_page (it also shows tables). Use the exact page title.
- Use web_search for other facts. If a search fails, never repeat the same query: change tool or wording.
- If a file path is given above, read it with the python tool (pandas for Excel/CSV).
- Use the python tool for any calculation, counting, sorting or text manipulation.
- Respect exact wording, spelling, units, dates and the requested format.
- Never invent facts.
- Finish by calling final_answer with ONLY the answer: no explanation, no markdown, no units unless asked.
"""
        result = self.agent.run(prompt)
        answer = str(result).strip()
        answer = re.sub(r"^(final answer|answer)\s*:\s*", "", answer, flags=re.IGNORECASE)

        if not answer:
            raise RuntimeError("Agent returned an empty answer.")
        return answer


# =========================================================
# HELPERS
# =========================================================

def should_skip(question: str, file_name: str) -> bool:
    q = question.lower()
    if any(p in q for p in UNSOLVABLE_PATTERNS):
        return True
    if file_name and file_name.lower().endswith(UNSOLVABLE_EXTENSIONS):
        return True
    return False


def get_file_context(task_id: str, file_name: str) -> str:
    if not file_name:
        return ""
    try:
        os.makedirs(FILES_DIR, exist_ok=True)
        path = os.path.join(FILES_DIR, f"{task_id}_{file_name}")
        r = requests.get(f"{GAIA_API_URL}/files/{task_id}", timeout=REQUEST_TIMEOUT)
        r.raise_for_status()
        with open(path, "wb") as f:
            f.write(r.content)

        ext = os.path.splitext(file_name)[1].lower()
        if ext in (".txt", ".csv", ".json", ".py", ".md", ".xml", ".html"):
            text = r.content.decode("utf-8", errors="replace")[:3000]
            return f"\nATTACHED FILE saved at {path}. Start of content:\n{text}\n"
        if ext in (".xlsx", ".xls"):
            df = pd.read_excel(path)
            return (
                f"\nATTACHED FILE saved at {path}. First rows:\n"
                f"{df.head(15).to_string()}\n"
            )
        return f"\nATTACHED FILE saved at {path} (type {ext}).\n"
    except Exception as e:
        print(f"Could not fetch file for {task_id}: {e}")
        return ""


def classify_error(error: Exception) -> str:
    text = f"{type(error).__name__} {error}".lower()
    if "tokens per day" in text or "(tpd)" in text:
        return "daily_limit"
    if "429" in text or "rate limit" in text or "413" in text or "tokens per minute" in text:
        return "minute_limit"
    return "other"


def solve_with_retries(agent: BasicAgent, question: str, file_context: str) -> str:
    last_error = None
    for attempt in range(1, MAX_ATTEMPTS + 1):
        try:
            return agent(question, file_context)
        except AllModelsExhausted:
            raise
        except Exception as e:
            last_error = e
            kind = classify_error(e)
            print(f"Attempt {attempt}/{MAX_ATTEMPTS} failed ({kind}): "
                  f"{type(e).__name__}: {str(e)[:250]}")

            if kind == "daily_limit":
                agent.mark_exhausted_and_switch()
            elif kind == "minute_limit":
                print(f"Per-minute limit. Waiting {RATE_LIMIT_WAIT}s...")
                time.sleep(RATE_LIMIT_WAIT)
            else:
                agent.switch_model()
    raise last_error


# =========================================================
# GAIA EVALUATION
# =========================================================

def run_and_submit_all(profile: Optional[gr.OAuthProfile], progress=gr.Progress()):

    if profile is None:
        return "Please log in to Hugging Face first.", pd.DataFrame()

    username = profile.username
    space_id = os.getenv("SPACE_ID", "mohamedazelmad/Final_Assignment_Template")
    agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"

    questions_url = f"{GAIA_API_URL}/questions"
    submit_url = f"{GAIA_API_URL}/submit"

    print(f"Logged in as: {username}")

    try:
        agent = BasicAgent()
    except Exception as error:
        traceback.print_exc()
        return (
            f"MODEL INITIALIZATION FAILED:\n{type(error).__name__}: {error}\n\n"
            f"No answers were submitted.",
            pd.DataFrame(),
        )

    try:
        response = requests.get(questions_url, timeout=REQUEST_TIMEOUT)
        response.raise_for_status()
        questions = response.json()
        if not isinstance(questions, list) or not questions:
            raise RuntimeError("GAIA returned an empty or invalid question list.")
    except Exception as error:
        traceback.print_exc()
        return f"QUESTION FETCH FAILED:\n{type(error).__name__}: {error}", pd.DataFrame()

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

    answers_payload = []
    results_log = []
    failed = 0
    skipped = 0
    stopped_early = False

    for index, item in enumerate(questions):
        task_id = item.get("task_id")
        question = item.get("question")
        file_name = item.get("file_name", "")

        if not task_id or not question:
            continue

        print(f"\nSolving question {index + 1}/{len(questions)} | {task_id}")
        progress(
            (index + 1) / len(questions),
            desc=f"Solving question {index + 1}/{len(questions)}",
        )

        if should_skip(question, file_name):
            answer = FALLBACK_ANSWER
            status = "Skipped (needs video/audio/image)"
            skipped += 1
        else:
            file_context = get_file_context(task_id, file_name)
            try:
                answer = solve_with_retries(agent, question, file_context)
                status = f"Answered ({agent.current_model})"
            except AllModelsExhausted:
                stopped_early = True
                break
            except Exception as error:
                traceback.print_exc()
                answer = FALLBACK_ANSWER
                status = f"FAILED: {type(error).__name__}: {str(error)[:200]}"
                failed += 1

        answers_payload.append({"task_id": task_id, "submitted_answer": answer})
        results_log.append({
            "Task ID": task_id,
            "Question": question,
            "Submitted Answer": answer,
            "Status": status,
        })
        print(f"Answer: {answer[:250]}")

        time.sleep(SLEEP_BETWEEN_QUESTIONS)

    results_df = pd.DataFrame(results_log)

    if stopped_early:
        return (
            "STOPPED: all Groq models reached their daily token limit.\n\n"
            f"Answered so far: {len(answers_payload)}/{len(questions)}\n"
            "Nothing was submitted. Wait for the quota to reset (check "
            "console.groq.com) and run again.",
            results_df,
        )

    if not answers_payload:
        return "No answers were generated. Nothing submitted.", results_df

    submission_data = {
        "username": username,
        "agent_code": agent_code,
        "answers": answers_payload,
    }

    try:
        progress(1.0, desc="Submitting answers to GAIA...")
        response = requests.post(submit_url, json=submission_data, timeout=120)
        response.raise_for_status()
        result = response.json()

        message = (
            "SUBMISSION SUCCESSFUL!\n\n"
            f"Username: {result.get('username', username)}\n"
            f"Score: {result.get('score', 'N/A')}%\n"
            f"Correct answers: {result.get('correct_count', 'N/A')}/"
            f"{result.get('total_attempted', len(answers_payload))}\n"
            f"Skipped (video/audio/image): {skipped}\n"
            f"Failed (fallback answer): {failed}\n"
            f"Message: {result.get('message', 'Evaluation completed.')}"
        )
        print(message)
        return message, results_df

    except Exception as error:
        traceback.print_exc()
        return (
            f"SUBMISSION FAILED:\n{type(error).__name__}: {error}\n\n"
            "The answers were generated, but submission was not confirmed.",
            results_df,
        )


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

with gr.Blocks(title="GAIA Agent Evaluation") as demo:

    gr.Markdown(
        """
        # GAIA Final Assignment — Research Agent

        Powered by Groq (automatic model switching), Wikipedia and web search.

        **Before running:**
        - Log in with your Hugging Face account.
        - Make sure `GROQ_API_KEY` is set in Space Secrets.
        - Optional: add `TAVILY_API_KEY` for more reliable web search.
        - The run can take 20–40 minutes. Keep this tab open.
        """
    )

    gr.LoginButton()

    run_button = gr.Button("Run Evaluation & Submit All Answers", variant="primary")

    status_output = gr.Textbox(label="Evaluation Status", lines=8, interactive=False)

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

    run_button.click(
        fn=run_and_submit_all,
        outputs=[status_output, results_table],
        concurrency_limit=1,
    )


if __name__ == "__main__":
    print("=" * 50)
    print("GAIA RESEARCH AGENT STARTING")
    print("=" * 50)
    print(f"Space ID: {os.getenv('SPACE_ID', 'Unknown')}")

    demo.queue().launch(
        server_name="0.0.0.0",
        server_port=7860,
        ssr_mode=False,
    )