File size: 21,263 Bytes
ac5211b
 
 
b96ee70
 
 
 
 
 
ac5211b
 
 
 
b96ee70
ac5211b
 
10e9b7d
ac5211b
 
 
 
 
 
 
10e9b7d
3c4371f
ac5211b
 
b96ee70
 
 
 
8d99315
b96ee70
 
ac5211b
 
b96ee70
ac5211b
 
 
 
 
 
 
 
10e9b7d
e80aab9
3db6293
e7a6076
 
b96ee70
ac5211b
 
 
b96ee70
e80aab9
b96ee70
 
 
cb79b9f
 
b96ee70
 
cb79b9f
ac5211b
 
 
 
 
 
b96ee70
 
ac5211b
 
 
 
 
 
 
 
 
b96ee70
ac5211b
 
 
 
 
b96ee70
ac5211b
b96ee70
ac5211b
 
b96ee70
ac5211b
 
 
 
 
b96ee70
ac5211b
 
 
 
b96ee70
ac5211b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b96ee70
 
ac5211b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b96ee70
 
ac5211b
 
b96ee70
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac5211b
 
 
 
b96ee70
 
ac5211b
 
 
 
 
 
 
b96ee70
 
ac5211b
 
 
 
b96ee70
 
 
ac5211b
 
 
 
 
 
 
 
 
 
b96ee70
 
 
ac5211b
 
 
 
 
b96ee70
ac5211b
 
b96ee70
ac5211b
 
b96ee70
 
ac5211b
 
b96ee70
ac5211b
 
 
b96ee70
 
ac5211b
b96ee70
 
 
ac5211b
b96ee70
ac5211b
b96ee70
 
ac5211b
 
 
b96ee70
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac5211b
 
b96ee70
ac5211b
 
 
31243f4
ac5211b
 
 
 
 
 
 
 
 
b96ee70
ac5211b
 
 
31243f4
ac5211b
 
 
 
b96ee70
ac5211b
 
 
b96ee70
 
 
 
ac5211b
b96ee70
ac5211b
 
b96ee70
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8d99315
b96ee70
 
 
 
 
 
 
 
 
 
0a91736
 
 
b96ee70
 
 
 
ac5211b
 
 
 
8d99315
b96ee70
ac5211b
 
b96ee70
ac5211b
b96ee70
ac5211b
b96ee70
ac5211b
 
b96ee70
 
8d99315
 
 
 
 
 
b96ee70
 
8d99315
 
 
ac5211b
b96ee70
ac5211b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3c4371f
ac5211b
 
7e4a06b
ac5211b
3c4371f
7e4a06b
7d65c66
3c4371f
b96ee70
 
e80aab9
31243f4
ac5211b
31243f4
 
36ed51a
3c4371f
eccf8e4
ac5211b
7d65c66
31243f4
7d65c66
ac5211b
 
 
 
 
e80aab9
ac5211b
 
31243f4
ac5211b
31243f4
 
b96ee70
ac5211b
 
 
 
 
 
 
 
31243f4
 
 
 
7d65c66
e80aab9
ac5211b
e80aab9
 
31243f4
e80aab9
 
3c4371f
 
 
e80aab9
ac5211b
e80aab9
ac5211b
 
7d65c66
ac5211b
 
 
b96ee70
 
 
 
 
 
 
 
ac5211b
 
 
 
e80aab9
 
 
b96ee70
0ee0419
e514fd7
b96ee70
 
ac5211b
e514fd7
ac5211b
 
 
b96ee70
 
e514fd7
e80aab9
7e4a06b
b96ee70
 
 
 
 
ac5211b
31243f4
ac5211b
9088b99
7d65c66
e80aab9
ac5211b
 
