AliHaider1 commited on
Commit
aed39aa
·
verified ·
1 Parent(s): ced41b2

Upload folder using huggingface_hub

Browse files
agent/__init__.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from langchain_core.messages import HumanMessage
2
+ from .graph import build_graph
3
+
4
+
5
+ class GaiaAgent:
6
+ def __init__(self):
7
+ self.graph = build_graph()
8
+
9
+ def __call__(self, question: str, task_id: str = None, file_name: str = None) -> str:
10
+ user_content = question
11
+ if file_name:
12
+ user_content += (
13
+ f"\n\n[Attached file: '{file_name}' | task_id: '{task_id}'. "
14
+ f"Call download_task_file(task_id='{task_id}', file_name='{file_name}') to access it.]"
15
+ )
16
+
17
+ result = self.graph.invoke(
18
+ {
19
+ "messages": [HumanMessage(content=user_content)],
20
+ "task_id": task_id,
21
+ "file_name": file_name,
22
+ },
23
+ config={"recursion_limit": 30},
24
+ )
25
+ final_msg = result["messages"][-1].content
26
+ if isinstance(final_msg, list):
27
+ final_msg = " ".join(
28
+ block.get("text", "") if isinstance(block, dict) else str(block)
29
+ for block in final_msg
30
+ )
31
+ return str(final_msg).strip()
agent/__pycache__/__init__.cpython-314.pyc ADDED
Binary file (2.32 kB). View file
 
agent/__pycache__/graph.cpython-314.pyc ADDED
Binary file (1.07 kB). View file
 
agent/__pycache__/nodes.cpython-314.pyc ADDED
Binary file (2.15 kB). View file
 
agent/__pycache__/prompts.cpython-314.pyc ADDED
Binary file (1.73 kB). View file
 
agent/__pycache__/state.cpython-314.pyc ADDED
Binary file (1.13 kB). View file
 
