File size: 11,256 Bytes
281882c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a277f83
 
 
281882c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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'<sup[^>]*class="reference".*?</sup>', "", 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,
    ]