e80aab9
7d65c66
ac5211b
 
 
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
"""
GAIA Final Assignment agent — Hugging Face Agents Course, Unit 4.

A LangGraph ReAct agent (assistant node <-> tool node loop), the pattern most
course submissions use, backed by Gemini through langchain-google-genai.

Tools: web search (Tavily or DuckDuckGo), Wikipedia (incl. past revisions),
web page reader, task-file download, Gemini-powered media analysis
(image / audio / video / YouTube), Python execution, spreadsheet reader.

Required Space secret:  GEMINI_API_KEY
Recommended secrets:    HF_TOKEN (access to gated gaia-benchmark/GAIA, for attachments),
                        TAVILY_API_KEY (more reliable search than DuckDuckGo on Spaces)
Optional variables:     MODEL_ID (default gemini-3.5-flash-lite), REQUESTS_PER_MINUTE (default 8)
"""

import os
import re
import json
import time
import mimetypes
import subprocess
import tempfile

import gradio as gr
import pandas as pd
import requests

from langchain_core.messages import HumanMessage, SystemMessage
from langchain_core.rate_limiters import InMemoryRateLimiter
from langchain_core.tools import tool
from langchain_google_genai import ChatGoogleGenerativeAI
from langgraph.errors import GraphRecursionError
from langgraph.graph import START, MessagesState, StateGraph
from langgraph.prebuilt import ToolNode, tools_condition

# This Space runs on ZeroGPU hardware, which expects at least one @spaces.GPU function at startup.
# The agent itself needs no GPU (the model is called via API), so this is just a placeholder.
try:
    import spaces

    @spaces.GPU
    def _zero_gpu_placeholder():
        return None
except ImportError:
    pass

# --- Constants ---
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
MODEL_ID = os.getenv("MODEL_ID", "gemini-3.5-flash-lite")
MEDIA_MODEL = os.getenv("MEDIA_MODEL", MODEL_ID)
REQUESTS_PER_MINUTE = float(os.getenv("REQUESTS_PER_MINUTE", "8"))
DOWNLOAD_DIR = os.path.join(tempfile.gettempdir(), "gaia_files")
os.makedirs(DOWNLOAD_DIR, exist_ok=True)
UA = {"User-Agent": "Mozilla/5.0 (GAIA-agent; HF agents course)"}
TASK_FILES: dict = {}  # task_id -> file_name, filled from /questions

# One shared limiter for every Gemini call (agent + media tool) to stay inside the free tier.
RATE_LIMITER = InMemoryRateLimiter(requests_per_second=REQUESTS_PER_MINUTE / 60,
                                   check_every_n_seconds=0.5, max_bucket_size=1)


def _api_key():
    return os.getenv("GEMINI_API_KEY") or os.getenv("GOOGLE_API_KEY")


