File size: 11,591 Bytes
90d0b3d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Custom tools for the GAIA agent.

Everything that needs a model (speech-to-text, image understanding) goes through
UF's NaviGator AI Toolkit, an OpenAI-compatible API.
"""

from __future__ import annotations

import base64
import logging
import mimetypes
import os
import re
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path

import requests
from markdownify import markdownify
from smolagents import Tool, tool

from config import navigator_client

logging.getLogger("pypdf").setLevel(logging.ERROR)

USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0 Safari/537.36"
WIKI_API = "https://en.wikipedia.org/w/api.php"
WIKI_HEADERS = {"User-Agent": "gaia-course-agent/0.1 (educational project)"}


def _truncate(text: str, limit: int) -> str:
    if len(text) <= limit:
        return text
    return text[:limit] + f"\n\n...[truncated, {len(text) - limit} more characters]"


def _html_to_markdown(html: str) -> str:
    md = markdownify(html, strip=["img"])
    md = re.sub(r"\n{3,}", "\n\n", md)
    return md.strip()


# --------------------------------------------------------------------------- web


@tool
def web_search(query: str, max_results: int = 8) -> str:
    """Search the web (DuckDuckGo, falling back to Bing) and return titles, URLs and snippets.

    Args:
        query: The search query.
        max_results: How many results to return (default 8).
    """
    errors = []
    try:
        from ddgs import DDGS

        results = DDGS().text(query, max_results=max_results)
        if results:
            return "\n\n".join(f"[{r.get('title')}]({r.get('href')})\n{r.get('body')}" for r in results)
    except Exception as e:  # rate limits happen
        errors.append(f"ddgs: {e}")
    try:
        from smolagents import WebSearchTool

        return WebSearchTool(max_results=max_results, engine="bing")(query)
    except Exception as e:
        errors.append(f"bing: {e}")
    return "Search failed: " + "; ".join(errors)


@tool
def visit_webpage(url: str) -> str:
    """Fetch a web page and return its content as markdown (long pages are truncated at 40,000 characters).
    Tip: store the result in a variable and print only the parts you need.

    Args:
        url: The full URL of the page to fetch.
    """
    try:
        r = requests.get(url, headers={"User-Agent": USER_AGENT}, timeout=30)
        r.raise_for_status()
    except Exception as e:
        return f"Error fetching {url}: {e}"
    ctype = r.headers.get("content-type", "")
    if "pdf" in ctype or url.lower().endswith(".pdf"):
        return _pdf_bytes_to_text(r.content)
    if "html" not in ctype and "xml" not in ctype:
        return _truncate(r.text, 40000)
    return _truncate(_html_to_markdown(r.text), 40000)


def _pdf_bytes_to_text(data: bytes) -> str:
    try:
        from pypdf import PdfReader
        import io

        reader = PdfReader(io.BytesIO(data))
        return _truncate("\n".join(page.extract_text() or "" for page in reader.pages), 40000)
    except Exception as e:
        return f"Could not parse PDF: {e}"


# --------------------------------------------------------------------- wikipedia


@tool
def wikipedia_search(query: str, limit: int = 8) -> str:
    """Search English Wikipedia and return matching article titles with short snippets.

    Args:
        query: What to search for.
        limit: Maximum number of results (default 8).
    """
    params = {"action": "query", "list": "search", "srsearch": query, "srlimit": limit, "format": "json"}
    try:
        data = requests.get(WIKI_API, params=params, headers=WIKI_HEADERS, timeout=30).json()
    except Exception as e:
        return f"Wikipedia search failed: {e}"
    hits = data.get("query", {}).get("search", [])
    if not hits:
        return "No results."
    out = []
    for h in hits:
        snippet = re.sub(r"<[^>]+>", "", h.get("snippet", ""))
        out.append(f"- {h['title']}: {snippet}")
    return "\n".join(out)


@tool
def wikipedia_page(title: str, as_of_date: str = "") -> str:
    """Return the full content of an English Wikipedia article as markdown, tables included.
    Long articles are returned in full (up to 150,000 characters), so store the result in a
    variable and print only the relevant parts (e.g. search it with Python string methods).

    Args:
        title: Exact article title (use wikipedia_search first if unsure).
        as_of_date: Optional date "YYYY-MM-DD". If given, returns the article as it was at the end of that day
            (useful when a question refers to a specific version of Wikipedia, e.g. "the 2022 version").
    """
    params = {"action": "parse", "prop": "text", "format": "json", "redirects": 1, "disableeditsection": 1}
    if as_of_date:
        rev_params = {
            "action": "query",
            "prop": "revisions",
            "titles": title,
            "rvlimit": 1,
            "rvdir": "older",
            "rvstart": f"{as_of_date}T23:59:59Z",
            "rvprop": "ids|timestamp",
            "redirects": 1,
            "format": "json",
        }
        try:
            data = requests.get(WIKI_API, params=rev_params, headers=WIKI_HEADERS, timeout=30).json()
            page = next(iter(data["query"]["pages"].values()))
            params["oldid"] = page["revisions"][0]["revid"]
        except Exception as e:
            return f"Could not find a revision of '{title}' as of {as_of_date}: {e}"
    else:
        params["page"] = title
    try:
        data = requests.get(WIKI_API, params=params, headers=WIKI_HEADERS, timeout=60).json()
    except Exception as e:
        return f"Wikipedia fetch failed: {e}"
    if "error" in data:
        return f"Wikipedia error: {data['error'].get('info')}"
    html = data["parse"]["text"]["*"]
    html = re.sub(r'<sup[^>]*class="[^"]*reference[^"]*"[^>]*>.*?</sup>', "", html, flags=re.S)
    html = re.sub(r'<style[^>]*>.*?</style>', "", html, flags=re.S)
    header = f"# {data['parse']['title']}" + (f" (revision {params['oldid']}, as of {as_of_date})" if as_of_date else "")
    return _truncate(header + "\n\n" + _html_to_markdown(html), 150000)


# ------------------------------------------------------------------------- files


@tool
def read_file(file_path: str) -> str:
    """Read a local file and return its content as text.
    Spreadsheets (.xlsx/.xls/.csv) are returned as CSV text for every sheet; PDFs as extracted text;
    other files as plain text. For audio use transcribe_audio, for images use analyze_image.

    Args:
        file_path: Path to the file.
    """
    p = Path(file_path)
    if not p.exists():
        return f"File not found: {file_path}"
    suffix = p.suffix.lower()
    try:
        if suffix in {".xlsx", ".xls"}:
            import pandas as pd

            sheets = pd.read_excel(p, sheet_name=None)
            return "\n\n".join(f"## Sheet: {name}\n{df.to_csv(index=False)}" for name, df in sheets.items())
        if suffix == ".csv":
            return _truncate(p.read_text(errors="replace"), 60000)
        if suffix == ".pdf":
            return _pdf_bytes_to_text(p.read_bytes())
        return _truncate(p.read_text(errors="replace"), 60000)
    except Exception as e:
        return f"Error reading {file_path}: {e}"


@tool
def run_python_file(file_path: str) -> str:
    """Execute a Python script in a separate process (60 second limit) and return its stdout and stderr.

    Args:
        file_path: Path to the .py file to run.
    """
    p = Path(file_path).resolve()
    if not p.exists():
        return f"File not found: {file_path}"
    with tempfile.TemporaryDirectory() as tmp:
        script = Path(tmp) / p.name
        shutil.copy(p, script)
        try:
            proc = subprocess.run(
                [sys.executable, "-I", str(script)], cwd=tmp, capture_output=True, text=True, timeout=60
            )
        except subprocess.TimeoutExpired:
            return "Timed out after 60 seconds."
    return f"exit code: {proc.returncode}\n--- stdout ---\n{proc.stdout[-20000:]}\n--- stderr ---\n{proc.stderr[-5000:]}"


# ---------------------------------------------------------------- audio / vision


@tool
def transcribe_audio(file_path: str) -> str:
    """Transcribe speech in an audio file (mp3, wav, m4a, ...) to text using Whisper.
    This can take a few minutes.

    Args:
        file_path: Path to the audio file.
    """
    p = Path(file_path)
    if not p.exists():
        return f"File not found: {file_path}"
    client = navigator_client(timeout=600)
    candidates = [p]
    # NaviGator's whisper endpoint handled WAV reliably in testing; convert as a fallback.
    if p.suffix.lower() != ".wav" and shutil.which("afconvert"):
        wav = Path(tempfile.gettempdir()) / (p.stem + ".wav")
        if subprocess.run(["afconvert", "-f", "WAVE", "-d", "LEI16@16000", str(p), str(wav)], capture_output=True).returncode == 0:
            candidates = [wav, p]
    errors = []
    for c in candidates:
        try:
            with open(c, "rb") as f:
                result = client.audio.transcriptions.create(model="whisper-large-v3", file=f)
            return result.text
        except Exception as e:
            errors.append(f"{c.name}: {e}")
    return "Transcription failed: " + "; ".join(errors)


@tool
def analyze_image(file_path: str, question: str) -> str:
    """Ask a vision-language model a question about a local image file and get a text answer.
    Ask for detailed, literal descriptions; the model can make mistakes on fine details.

    Args:
        file_path: Path to the image (png, jpg, ...).
        question: What you want to know about the image.
    """
    p = Path(file_path)
    if not p.exists():
        return f"File not found: {file_path}"
    mime = mimetypes.guess_type(p.name)[0] or "image/png"
    b64 = base64.b64encode(p.read_bytes()).decode()
    client = navigator_client(timeout=300)
    try:
        resp = client.chat.completions.create(
            model="mistral-small-3.1",
            messages=[
                {
                    "role": "user",
                    "content": [
                        {"type": "text", "text": question},
                        {"type": "image_url", "image_url": {"url": f"data:{mime};base64,{b64}"}},
                    ],
                }
            ],
            max_tokens=2000,
        )
        return resp.choices[0].message.content
    except Exception as e:
        return f"Image analysis failed: {e}"


# ----------------------------------------------------------------------- youtube


@tool
def youtube_transcript(url: str) -> str:
    """Get the spoken-word transcript (captions) of a YouTube video, with timestamps in seconds.
    Note: this only contains what is said, not what is shown on screen.

    Args:
        url: The YouTube video URL.
    """
    m = re.search(r"(?:v=|youtu\.be/|shorts/)([A-Za-z0-9_-]{11})", url)
    if not m:
        return "Could not find a video id in the URL."
    try:
        from youtube_transcript_api import YouTubeTranscriptApi

        fetched = YouTubeTranscriptApi().fetch(m.group(1), languages=["en", "en-US", "en-GB"])
        return "\n".join(f"[{s.start:.0f}s] {s.text}" for s in fetched)
    except Exception as e:
        return f"Transcript unavailable: {type(e).__name__}: {str(e)[:300]}"


ALL_TOOLS = [
    web_search,
    visit_webpage,
    wikipedia_search,
    wikipedia_page,
    read_file,
    run_python_file,
    transcribe_audio,
    analyze_image,
    youtube_transcript,
]