"""The GAIA agent: a smolagents CodeAgent driven by gpt-oss-120b on NaviGator.""" from __future__ import annotations import re from smolagents import CodeAgent, OpenAIServerModel from config import MAIN_MODEL, NAVIGATOR_BASE_URL, navigator_api_key from tools import ALL_TOOLS INSTRUCTIONS = """You are a meticulous research assistant answering questions from the GAIA benchmark. How to work: - Break the problem into steps. Verify facts with tools instead of relying on memory whenever a fact can be looked up. - Prefer Wikipedia tools for encyclopedic facts; use web_search + visit_webpage for everything else. - Tool outputs can be long: store them in variables and print only the relevant slices (e.g. search with str.find / re). - If a file is attached, its local path is given in the question. Use read_file, run_python_file, transcribe_audio or analyze_image. - Read the question again before answering and make sure you answer exactly what is asked (units, ordering, format, which name, etc.). - Never call exit(), sys.exit() or raise SystemExit in your code; use if/else instead. - Look at the data before parsing it: print a relevant slice of a page first, then write the extraction code. - Never conclude from a failed parse. If a regex/search finds nothing (empty list, 0, None), that usually means your parsing is wrong, not that the answer is zero: inspect the text and try again, or use another source. - Cross-check important facts (counts, names, dates) with a second look or second source before answering. - If something truly cannot be determined, give your single best guess rather than an explanation. Final answer format (the answer is graded by exact string match): - Call final_answer with ONLY the answer: a number, as few words as possible, or a comma separated list. No explanation, no sentence, no "FINAL ANSWER" prefix. - Numbers: write digits without thousands separators, and no units or symbols ($, %) unless the question explicitly asks for them. - Strings: no articles, no abbreviations (e.g. write city names in full) unless asked; keep the spelling/capitalization of proper names. - Lists: comma separated, apply the same rules to every element, follow any ordering the question asks for. - Follow any explicit formatting instruction in the question exactly (e.g. "two decimal places", "first name only", "IOC code", "algebraic notation"). """ AUTHORIZED_IMPORTS = [ "math", "statistics", "re", "json", "datetime", "collections", "itertools", "functools", "unicodedata", "fractions", "decimal", "pandas", "numpy", "io", "csv", ] class NavigatorModel(OpenAIServerModel): """gpt-oss on NaviGator: server-side `stop` sequences can fire inside the model's hidden reasoning and return an empty answer, so never send them; smolagents then trims the output at the stop sequences client-side instead.""" @property def supports_stop_parameter(self) -> bool: return False def generate(self, messages, stop_sequences=None, response_format=None, tools_to_call_from=None, **kwargs): # gpt-oss occasionally spends the whole turn in hidden reasoning and returns empty content: retry. msg = None for _ in range(3): msg = super().generate(messages, stop_sequences=stop_sequences, response_format=response_format, tools_to_call_from=tools_to_call_from, **kwargs) if (msg.content and str(msg.content).strip()) or msg.tool_calls: return msg return msg EXTRACT_PROMPT = """A research agent was asked the question below and produced a draft response. Extract the final answer from the draft and rewrite it to follow these rules exactly: - Output ONLY the answer: a number, as few words as possible, or a comma separated list. No explanation, no markdown, no quotes. - Numbers: digits only, no thousands separators, no units or symbols unless the question explicitly asks for them. - Strings: no articles or abbreviations unless asked; follow any format the question requests (e.g. first name only, a code, decimal places). If the draft contains no answer at all, output your best short guess. Question: {question} Draft response: {draft} Final answer:""" def extract_answer(question: str, draft: str) -> str: """Use the model to turn a long/verbose draft into a GAIA-formatted short answer.""" from config import navigator_client resp = navigator_client(timeout=300).chat.completions.create( model=MAIN_MODEL, messages=[{"role": "user", "content": EXTRACT_PROMPT.format(question=question, draft=draft[:8000])}], ) return (resp.choices[0].message.content or draft).strip() def looks_verbose(answer: str) -> bool: return bool( "\n" in answer or "**" in answer or "<" in answer or len(answer) > 120 or len(answer.split()) > 15 ) def build_agent(max_steps: int = 20, verbosity_level: int = 1) -> CodeAgent: model = NavigatorModel( model_id=MAIN_MODEL, api_base=NAVIGATOR_BASE_URL, api_key=navigator_api_key(), client_kwargs={"timeout": 600, "max_retries": 3}, ) return CodeAgent( tools=ALL_TOOLS, model=model, instructions=INSTRUCTIONS, additional_authorized_imports=AUTHORIZED_IMPORTS, max_steps=max_steps, verbosity_level=verbosity_level, max_print_outputs_length=20000, # JSON {"thought", "code"} replies instead of regex-parsed blocks: far fewer format errors with gpt-oss. use_structured_outputs_internally=True, ) def normalize_answer(answer) -> str: """Light clean-up so the answer survives exact-match grading.""" text = str(answer).strip() text = re.sub(r"", "", text, flags=re.I).strip() text = re.sub(r"^\s*(final answer|answer)\s*[::]\s*", "", text, flags=re.I) text = text.strip().strip("`").strip() if text.startswith('"') and text.endswith('"') and text.count('"') == 2: text = text[1:-1] if text.endswith(".") and not re.search(r"\d\.$", text) and text.count(" ") < 6: text = text[:-1] return text.strip() class GaiaAgent: """Callable wrapper: question text (+ optional file path) -> answer string.""" def __init__(self, max_steps: int = 20, verbosity_level: int = 1): self.max_steps = max_steps self.verbosity_level = verbosity_level def __call__(self, question: str, file_path: str | None = None) -> str: agent = build_agent(self.max_steps, self.verbosity_level) # fresh memory per question task = question if file_path: task += f"\n\nAttached file (local path): {file_path}" try: result = str(agent.run(task)) except SystemExit: # model-written code called sys.exit(): start over once with a fresh agent result = str(build_agent(self.max_steps, self.verbosity_level).run(task)) if looks_verbose(result): result = extract_answer(question, result) return normalize_answer(result)