# =====================================================================
# Tools
# =====================================================================

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

    Args:
        query: The search query. Keep it short and specific.
    """
    tavily_key = os.getenv("TAVILY_API_KEY")
    if tavily_key:
        try:
            r = requests.post(
                "https://api.tavily.com/search",
                json={"api_key": tavily_key, "query": query, "max_results": 6, "search_depth": "advanced"},
                timeout=40,
            )
            r.raise_for_status()
            res = r.json().get("results", [])
            return "\n\n".join(f"[{x['title']}]({x['url']})\n{x.get('content','')}" for x in res) or "No results."
        except Exception as e:  # fall back to DuckDuckGo
            print(f"Tavily failed: {e}")
    from ddgs import DDGS
    for attempt in range(3):
        try:
            res = list(DDGS().text(query, max_results=6))
            if res:
                return "\n\n".join(f"[{x.get('title')}]({x.get('href')})\n{x.get('body','')}" for x in res)
        except Exception as e:
            print(f"DDG attempt {attempt+1} failed: {e}")
            time.sleep(2 + attempt * 3)
    return "Search failed or returned nothing. Try different wording, or use wikipedia_search / visit_webpage."


@tool
def wikipedia_search(query: str) -> str:
    """Search English Wikipedia. Returns matching article titles with short snippets.

    Args:
        query: What to look for on Wikipedia.
    """
    r = requests.get(
        "https://en.wikipedia.org/w/api.php",
        params={"action": "query", "list": "search", "srsearch": query, "format": "json", "srlimit": 8},
        headers=UA, timeout=30,
    )
    hits = r.json().get("query", {}).get("search", [])
    return "\n".join(f"- {h['title']}: {re.sub('<[^>]+>', '', h['snippet'])}" for h in hits) or "No results."


@tool
def wikipedia_page(title: str, as_of: str = "") -> str:
    """Get the full text of an English Wikipedia article (tables rendered as markdown).
    Optionally get the revision as it stood on a given date.

    Args:
        title: Exact article title, e.g. "Mercedes Sosa".
        as_of: Optional ISO date like "2022-12-31"; returns the last revision on or before it.
    """
    from markdownify import markdownify

    params = {"action": "parse", "page": title, "prop": "text", "format": "json", "redirects": 1}
    if as_of:
        rv = requests.get(
            "https://en.wikipedia.org/w/api.php",
            params={"action": "query", "prop": "revisions", "titles": title, "rvlimit": 1,
                    "rvstart": f"{as_of}T23:59:59Z", "rvdir": "older", "rvprop": "ids",
                    "format": "json", "redirects": 1},
            headers=UA, timeout=30,
        ).json()
        pages = rv.get("query", {}).get("pages", {})
        revid = next((p["revisions"][0]["revid"] for p in pages.values() if p.get("revisions")), None)
        if revid:
            params = {"action": "parse", "oldid": revid, "prop": "text", "format": "json"}
    data = requests.get("https://en.wikipedia.org/w/api.php", params=params, headers=UA, timeout=40).json()
    if "error" in data:
        return f"Error: {data['error'].get('info')}. Use wikipedia_search to find the exact title."
    html = data["parse"]["text"]["*"]
    html = re.sub(r"<(style|script)[^>]*>.*?</\1>", "", html, flags=re.S)
    text = re.sub(r"\n{3,}", "\n\n", markdownify(html))
    return text[:40000]


@tool
def visit_webpage(url: str) -> str:
    """Fetch a web page and return its content as markdown text.

    Args:
        url: Full http(s) URL of the page.
    """
    from markdownify import markdownify

    try:
        r = requests.get(url, headers=UA, timeout=30)
        r.raise_for_status()
    except Exception as e:
        return f"Could not fetch {url}: {e}"
    html = re.sub(r"<(style|script|nav|footer)[^>]*>.*?</\1>", "", r.text, flags=re.S | re.I)
    text = re.sub(r"\n{3,}", "\n\n", markdownify(html))
    return text[:40000]


@tool
def download_task_file(task_id: str) -> str:
    """Download the file attached to the current GAIA task and return its local path.
    Use it whenever the question mentions an attached file, image, audio, spreadsheet or code.

    Args:
        task_id: The task_id of the current question.
    """
    r = requests.get(f"{DEFAULT_API_URL}/files/{task_id}", timeout=60)
    file_name = TASK_FILES.get(task_id, "")
    if r.status_code != 200 and file_name:
        # The course endpoint has been returning 404 for attachments; fall back to the
        # official (gated) GAIA validation set. Needs HF_TOKEN with access granted.
        token = os.getenv("HF_TOKEN")
        url = f"https://huggingface.co/datasets/gaia-benchmark/GAIA/resolve/main/2023/validation/{file_name}"
        r = requests.get(url, headers={"Authorization": f"Bearer {token}"} if token else {}, timeout=120)
    if r.status_code != 200:
        return f"The attached file is not available (HTTP {r.status_code}). Answer as best you can without it."
    name = file_name or task_id
    m = re.search(r'filename="?([^";]+)"?', r.headers.get("content-disposition", ""))
    if m:
        name = m.group(1)
    path = os.path.join(DOWNLOAD_DIR, name)
    with open(path, "wb") as f:
        f.write(r.content)
    return path


@tool
def analyze_media(source: str, question: str) -> str:
    """Look at / listen to an image, audio file, video file, PDF or YouTube video and answer
    a question about it. Ask precise questions, e.g. "Transcribe all speech verbatim" or
    "Give the chess position in FEN".

    Args:
        source: Local file path (from download_task_file) or a YouTube / http URL.
        question: What you want to know about the media.
    """
    from google import genai
    from google.genai import types

    client = genai.Client(api_key=_api_key())
    if source.startswith("http"):
        part = types.Part(file_data=types.FileData(file_uri=source))
    elif not os.path.exists(source):
        return f"File not found: {source}"
    else:
        mime = mimetypes.guess_type(source)[0] or "application/octet-stream"
        if os.path.getsize(source) < 15 * 1024 * 1024:
            with open(source, "rb") as f:
                part = types.Part.from_bytes(data=f.read(), mime_type=mime)
        else:
            part = client.files.upload(file=source)
            while getattr(part.state, "name", "") == "PROCESSING":
                time.sleep(3)
                part = client.files.get(name=part.name)
    for attempt in range(3):
        RATE_LIMITER.acquire()
        try:
            return client.models.generate_content(model=MEDIA_MODEL, contents=[part, question]).text
        except Exception as e:
            print(f"analyze_media attempt {attempt+1}: {str(e)[:300]}")
            time.sleep(20 * (attempt + 1))
    return "Media analysis failed."


@tool
def run_python(code: str) -> str:
    """Run a Python snippet and return what it prints. Use it for any counting, arithmetic,
    date maths, string reversal or data processing (pandas is available). Always print() results.

    Args:
        code: Python source code to execute.
    """
    try:
        p = subprocess.run(["python", "-c", code], capture_output=True, text=True, timeout=60, cwd=DOWNLOAD_DIR)
        return (p.stdout + ("\nSTDERR:\n" + p.stderr if p.stderr else ""))[:20000] or "(no output)"
    except subprocess.TimeoutExpired:
        return "Timed out after 60 seconds."


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

    Args:
        file_path: Local path to the .py file.
    """
    try:
        p = subprocess.run(["python", file_path], capture_output=True, text=True, timeout=60)
        return f"STDOUT:\n{p.stdout}\nSTDERR:\n{p.stderr}"
    except subprocess.TimeoutExpired:
        return "Timed out after 60 seconds."


