"""Tools for the GAIA agent (smolagents). Each tool returns a string. Errors are returned as text, never raised, so the agent can read what went wrong and try another route. """ import os import re import subprocess import sys import time from pathlib import Path import requests from smolagents import Tool, VisitWebpageTool, tool HEADERS = {"User-Agent": "Mozilla/5.0 (GAIA agent; HF agents-course final project)"} # Cap on any single tool output. About 12k characters is ~3k tokens, which keeps a # 32k-token model (e.g. Qwen2.5-72B) from overflowing after a few web pages. MAX_CHARS = int(os.getenv("MAX_TOOL_CHARS", "12000")) def _truncate(text: str, limit: int = MAX_CHARS) -> str: if len(text) <= limit: return text return text[:limit] + f"\n\n[... truncated, {len(text) - limit} more characters ...]" # --------------------------------------------------------------------------- # Web search: Tavily if TAVILY_API_KEY is set, otherwise DuckDuckGo (free, # but rate-limited on shared Space IPs, so it retries with back-off). # --------------------------------------------------------------------------- class WebSearchTool(Tool): name = "web_search" description = ( "Searches the web and returns the top results (title, URL, snippet). " "Use it to find pages, then open the most promising URL with visit_webpage " "to read the details. Snippets alone are often incomplete." ) inputs = {"query": {"type": "string", "description": "The search query."}} output_type = "string" def __init__(self, max_results: int = 6, **kwargs): super().__init__(**kwargs) self.max_results = max_results self.tavily_key = os.getenv("TAVILY_API_KEY") def _tavily(self, query: str) -> str: r = requests.post( "https://api.tavily.com/search", headers={"Authorization": f"Bearer {self.tavily_key}"}, json={"query": query, "max_results": self.max_results}, timeout=30, ) r.raise_for_status() results = r.json().get("results", []) return "\n\n".join( f"[{x.get('title', '')}]({x.get('url', '')})\n{x.get('content', '')}" for x in results ) def _ddg(self, query: str) -> str: from ddgs import DDGS last_err = None for attempt in range(3): try: results = list(DDGS().text(query, max_results=self.max_results)) return "\n\n".join( f"[{x.get('title', '')}]({x.get('href', '')})\n{x.get('body', '')}" for x in results ) except Exception as e: # rate limits are common on shared IPs last_err = e time.sleep(2 * (attempt + 1)) raise RuntimeError(last_err) def forward(self, query: str) -> str: try: out = self._tavily(query) if self.tavily_key else self._ddg(query) return out or "No results found. Try different keywords." except Exception as e: return f"Search failed ({e}). Try rephrasing, or go straight to a known URL with visit_webpage." # --------------------------------------------------------------------------- # Wikipedia: full article HTML converted to Markdown, so tables survive. # (Many GAIA level-1 questions hinge on a discography or results table.) # --------------------------------------------------------------------------- WIKI_API = "https://en.wikipedia.org/w/api.php" def _wiki_get(params: dict) -> dict: params = {**params, "format": "json", "formatversion": 2} r = requests.get(WIKI_API, params=params, headers=HEADERS, timeout=30) r.raise_for_status() return r.json() @tool def wikipedia_search(query: str) -> str: """Searches English Wikipedia and returns matching article titles with short snippets. Use it to find the exact title before calling wikipedia_page. Args: query: Search terms, e.g. "Mercedes Sosa discography". """ try: data = _wiki_get({"action": "query", "list": "search", "srsearch": query, "srlimit": 8}) hits = data.get("query", {}).get("search", []) if not hits: return "No Wikipedia results." return "\n".join( f"- {h['title']}: {re.sub(r'<.*?>', '', h.get('snippet', ''))}" for h in hits ) except Exception as e: return f"Wikipedia search failed: {e}" @tool def wikipedia_page(title: str, as_of: str = "") -> str: """Returns an English Wikipedia article as Markdown, with tables kept intact. Args: title: Exact article title, e.g. "Mercedes Sosa". as_of: Optional date "YYYY-MM-DD". If given, returns the article as it stood on that date (use when the question names a specific Wikipedia version or year). """ from markdownify import markdownify try: params = {"action": "parse", "prop": "text", "redirects": 1, "disableeditsection": 1} if as_of: rev = _wiki_get({ "action": "query", "prop": "revisions", "titles": title, "rvlimit": 1, "rvprop": "ids|timestamp", "rvdir": "older", "rvstart": f"{as_of}T23:59:59Z", "redirects": 1, }) pages = rev.get("query", {}).get("pages", []) revs = pages[0].get("revisions") if pages else None if not revs: return f"No revision of '{title}' found on or before {as_of}." params["oldid"] = revs[0]["revid"] else: params["page"] = title data = _wiki_get(params) if "error" in data: return f"Wikipedia error: {data['error'].get('info')}. Use wikipedia_search to find the exact title." html = data["parse"]["text"] html = re.sub(r']*class="reference".*?', "", html, flags=re.S) # drop [1] markers md = markdownify(html, heading_style="ATX") md = re.sub(r"\n{3,}", "\n\n", md) return _truncate(f"# {data['parse']['title']}\n\n{md}") except Exception as e: return f"Failed to load Wikipedia page '{title}': {e}" # --------------------------------------------------------------------------- # YouTube transcripts. YouTube often blocks requests from cloud servers, so # this can fail on a Space; the agent is told to fall back to web search. # --------------------------------------------------------------------------- @tool def youtube_transcript(url: str) -> str: """Returns the spoken-word transcript (captions) of a YouTube video. It cannot see the video's images, only what is said. Args: url: The YouTube URL or the 11-character video id. """ m = re.search(r"(?:v=|youtu\.be/|shorts/|embed/)([\w-]{11})", url) video_id = m.group(1) if m else url.strip() try: from youtube_transcript_api import YouTubeTranscriptApi fetched = YouTubeTranscriptApi().fetch(video_id, languages=["en", "en-US", "en-GB"]) text = " ".join(snippet.text for snippet in fetched) return _truncate(text) or "Transcript is empty." except Exception as e: return ( f"Transcript unavailable ({type(e).__name__}: {e}). " "Try web_search for the video title plus the quote or topic instead." ) # --------------------------------------------------------------------------- # Attached files # --------------------------------------------------------------------------- AUDIO_EXT = {".mp3", ".wav", ".m4a", ".flac", ".ogg"} IMAGE_EXT = {".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp"} _whisper_model = None @tool def transcribe_audio(file_path: str) -> str: """Transcribes speech in an audio file (mp3, wav, m4a, ...) to text, locally with Whisper. Args: file_path: Path to the audio file. """ global _whisper_model try: from faster_whisper import WhisperModel if _whisper_model is None: size = os.getenv("WHISPER_MODEL", "base") # "small" is more accurate but slower on CPU _whisper_model = WhisperModel(size, device="cpu", compute_type="int8") segments, _info = _whisper_model.transcribe(file_path, beam_size=5) return " ".join(s.text.strip() for s in segments) or "No speech detected." except Exception as e: return f"Transcription failed: {e}" @tool def read_file(file_path: str) -> str: """Reads an attached file and returns its contents as text. Handles text and code files, CSV, Excel (every sheet), JSON, PDF and Word documents. Audio files are transcribed automatically. Images cannot be read as text: they are shown to you directly with the task instead. Args: file_path: Path to the file. """ p = Path(file_path) if not p.exists(): return f"File not found: {file_path}" ext = p.suffix.lower() try: if ext in AUDIO_EXT: return transcribe_audio(file_path) if ext in IMAGE_EXT: return "This is an image. Look at the image attached to the task instead of reading it as text." if ext in {".xlsx", ".xls", ".xlsm"}: import pandas as pd sheets = pd.read_excel(p, sheet_name=None) parts = [ f"## Sheet: {name} ({df.shape[0]} rows x {df.shape[1]} cols)\n{df.to_csv(index=False)}" for name, df in sheets.items() ] return _truncate("\n\n".join(parts)) if ext == ".pdf": from pypdf import PdfReader reader = PdfReader(str(p)) text = "\n\n".join((page.extract_text() or "") for page in reader.pages).strip() return _truncate(text) or "No text could be extracted (the PDF may be scanned images)." if ext == ".docx": import docx return _truncate("\n".join(par.text for par in docx.Document(str(p)).paragraphs)) return _truncate(p.read_text(encoding="utf-8", errors="replace")) except Exception as e: return f"Could not read {file_path}: {e}" @tool def run_python_file(file_path: str) -> str: """Executes an attached Python script in a separate process and returns what it prints (stdout and stderr). Use it when a question asks for the output of an attached .py file. Args: file_path: Path to the .py file. """ try: proc = subprocess.run( [sys.executable, file_path], capture_output=True, text=True, timeout=120, cwd=str(Path(file_path).parent), ) out = proc.stdout if proc.stderr: out += f"\n[stderr]\n{proc.stderr}" return _truncate(out) or "(the script printed nothing)" except subprocess.TimeoutExpired: return "The script ran for more than 120 seconds and was stopped." except Exception as e: return f"Could not run {file_path}: {e}" def get_tools() -> list: """All tools handed to the agent (final_answer is added by smolagents itself).""" return [ WebSearchTool(), VisitWebpageTool(max_output_length=MAX_CHARS), wikipedia_search, wikipedia_page, youtube_transcript, read_file, transcribe_audio, run_python_file, ]