File size: 7,310 Bytes
42e917a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""The GAIA agent: a smolagents CodeAgent with a provider-agnostic model.

Choose the LLM with environment variables (Space secrets/variables):

    MODEL_ID       a LiteLLM id such as "gemini/gemini-2.5-flash" or "openai/gpt-4.1-mini"
                   (format: "<provider>/<model>"), or a Hugging Face model id such as
                   "Qwen/Qwen3-Coder-480B-A35B-Instruct".
    MODEL_BACKEND  optional: "litellm" or "hf". Auto-detected from MODEL_ID if unset.
    HF_PROVIDER    optional Hugging Face inference provider, e.g. "together", "nebius".
    MAX_STEPS      optional, default 12.

API keys are read from the usual variables: HF_TOKEN, GEMINI_API_KEY, OPENAI_API_KEY,
ANTHROPIC_API_KEY, OPENROUTER_API_KEY, ... (LiteLLM picks them up automatically).
"""

import os
import re
from pathlib import Path

from smolagents import CodeAgent, InferenceClientModel, LiteLLMModel

from tools import IMAGE_EXT, get_tools

# Model-id prefixes that mean "route through LiteLLM" rather than Hugging Face.
LITELLM_PREFIXES = {
    "gemini", "openai", "anthropic", "openrouter", "groq", "mistral", "deepseek",
    "together_ai", "xai", "ollama", "ollama_chat", "azure", "bedrock", "vertex_ai", "cohere",
}

INSTRUCTIONS = """You are solving questions from the GAIA benchmark. Your final answer is graded by EXACT string match against the ground truth, so its form matters as much as its content.

How to work:
- Plan briefly, then verify facts with tools. Do not answer from memory when a source can be checked.
- For encyclopedic facts (discographies, results tables, biographies) prefer wikipedia_page, which keeps tables. If the question names a Wikipedia version or year, pass as_of="YYYY-MM-DD".
- For everything else: web_search to find a page, then visit_webpage to read it. Snippets are often incomplete.
- Do every calculation, count, sort or text manipulation in Python code, never in your head.
- If the question text looks scrambled (for example written backwards), decode it in Python first, then answer what it actually asks.
- If a file is attached, its path is given in the task. Use read_file (text, code, spreadsheets, PDFs, audio) or run_python_file (to get the output of a .py file). For spreadsheets you may also load them with pandas directly.
- If a tool fails, try a different route instead of repeating the same call.

Rules for the value you pass to final_answer:
- Only the answer itself: no explanation, no full sentence, no "FINAL ANSWER", no trailing period.
- A number: digits only, no thousands separators, no units, no "$" or "%", unless the question explicitly asks for them. Respect any requested rounding or decimal places.
- A string: as few words as possible, no articles, no abbreviations unless asked, exact spelling and capitalisation of the name as given in the source.
- A list: comma-separated with one space after each comma ("a, b, c"), ordered as the question asks (alphabetical, chronological, ...).
- Obey every formatting instruction in the question (e.g. "first name only", "IOC country code", "in algebraic notation", "plural form").
- If after real effort you still cannot be sure, give your single best guess rather than an apology."""


def build_model():
    """Return a smolagents Model chosen by environment variables."""
    model_id = os.getenv("MODEL_ID", "").strip()
    backend = os.getenv("MODEL_BACKEND", "").strip().lower()
    if not backend:
        prefix = model_id.split("/", 1)[0].lower() if "/" in model_id else ""
        backend = "litellm" if prefix in LITELLM_PREFIXES else "hf"

    if backend == "litellm":
        if not model_id:
            raise ValueError("MODEL_BACKEND=litellm needs MODEL_ID, e.g. 'gemini/gemini-2.5-flash'.")
        return LiteLLMModel(model_id=model_id, api_base=os.getenv("API_BASE") or None)

    kwargs = {"token": os.getenv("HF_TOKEN"), "timeout": 180}
    if model_id:
        kwargs["model_id"] = model_id
    if os.getenv("HF_PROVIDER"):
        kwargs["provider"] = os.getenv("HF_PROVIDER")
    return InferenceClientModel(**kwargs)  # without MODEL_ID, smolagents' default model


# ---------------------------------------------------------------------------
# Answer clean-up (the scorer does exact match)
# ---------------------------------------------------------------------------
_THOUSANDS = re.compile(r"-?\d{1,3}(,\d{3})+(\.\d+)?")


def clean_answer(answer) -> str:
    s = str(answer).strip()
    s = re.sub(r"^\s*(final\s+answer|answer)\s*[::-]\s*", "", s, flags=re.I)
    s = s.replace("**", "").replace("`", "").strip()
    if len(s) >= 2 and s[0] == s[-1] and s[0] in "\"'":  # surrounding quotes
        s = s[1:-1].strip()
    s = re.sub(r"\s+", " ", s)
    # Drop a sentence-ending period, but keep abbreviations ("D.C.", "Jr.").
    if s.endswith(".") and not re.search(r"(\b[A-Za-z]|\b(Jr|Sr|St|Inc|Ltd|Co|Corp|etc|vs))\.$", s):
        s = s[:-1].rstrip()
    if _THOUSANDS.fullmatch(s):  # "1,234,567" -> "1234567"
        s = s.replace(",", "")
    elif "," in s:  # list: normalise to "a, b, c"
        s = re.sub(r"\s*,\s*", ", ", s)
    return s


def check_answer_format(final_answer, memory, agent=None) -> bool:
    """Final-answer check: makes the agent retry if it answers with an essay."""
    text = str(final_answer)
    if "final answer" in text.lower():
        raise ValueError("Pass only the bare answer to final_answer, without the words 'FINAL ANSWER'.")
    if len(text) > 300:
        raise ValueError("The answer is far too long. Pass only the exact answer value, not an explanation.")
    return True


class GaiaAgent:
    """Callable used by app.py: agent(question, file_path) -> answer string."""

    def __init__(self):
        self.model = build_model()
        self.agent = CodeAgent(
            tools=get_tools(),
            model=self.model,
            instructions=INSTRUCTIONS,
            max_steps=int(os.getenv("MAX_STEPS", "12")),
            additional_authorized_imports=[
                "pandas", "numpy", "math", "re", "json", "csv", "datetime", "statistics",
                "itertools", "collections", "unicodedata", "fractions", "decimal", "openpyxl",
            ],
            final_answer_checks=[check_answer_format],
            verbosity_level=1,
        )

    def __call__(self, question: str, file_path: str | None = None) -> str:
        task = question
        images = None
        if file_path:
            ext = Path(file_path).suffix.lower()
            task += f"\n\nAttached file: {file_path}"
            if ext in IMAGE_EXT:
                from PIL import Image

                images = [Image.open(file_path).convert("RGB")]
                task += "\n(The image is attached to this message; look at it directly.)"
            else:
                task += f"\n(Open it with read_file{' or run_python_file' if ext == '.py' else ''}.)"
        try:
            result = self.agent.run(task, images=images)
        except Exception as e:
            if images is None:
                raise
            # Model may not accept images: retry text-only so the run still produces an answer.
            print(f"Run with image failed ({e}); retrying without the image.")
            result = self.agent.run(task + "\n(The image could not be shown; work from the question.)")
        return clean_answer(result)