@tool
def read_table_file(file_path: str) -> str:
    """Read an Excel or CSV file and return every sheet as markdown.

    Args:
        file_path: Local path to a .xlsx/.xls/.csv file.
    """
    if file_path.lower().endswith(".csv"):
        sheets = {"csv": pd.read_csv(file_path)}
    else:
        sheets = pd.read_excel(file_path, sheet_name=None)
    out = [f"## Sheet: {n}  shape={df.shape}\n{df.to_markdown(index=False)}" for n, df in sheets.items()]
    return "\n\n".join(out)[:40000]


TOOLS = [web_search, wikipedia_search, wikipedia_page, visit_webpage, download_task_file,
         analyze_media, run_python, run_python_file, read_table_file]


# =====================================================================
# Agent (LangGraph ReAct loop)
# =====================================================================

# GAIA's official system prompt, plus tool guidance.
SYSTEM_PROMPT = """You are a general AI assistant. I will ask you a question. Report your thoughts, and finish
your answer with the following template: FINAL ANSWER: [YOUR FINAL ANSWER].
YOUR FINAL ANSWER should be a number OR as few words as possible OR a comma separated list of numbers
and/or strings. If you are asked for a number, don't use comma to write your number neither use units
such as $ or percent sign unless specified otherwise. If you are asked for a string, don't use articles,
neither abbreviations (e.g. for cities), and write the digits in plain text unless specified otherwise.
If you are asked for a comma separated list, apply the above rules depending of whether the element to
be put in the list is a number or a string.

How to work:
- Use tools to find evidence; never guess when a tool can check.
- If the question has an attached file, call download_task_file(task_id) first, then analyze_media
  (images, audio, video), read_table_file (spreadsheets) or run_python_file (code).
- For YouTube links, call analyze_media with the URL.
- For Wikipedia facts pinned to a year, use wikipedia_page(title, as_of="YYYY-12-31").
- Do counting, arithmetic and text manipulation with run_python.
- Read the question carefully: it may be written backwards, or ask for a specific format
  (first name only, IOC code, alphabetical order, two decimal places...). Follow it exactly."""


