File size: 10,634 Bytes
912dd45
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Tools the GAIA agent can call.

The LLM only sees each tool's NAME, DOCSTRING and ARGUMENT TYPES — so the
docstring is effectively a prompt telling the model when and how to use it.
"""

import subprocess
import sys

import requests
from bs4 import BeautifulSoup
from langchain_core.tools import tool
from markdownify import markdownify

MAX_CHARS = 20_000  # cap tool output so we don't flood the context window
WIKI_API = "https://en.wikipedia.org/w/api.php"
# Wikimedia's API policy asks for a descriptive User-Agent with a contact URL;
# generic ones get rate-limited (HTTP 429) much sooner.
HEADERS = {"User-Agent": "GAIA-agent-course-project/1.0 "
                         "(https://huggingface.co/spaces/ShayanDarabi/Final_Assignment_Template)"}


def _wiki_get(params: dict) -> dict:
    """GET the Wikipedia API, backing off and retrying when rate-limited."""
    import time
    for attempt in range(4):
        resp = requests.get(WIKI_API, params=params, headers=HEADERS, timeout=30)
        if resp.status_code != 429:
            resp.raise_for_status()
            return resp.json()
        time.sleep(int(resp.headers.get("Retry-After", 0)) or 2 ** (attempt + 1))
    raise RuntimeError("Wikipedia is rate-limiting us (429). Use web_search / fetch_webpage instead.")


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]"


# --- Python -------------------------------------------------------------------
@tool
def python_repl(code: str) -> str:
    """Execute Python code and return what it prints (stdout + stderr).

    Use this for ANY calculation, counting, sorting, date math, logic/table
    checks, string manipulation, or reading data files with pandas.
    The code runs in a fresh process each call, so always print() the
    values you need — nothing else is returned.
    """
    try:
        result = subprocess.run(
            [sys.executable, "-c", code],
            capture_output=True,
            text=True,
            timeout=60,
        )
    except subprocess.TimeoutExpired:
        return "Error: code timed out after 60 seconds."
    output = result.stdout + (f"\nSTDERR:\n{result.stderr}" if result.stderr else "")
    return _truncate(output.strip() or "(no output — did you forget to print()?)")


# --- Wikipedia ------------------------------------------------------------------
@tool
def wikipedia_search(query: str) -> str:
    """Search English Wikipedia. Returns the top matching page titles with a
    short snippet each. Follow up with wikipedia_page(title) to read a page."""
    params = {"action": "query", "list": "search", "srsearch": query,
              "srlimit": 8, "format": "json"}
    hits = _wiki_get(params)["query"]["search"]
    if not hits:
        return f"No Wikipedia results for {query!r}."
    lines = []
    for h in hits:
        snippet = BeautifulSoup(h["snippet"], "html.parser").get_text()
        lines.append(f"- {h['title']}: {snippet}")
    return "\n".join(lines)


@tool
def wikipedia_page(title: str, section: str = "") -> str:
    """Read an English Wikipedia page as markdown, INCLUDING its tables
    (discographies, filmographies, results tables, etc.).

    Args:
        title: exact page title, e.g. "Mercedes Sosa".
        section: optional section heading to read only that part, e.g.
            "Discography". Leave empty to get the whole page (may be truncated;
            the list of section names is always included so you can drill in).
    """
    base = {"action": "parse", "page": title, "format": "json", "redirects": 1}

    # 1. Get the list of sections (always useful for the model to navigate).
    data = _wiki_get({**base, "prop": "sections"})
    if "error" in data:
        return f"Error: {data['error'].get('info')}. Try wikipedia_search first."
    sections = data["parse"]["sections"]
    toc = ", ".join(s["line"] for s in sections)

    # 2. Fetch either one section or the whole page as HTML.
    params = {**base, "prop": "text"}
    if section:
        match = next((s for s in sections
                      if section.lower() in BeautifulSoup(s["line"], "html.parser").get_text().lower()), None)
        if not match:
            return f"No section matching {section!r}. Sections are: {toc}"
        params["section"] = match["index"]
    html = _wiki_get(params)["parse"]["text"]["*"]

    # 3. Strip noise (references, edit links, navboxes), convert to markdown.
    soup = BeautifulSoup(html, "html.parser")
    for tag in soup.select("sup.reference, .mw-editsection, .navbox, .reflist, style, script"):
        tag.decompose()
    text = markdownify(str(soup), heading_style="ATX", strip=["a", "img"])  # keep link text, drop URLs
    return _truncate(f"SECTIONS: {toc}\n\n{text}")


# --- Web ------------------------------------------------------------------------
@tool
def web_search(query: str) -> str:
    """Search the web (DuckDuckGo). Returns titles, URLs and snippets of the top
    results. Snippets are often incomplete — use fetch_webpage(url) to read a
    promising result in full before answering."""
    import os
    results = []

    # 1. Tavily (reliable search API, free tier) if a key is configured.
    if os.getenv("TAVILY_API_KEY"):
        try:
            resp = requests.post("https://api.tavily.com/search", timeout=30, json={
                "api_key": os.environ["TAVILY_API_KEY"], "query": query, "max_results": 8})
            resp.raise_for_status()
            results = [{"title": r["title"], "href": r["url"], "body": r["content"]}
                       for r in resp.json().get("results", [])]
        except Exception:
            results = []

    # 2. Free fallback: scrape-based search, trying several engines in turn,
    #    because any single one may rate-limit or block us.
    if not results:
        from ddgs import DDGS
        for backend in ("bing", "duckduckgo", "brave", "google"):
            try:
                results = DDGS().text(query, max_results=8, backend=backend)
                if results:
                    break
            except Exception:
                continue

    if not results:
        return f"No results for {query!r}. Try a shorter or rephrased query."
    return "\n\n".join(f"{r['title']}\n{r['href']}\n{r['body']}" for r in results)


@tool
def fetch_webpage(url: str) -> str:
    """Download a web page and return its main text as markdown (links kept,
    so you can follow them with another fetch_webpage call)."""
    try:
        resp = requests.get(url, headers=HEADERS, timeout=30)
        resp.raise_for_status()
    except Exception as e:
        return f"Could not fetch {url}: {e}"

    # PDFs (papers!) need text extraction, not HTML parsing.
    if "pdf" in resp.headers.get("Content-Type", "") or resp.content[:5] == b"%PDF-":
        import io
        from pypdf import PdfReader
        reader = PdfReader(io.BytesIO(resp.content))
        return _truncate("\n".join(page.extract_text() or "" for page in reader.pages), 40_000)

    soup = BeautifulSoup(resp.text, "html.parser")
    for tag in soup(["script", "style", "nav", "footer", "header", "aside", "form", "noscript"]):
        tag.decompose()
    main = soup.find("main") or soup.find("article") or soup.body or soup
    return _truncate(markdownify(str(main), heading_style="ATX", strip=["img"]))


@tool
def youtube_transcript(url: str) -> str:
    """Get the spoken-word transcript (captions) of a YouTube video.
    Only covers what is SAID — it cannot tell you what is SHOWN on screen."""
    import re
    from youtube_transcript_api import YouTubeTranscriptApi
    match = re.search(r"(?:v=|youtu\.be/|shorts/)([\w-]{11})", url)
    if not match:
        return "Could not find a video id in that URL."
    try:
        transcript = YouTubeTranscriptApi().fetch(match.group(1))
    except Exception as e:
        return f"No transcript available: {type(e).__name__}. Try web_search about the video instead."
    return _truncate("\n".join(f"[{s.start:.0f}s] {s.text}" for s in transcript.snippets))


# --- Files ----------------------------------------------------------------------
@tool
def read_file(path: str) -> str:
    """Read an attached file. Spreadsheets (.xlsx/.xls/.csv) are returned as
    tables (every sheet, all rows and columns); code and text files are returned
    verbatim. For analysis/calculation on a spreadsheet, prefer python_repl with
    pandas (e.g. pd.read_excel(path)) so numbers are computed, not eyeballed."""
    from pathlib import Path
    import pandas as pd
    p = Path(path)
    if not p.exists():
        return f"File not found: {path}"
    suffix = p.suffix.lower()
    if suffix in (".xlsx", ".xls"):
        sheets = pd.read_excel(p, sheet_name=None)
        return _truncate("\n\n".join(f"Sheet '{name}' ({len(df)} rows):\n{df.to_string()}"
                                     for name, df in sheets.items()))
    if suffix == ".csv":
        return _truncate(pd.read_csv(p).to_string())
    if suffix in (".mp3", ".wav", ".m4a"):
        return "This is an audio file — use transcribe_audio(path)."
    if suffix in (".png", ".jpg", ".jpeg", ".gif", ".webp"):
        return "This is an image — use analyze_image(path, question)."
    return _truncate(p.read_text(errors="replace"))


@tool
def transcribe_audio(path: str) -> str:
    """Transcribe speech in an audio file (.mp3, .wav, .m4a) to text."""
    from openai import OpenAI
    with open(path, "rb") as f:
        result = OpenAI().audio.transcriptions.create(model="gpt-4o-transcribe", file=f)
    return result.text


@tool
def analyze_image(path: str, question: str) -> str:
    """Look at an image file and answer a question about it. Ask for precise,
    exhaustive descriptions (e.g. 'List every piece and its square')."""
    import base64
    import mimetypes
    import os
    from openai import OpenAI
    mime = mimetypes.guess_type(path)[0] or "image/png"
    with open(path, "rb") as f:
        b64 = base64.b64encode(f.read()).decode()
    resp = OpenAI().chat.completions.create(
        model=os.getenv("OPENAI_MODEL", "gpt-5.4-mini"),
        messages=[{"role": "user", "content": [
            {"type": "text", "text": question},
            {"type": "image_url", "image_url": {"url": f"data:{mime};base64,{b64}"}},
        ]}],
    )
    return resp.choices[0].message.content


TOOLS = [
    python_repl,
    wikipedia_search, wikipedia_page,
    web_search, fetch_webpage, youtube_transcript,
    read_file, transcribe_audio, analyze_image,
]