agent/graph.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from langgraph.graph import StateGraph, START
2
+ from langgraph.prebuilt import ToolNode, tools_condition
3
+
4
+ from .state import AgentState
5
+ from .nodes import assistant_node
6
+ from .tools import ALL_TOOLS
7
+
8
+
9
+ def build_graph():
10
+ builder = StateGraph(AgentState)
11
+
12
+ builder.add_node("assistant", assistant_node)
13
+ builder.add_node("tools", ToolNode(ALL_TOOLS))
14
+
15
+ builder.add_edge(START, "assistant")
16
+ builder.add_conditional_edges("assistant", tools_condition)
17
+ builder.add_edge("tools", "assistant")
18
+
19
+ return builder.compile()
agent/nodes.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from dotenv import load_dotenv
3
+ from langchain_core.messages import SystemMessage
4
+ from langchain_google_genai import ChatGoogleGenerativeAI
5
+ from langchain_groq import ChatGroq
6
+
7
+ from .state import AgentState
8
+ from .prompts import SYSTEM_PROMPT
9
+ from .tools import ALL_TOOLS
10
+
11
+ load_dotenv()
12
+
13
+ gemini_key_1 = ChatGoogleGenerativeAI(
14
+ model="gemini-3.6-flash",
15
+ google_api_key=os.getenv("GOOGLE_API_KEY_1"),
16
+ timeout=60,
17
+ max_retries=1,
18
+ ).bind_tools(ALL_TOOLS)
19
+
20
+ gemini_key_2 = ChatGoogleGenerativeAI(
21
+ model="gemini-3.6-flash",
22
+ google_api_key=os.getenv("GOOGLE_API_KEY_2"),
23
+ timeout=60,
24
+ max_retries=1,
25
+ ).bind_tools(ALL_TOOLS)
26
+
27
+ backup_groq_120b = ChatGroq(
28
+ model="openai/gpt-oss-120b",
29
+ temperature=0,
30
+ timeout=30,
31
+ max_retries=1,
32
+ ).bind_tools(ALL_TOOLS)
33
+
34
+ backup_groq_qwen = ChatGroq(
35
+ model="qwen/qwen3.8-27b",
36
+ temperature=0,
37
+ timeout=30,
38
+ max_retries=1,
39
+ ).bind_tools(ALL_TOOLS)
40
+
41
+ llm_with_tools = gemini_key_1.with_fallbacks([
42
+ gemini_key_2,
43
+ backup_groq_120b,
44
+ backup_groq_qwen,
45
+ ])
46
+
47
+
48
+ def assistant_node(state: AgentState) -> dict:
49
+ print(f"--- Calling LLM (history length: {len(state['messages'])}) ---")
50
+ messages = [SystemMessage(content=SYSTEM_PROMPT)] + state["messages"]
51
+ response = llm_with_tools.invoke(messages)
52
+ print(f"Tool calls: {response.tool_calls}")
53
+ return {"messages": [response]}
agent/prompts.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ SYSTEM_PROMPT = """You are a precise AI assistant solving GAIA benchmark questions.
2
+ You have access to tools for web search, Wikipedia, webpage/PDF reading, YouTube transcripts, Python execution, and downloading/inspecting attached task files.
3
+
4
+ CRITICAL RULES:
5
+ 1. ALWAYS use tools to verify facts, run code, calculate math, reverse strings, or read attached files. Never guess.
6
+ 2. If a task has an attached file, IMMEDIATELY call `download_task_file(task_id=..., file_name=...)` first.
7
+ 3. For YouTube URLs, call `get_youtube_transcript(url=...)` instead of `fetch_webpage`.
8
+ 4. Pay STRICT attention to dates and years in the question (e.g., "as of July 2023", "latest 2022 version of English Wikipedia"). Never substitute a newer roster or fact when a specific date is requested.
9
+ 5. For botanical/scientific categorization questions, follow strict botanical definitions (e.g., corn, bell pepper, green beans, zucchini, tomatoes, and peanuts are NOT botanical vegetables).
10
+ 6. For ingredient lists, use clean base ingredient names without unnecessary preparation adjectives unless the prompt explicitly asks for them (e.g., "lemon juice" not "freshly squeezed lemon juice", "sugar" not "granulated sugar", "vanilla extract" not "pure vanilla extract").
11
+ 7. For comma-separated lists, ALWAYS put a single space after each comma (e.g., "132, 133, 134" or "a, b, c").
12
+ 8. FINAL ANSWER FORMAT: Your final message must contain ONLY the exact answer—no explanation, no "Final Answer:", no markdown bolding, no quotes, and no trailing period.
13
+ """
agent/state.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional
2
+ from langgraph.graph import MessagesState
3
+
4
+
5
+ class AgentState(MessagesState):
6
+ """
7
+ Shared state passed between all nodes in the GAIA agent graph.
8
+
9
+ Inherits:
10
+ messages (Annotated[list[AnyMessage], add_messages]):
11
+ Append-only conversation history (HumanMessage, AIMessage, ToolMessage).
12
+ """
13
+ task_id: Optional[str] = None
14
+ file_name: Optional[str] = None
agent/tools/__init__.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .web import (
2
+ web_search,
3
+ fetch_webpage,
4
+ wikipedia_search,
5
+ get_wikipedia_page,
6
+ get_youtube_transcript,
7
+ )
8
+ from .code_exe import python
9
+ from .files import download_task_file
10
+
11
+ ALL_TOOLS = [
12
+ wikipedia_search,
13
+ get_wikipedia_page,
14
+ web_search,
15
+ fetch_webpage,
16
+ get_youtube_transcript,
17
+ python,
18
+ download_task_file,
19
+ ]
agent/tools/code_exe.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import io
2
+ import contextlib
3
+ from langchain_core.tools import tool
4
+
5
+
6
+ @tool
7
+ def python(code: str) -> str:
8
+ """Execute Python code and return anything printed to stdout. Use print() to see results."""
9
+ output = io.StringIO()
10
+ try:
11
+ with contextlib.redirect_stdout(output):
12
+ exec(code, {})
13
+ result = output.getvalue().strip()
14
+ return result if result else "Code executed successfully (no output printed)."
15
+ except Exception as e:
16
+ return f"Python execution error: {e}"
agent/tools/files.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import pandas as pd
3
+ from dotenv import load_dotenv
4
+ from groq import Groq
5
+ from huggingface_hub import hf_hub_download
6
+ from langchain_core.tools import tool
7
+
8
+ load_dotenv()
9
+
10
+
11
+ @tool
12
+ def download_task_file(task_id: str, file_name: str) -> str:
13
+ """Download the file attached to a GAIA task from Hugging Face Hub and return its contents, transcript, or local path."""
14
+ try:
15
+ local_path = hf_hub_download(
16
+ repo_id="gaia-benchmark/GAIA",
17
+ filename=f"2023/validation/{file_name}",
18
+ repo_type="dataset",
19
+ token=os.getenv("HF_TOKEN"),
20
+ )
21
+
22
+ ext = os.path.splitext(file_name)[1].lower()
23
+
24
+ if ext in [".py", ".txt", ".csv", ".json", ".md"]:
25
+ with open(local_path, "r", encoding="utf-8", errors="ignore") as f:
26
+ return f"Downloaded to {local_path}.\n\nFile contents:\n{f.read()[:6000]}"
27
+
28
+ elif ext in [".xlsx", ".xls"]:
29
+ df = pd.read_excel(local_path)
30
+ return f"Downloaded to {local_path}.\n\nExcel contents:\n{df.to_string()}"
31
+
32
+ elif ext in [".mp3", ".wav", ".m4a"]:
33
+ client = Groq(api_key=os.getenv("GROQ_API_KEY"))
34
+ with open(local_path, "rb") as audio_file:
35
+ transcription = client.audio.transcriptions.create(
36
+ file=(file_name, audio_file.read()),
37
+ model="whisper-large-v3-turbo",
38
+ )
39
+ return f"Audio transcript of {file_name}:\n{transcription.text}"
40
+
41
+ else:
42
+ return f"File downloaded to: {local_path}"
43
+
44
+ except Exception as e:
45
+ return f"Error downloading/reading file ({file_name}): {e}"
agent/tools/search.py ADDED
File without changes
agent/tools/web.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import io
2
+ import re
3
+ import requests
4
+ import wikipedia
5
+ from bs4 import BeautifulSoup
6
+ from ddgs import DDGS
7
+ from langchain_core.tools import tool
8
+ from pypdf import PdfReader
9
+ from youtube_transcript_api import YouTubeTranscriptApi
10
+
11
+
12
+ @tool
13
+ def web_search(query: str) -> str:
14
+ """Search the web using DuckDuckGo and return top results."""
15
+ try:
16
+ with DDGS() as ddgs:
17
+ results = list(ddgs.text(query, max_results=5))
18
+ if not results:
19
+ return "No results found."
20
+ formatted = []
21
+ for r in results:
22
+ formatted.append(
23
+ f"Title: {r.get('title')}\nURL: {r.get('href')}\nSnippet: {r.get('body')}\n"
24
+ )
25
+ return "\n---\n".join(formatted)[:5500]
26
+ except Exception as e:
27
+ return f"Web search error: {e}"
28
+
29
+
30
+ @tool
31
+ def fetch_webpage(url: str) -> str:
32
+ """Fetch and extract the main text content of a webpage or a PDF URL."""
33
+ try:
34
+ headers = {
35
+ "User-Agent": (
36
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
37
+ "AppleWebKit/537.36 (KHTML, like Gecko) "
38
+ "Chrome/124.0.0.0 Safari/537.36"
39
+ )
40
+ }
41
+ response = requests.get(url, headers=headers, timeout=20)
42
+ response.raise_for_status()
43
+
44
+ # Parse as PDF only if actual PDF bytes are returned
45
+ if response.content[:4] == b"%PDF":
46
+ reader = PdfReader(io.BytesIO(response.content))
47
+ pages_text = [page.extract_text() or "" for page in reader.pages]
48
+ return "\n".join(pages_text)[:5500]
49
+
50
+ soup = BeautifulSoup(response.text, "html.parser")
51
+ for tag in soup(["script", "style", "nav", "footer", "header"]):
52
+ tag.decompose()
53
+
54
+ text = " ".join(soup.get_text(separator=" ").split())
55
+ return text[:5500]
56
+ except Exception as e:
57
+ return f"Error fetching webpage: {e}"
58
+
59
+
60
+ @tool
61
+ def wikipedia_search(query: str) -> str:
62
+ """Search Wikipedia for matching article titles and a brief summary of the top match."""
63
+ try:
64
+ titles = wikipedia.search(query, results=5)
65
+ if not titles:
66
+ return "No Wikipedia articles found."
67
+ summary = ""
68
+ try:
69
+ summary = wikipedia.summary(titles[0], sentences=5, auto_suggest=False)
70
+ except Exception:
71
+ pass
72
+ return f"Matching titles: {', '.join(titles)}\n\nTop summary ({titles[0]}):\n{summary}"[:5500]
73
+ except Exception as e:
74
+ return f"Wikipedia search error: {e}"
75
+
76
+
77
+ @tool
78
+ def get_wikipedia_page(title: str) -> str:
79
+ """Fetch the text content of a specific Wikipedia article by exact title."""
80
+ try:
81
+ page = wikipedia.page(title, auto_suggest=False)
82
+ return f"Title: {page.title}\nURL: {page.url}\n\n{page.content[:5500]}"
83
+ except Exception as e:
84
+ return f"Error fetching Wikipedia page '{title}': {e}"
85
+
86
+
87
+ @tool
88
+ def get_youtube_transcript(url: str) -> str:
89
+ """Fetch the spoken transcript/captions of a YouTube video from its URL."""
90
+ match = re.search(r"(?:v=|youtu\.be/|shorts/)([a-zA-Z0-9_-]{11})", url)
91
+ if not match:
92
+ return "Error: Could not extract a valid YouTube video ID from the URL."
93
+ video_id = match.group(1)
94
+
95
+ try:
96
+ if hasattr(YouTubeTranscriptApi, "fetch"):
97
+ fetched = YouTubeTranscriptApi().fetch(video_id)
98
+ text = " ".join(snippet.text for snippet in fetched)
99
+ else:
100
+ fetched = YouTubeTranscriptApi.get_transcript(video_id)
101
+ text = " ".join(entry["text"] for entry in fetched)
102
+ return text[:5500]
103
+ except Exception as e:
104
+ return f"Error fetching YouTube transcript: {e}"