def build_graph():
    llm = ChatGoogleGenerativeAI(
        model=MODEL_ID,
        google_api_key=_api_key(),
        rate_limiter=RATE_LIMITER,
        max_retries=3,
    )
    llm_with_tools = llm.bind_tools(TOOLS)

    def assistant(state: MessagesState):
        return {"messages": [llm_with_tools.invoke(state["messages"])]}

    builder = StateGraph(MessagesState)
    builder.add_node("assistant", assistant)
    builder.add_node("tools", ToolNode(TOOLS))
    builder.add_edge(START, "assistant")
    builder.add_conditional_edges("assistant", tools_condition)
    builder.add_edge("tools", "assistant")
    return builder.compile(), llm


def _message_text(msg) -> str:
    content = msg.content
    if isinstance(content, list):  # Gemini can return a list of content parts
        content = "".join(p.get("text", "") if isinstance(p, dict) else str(p) for p in content)
    return str(content)


def extract_final_answer(text: str) -> str:
    matches = re.findall(r"FINAL ANSWER:\s*(.+)", text, flags=re.I)  # one line only
    lines = [l for l in text.strip().splitlines() if l.strip()]
    ans = (matches[-1] if matches else lines[-1] if lines else "").strip()
    ans = ans.strip("`*\"' \n")
    if ans.endswith(".") and not re.search(r"\d\.$", ans) and len(ans.split()) <= 6:
        ans = ans[:-1]
    return ans.strip()


class GaiaAgent:
    def __init__(self):
        self.graph, self.llm = build_graph()
        print(f"GaiaAgent (LangGraph) initialized with {MODEL_ID}")

    def __call__(self, question: str, task_id: str = "", file_name: str = "") -> str:
        prompt = f"task_id: {task_id}\n"
        if file_name:
            prompt += f"Attached file: {file_name} (get it with download_task_file('{task_id}'))\n"
        prompt += f"\nQuestion:\n{question}"
        messages = [SystemMessage(content=SYSTEM_PROMPT), HumanMessage(content=prompt)]
        for attempt in range(2):
            try:
                result = self.graph.invoke({"messages": messages}, {"recursion_limit": 24})
                final = _message_text(result["messages"][-1])
                if "FINAL ANSWER" not in final.upper():
                    # Formatter step: ask once more for just the answer in GAIA format.
                    fmt = self.llm.invoke(result["messages"] + [HumanMessage(content=(
                        "Based on the work above, reply with exactly one line: FINAL ANSWER: <answer>, "
                        "following the answer format rules. No other text."))])
                    final = _message_text(fmt)
                print(f"[{task_id}] raw final message: {final[-300:]}")
                return extract_final_answer(final)
            except GraphRecursionError:
                print(f"[{task_id}] step limit reached; giving up on this question.")
                return "unknown"
            except Exception as e:
                print(f"Agent error (attempt {attempt+1}) on {task_id}: {str(e)[:500]}")
                time.sleep(20)
        return "unknown"


# =====================================================================
# Run + submit (based on the course template)
# =====================================================================

CACHE_PATH = os.path.join(tempfile.gettempdir(), "gaia_answers.json")


