File size: 8,688 Bytes
84d8d95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
896bda6
 
 
 
 
 
 
 
 
84d8d95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0de769d
84d8d95
 
 
 
 
 
0de769d
 
 
 
 
 
 
 
 
84d8d95
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""LangGraph ReAct agent for the GAIA final assignment (Gemini + tools)."""
import base64
import io
import mimetypes
import os
import re
import contextlib
import traceback

from dotenv import load_dotenv
from langchain_core.messages import HumanMessage, SystemMessage
from langchain_core.tools import tool
from langchain_google_genai import ChatGoogleGenerativeAI
from langgraph.graph import START, MessagesState, StateGraph
from langgraph.prebuilt import ToolNode, tools_condition

load_dotenv(override=True)

GEMINI_API_KEY = os.getenv("GEMINI_API_KEY") or os.getenv("GOOGLE_API_KEY")
MODEL_NAME = os.getenv("GEMINI_MODEL", "gemini-3.8-flash")
MAX_TOOL_OUTPUT = 8000

with open(os.path.join(os.path.dirname(__file__), "system_prompt.txt"), encoding="utf-8") as f:
    SYSTEM_PROMPT = f.read()


def _clip(text: str) -> str:
    text = str(text)
    return text if len(text) <= MAX_TOOL_OUTPUT else text[:MAX_TOOL_OUTPUT] + "\n...[truncated]"


def _llm(**kwargs):
    return ChatGoogleGenerativeAI(
        model=MODEL_NAME, google_api_key=GEMINI_API_KEY, temperature=0, **kwargs
    )


# ---------------------------------------------------------------- search tools
@tool
def web_search(query: str) -> str:
    """Search the web (Tavily) and return up to 5 results with content.

    Args:
        query: The search query.
    """
    from langchain_tavily import TavilySearch

    res = TavilySearch(max_results=5).invoke({"query": query})
    items = res.get("results", []) if isinstance(res, dict) else res
    return _clip(
        "\n\n---\n\n".join(
            f"[{r.get('title', '')}]({r.get('url', '')})\n{r.get('content', '')}" for r in items
        )
    )


@tool
def wiki_search(query: str) -> str:
    """Search Wikipedia and return the top 2 pages (long content).

    Args:
        query: The search query.
    """
    from langchain_community.document_loaders import WikipediaLoader

    docs = WikipediaLoader(query=query, load_max_docs=2, doc_content_chars_max=6000).load()
    return _clip(
        "\n\n---\n\n".join(f"[{d.metadata.get('source', '')}]\n{d.page_content}" for d in docs)
    )


@tool
def arxiv_search(query: str) -> str:
    """Search arXiv and return the top 3 paper abstracts.

    Args:
        query: The search query.
    """
    from langchain_community.document_loaders import ArxivLoader

    docs = ArxivLoader(query=query, load_max_docs=3).load()
    return _clip("\n\n---\n\n".join(d.page_content[:1500] for d in docs))


@tool
def fetch_webpage(url: str) -> str:
    """Download a web page and return its readable text.

    Args:
        url: Full URL of the page.
    """
    import requests
    from bs4 import BeautifulSoup

    r = requests.get(url, timeout=30, headers={"User-Agent": "Mozilla/5.0"})
    r.raise_for_status()
    soup = BeautifulSoup(r.text, "html.parser")
    for t in soup(["script", "style", "nav", "footer"]):
        t.decompose()
    return _clip(re.sub(r"\n{3,}", "\n\n", soup.get_text("\n")))


@tool
def youtube_transcript(url: str) -> str:
    """Get the transcript of a YouTube video.

    Args:
        url: The YouTube video URL.
    """
    from youtube_transcript_api import YouTubeTranscriptApi

    m = re.search(r"(?:v=|youtu\.be/)([\w-]{11})", url)
    if not m:
        return "Could not parse video id."
    try:
        segs = YouTubeTranscriptApi().fetch(m.group(1))
        return _clip(" ".join(s.text for s in segs))
    except Exception as e:
        return (
            f"Transcript unavailable ({type(e).__name__}); YouTube may be blocked from this server. "
            "Do NOT retry this tool. Use web_search for the video title, description or discussions of it; "
            "if that fails, give your best-guess answer."
        )


# ------------------------------------------------------------------ file tools
@tool
def read_file(file_path: str) -> str:
    """Read a local file: txt/py/json/md, csv, xlsx/xls, or pdf. Returns its contents.

    Args:
        file_path: Local path to the file.
    """
    ext = os.path.splitext(file_path)[1].lower()
    try:
        if ext in (".csv",):
            import pandas as pd

            return _clip(pd.read_csv(file_path).to_string())
        if ext in (".xlsx", ".xls"):
            import pandas as pd

            sheets = pd.read_excel(file_path, sheet_name=None)
            return _clip("\n\n".join(f"## sheet: {n}\n{df.to_string()}" for n, df in sheets.items()))
        if ext == ".pdf":
            import fitz  # pymupdf

            with fitz.open(file_path) as doc:
                return _clip("\n".join(p.get_text() for p in doc))
        with open(file_path, encoding="utf-8", errors="replace") as f:
            return _clip(f.read())
    except Exception as e:
        return f"Error reading file: {e}"


@tool
def python_executor(code: str) -> str:
    """Execute Python code and return what it prints. Use print() for results.
    pandas, numpy, math, re, json, datetime are available. Use it for calculations and file processing.

    Args:
        code: Python source code.
    """
    buf = io.StringIO()
    try:
        with contextlib.redirect_stdout(buf), contextlib.redirect_stderr(buf):
            exec(code, {"__name__": "__main__"})
    except Exception:
        buf.write(traceback.format_exc(limit=3))
    return _clip(buf.getvalue() or "(no output; use print())")


def _media_message(file_path: str, prompt: str, default_mime: str) -> str:
    mime = mimetypes.guess_type(file_path)[0] or default_mime
    with open(file_path, "rb") as f:
        data = base64.b64encode(f.read()).decode()
    kind = "image_url" if mime.startswith("image") else "media"
    block = (
        {"type": "image_url", "image_url": {"url": f"data:{mime};base64,{data}"}}
        if kind == "image_url"
        else {"type": "media", "mime_type": mime, "data": data}
    )
    msg = HumanMessage(content=[{"type": "text", "text": prompt}, block])
    return _clip(_llm().invoke([msg]).content)


@tool
def analyze_image(file_path: str, question: str) -> str:
    """Look at a local image file (png/jpg) and answer a question about it (chess boards, charts, etc.).

    Args:
        file_path: Local path to the image.
        question: What to find out about the image.
    """
    try:
        return _media_message(file_path, question, "image/png")
    except Exception as e:
        return f"Error analyzing image: {e}"


@tool
def transcribe_audio(file_path: str) -> str:
    """Transcribe a local audio file (mp3/wav) word for word.

    Args:
        file_path: Local path to the audio file.
    """
    try:
        return _media_message(file_path, "Transcribe this audio verbatim. Output only the transcript.", "audio/mpeg")
    except Exception as e:
        return f"Error transcribing audio: {e}"


TOOLS = [
    web_search,
    wiki_search,
    arxiv_search,
    fetch_webpage,
    youtube_transcript,
    read_file,
    python_executor,
    analyze_image,
    transcribe_audio,
]


def build_graph():
    llm_with_tools = _llm().bind_tools(TOOLS)
    sys_msg = SystemMessage(content=SYSTEM_PROMPT)

    def assistant(state: MessagesState):
        return {"messages": [llm_with_tools.invoke([sys_msg] + state["messages"])]}

    builder = StateGraph(MessagesState)
    builder.add_node("assistant", assistant)
    builder.add_node("tools", ToolNode(TOOLS, handle_tool_errors=True))
    builder.add_edge(START, "assistant")
    builder.add_conditional_edges("assistant", tools_condition)
    builder.add_edge("tools", "assistant")
    return builder.compile()


def direct_answer(question: str) -> str:
    """Last-resort: answer without tools (used when the tool loop fails or runs out of steps)."""
    msgs = [
        SystemMessage(content=SYSTEM_PROMPT),
        HumanMessage(content=question + "\n\nTools are unavailable. Give your best-guess answer from your own knowledge now."),
    ]
    return extract_final_answer(_llm().invoke(msgs).content)


def extract_final_answer(text) -> str:
    """Return only what follows 'FINAL ANSWER:' (GAIA uses exact match)."""
    if isinstance(text, list):  # Gemini may return content blocks
        text = " ".join(b.get("text", "") if isinstance(b, dict) else str(b) for b in text)
    text = str(text)
    m = re.search(r"FINAL ANSWER:\s*(.*)", text, re.IGNORECASE | re.DOTALL)
    ans = (m.group(1) if m else text).strip().splitlines()[0] if (m or text.strip()) else ""
    return ans.strip().rstrip(".").strip()


if __name__ == "__main__":
    g = build_graph()
    out = g.invoke({"messages": [HumanMessage(content="What is 12 * 7 plus the number of planets in the solar system?")]})
    print(extract_final_answer(out["messages"][-1].content))