def _load_cache():
    try:
        with open(CACHE_PATH) as f:
            return json.load(f)
    except Exception:
        return {}


def run_and_submit_all(profile: gr.OAuthProfile | None, use_cache: bool = True):
    space_id = os.getenv("SPACE_ID")
    if profile:
        username = f"{profile.username}"
        print(f"User logged in: {username}")
    else:
        return "Please Login to Hugging Face with the button.", None

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

    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(questions_url, timeout=30)
        response.raise_for_status()
        questions_data = response.json()
    except Exception as e:
        return f"Error fetching questions: {e}", None

    for item in questions_data:
        if item.get("file_name"):
            TASK_FILES[item["task_id"]] = item["file_name"]

    cache = _load_cache() if use_cache else {}
    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 cache[task_id] not in ("", "unknown"):
            ans = cache[task_id]
        else:
            ans = agent(question_text, task_id=task_id, file_name=item.get("file_name", ""))
            cache[task_id] = ans
            with open(CACHE_PATH, "w") as f:
                json.dump(cache, f)
        answers_payload.append({"task_id": task_id, "submitted_answer": ans})
        results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": ans})

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

    submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
    try:
        response = requests.post(submit_url, json=submission_data, timeout=120)
        response.raise_for_status()
        result_data = response.json()
        final_status = (
            f"Submission Successful!\n"
            f"User: {result_data.get('username')}\n"
            f"Overall Score: {result_data.get('score', 'N/A')}% "
            f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
            f"Message: {result_data.get('message', 'No message received.')}"
        )
        return final_status, pd.DataFrame(results_log)
    except requests.exceptions.HTTPError as e:
        detail = e.response.text[:500] if e.response is not None else str(e)
        return f"Submission Failed: {detail}", pd.DataFrame(results_log)
    except Exception as e:
        return f"Submission Failed: {e}", pd.DataFrame(results_log)


def test_one_question(question: str):
    """Quick check of the agent on a single question, without submitting."""
    try:
        return GaiaAgent()(question, task_id="manual-test")
    except Exception as e:
        return f"Error: {e}"


def clear_cache():
    if os.path.exists(CACHE_PATH):
        os.remove(CACHE_PATH)
    return "Answer cache cleared."


with gr.Blocks() as demo:
    gr.Markdown("# GAIA Agent — Final Assignment (LangGraph + Gemini)")
    gr.Markdown(
        """
        A LangGraph ReAct agent with web search, Wikipedia (incl. historical revisions), page reading,
        task-file download, Gemini media analysis (images, audio, video, YouTube), Python execution
        and spreadsheet reading.

        1. Add a `GEMINI_API_KEY` secret in this Space's settings. Recommended: `HF_TOKEN` (with access
           granted to the gated `gaia-benchmark/GAIA` dataset, for attached files) and `TAVILY_API_KEY`.
        2. Log in with Hugging Face below.
        3. Optionally try one question first, then click **Run Evaluation & Submit All Answers**
           (takes a while; answers are cached so a re-run after a timeout resumes where it stopped).
        """
    )
    gr.LoginButton()
    with gr.Row():
        test_q = gr.Textbox(label="Test question", value="What is the capital of the country where the Eiffel Tower is?")
        test_out = gr.Textbox(label="Agent answer")
    gr.Button("Test one question").click(fn=test_one_question, inputs=[test_q], outputs=[test_out])

    use_cache = gr.Checkbox(value=True, label="Reuse cached answers from a previous run")
    run_button = gr.Button("Run Evaluation & Submit All Answers")
    clear_button = gr.Button("Clear answer cache")
    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, inputs=[use_cache], outputs=[status_output, results_table])
    clear_button.click(fn=clear_cache, outputs=[status_output])


if __name__ == "__main__":
    print(f"SPACE_ID: {os.getenv('SPACE_ID')}  MODEL_ID: {MODEL_ID}")
    demo.launch(debug=True, share=False)