Inigoalon commited on
Commit
4c9e4c6
·
verified ·
1 Parent(s): a1e1b88

Upload 17 files

Browse files
README.md CHANGED
@@ -1,14 +1,74 @@
1
- ---
2
- title: GAIA Execution
3
- emoji: 🐠
4
- colorFrom: yellow
5
- colorTo: red
6
- sdk: gradio
7
- sdk_version: 5.47.0
8
- app_file: app.py
9
- pinned: false
10
- license: apache-2.0
11
- short_description: GAIA Leaderboard
12
- ---
13
-
14
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # AI Agent for GAIA Dataset
2
+
3
+ This repository contains the code and solution developed for the final test of the Hugging Face course on AI Agents. It demonstrates the capabilities of an AI Agent using the GAIA dataset.
4
+
5
+ ## Repository Structure
6
+
7
+ - **`app.py`**: Fetches test questions from the Hugging Face server and executes the AI Agent.
8
+ - **`tools/`**: Contains custom tools created specifically to assist the Agent in solving tasks.
9
+
10
+ ## Performance and Considerations
11
+
12
+ The implemented solution achieved a **70% score** on the GAIA benchmark using the following models:
13
+
14
+ - Gemini-2.0-flash
15
+ - GPT-4.1-mini
16
+
17
+ However, due to the inherent non-deterministic behavior of these large language models (LLMs), outputs can occasionally vary even when using a temperature setting of `0`. Batched inference is likely the main contributor to this variability.
18
+
19
+ Additionally, a substantial number of tools were necessary to enhance performance given the limitations of these more economical models. For instance, a dedicated chess tool was implemented due to consistent inaccuracies in parsing image data by GPT-4.1-mini and Gemini models.
20
+
21
+ ## The certificate
22
+ <img src="certificate.jpg">
23
+
24
+ ## Installation
25
+
26
+ 1\. **Clone the repository**
27
+
28
+ ```bash
29
+ git clone <repository-url>
30
+ ```
31
+
32
+ 2\. **Set up Python virtual environment**
33
+
34
+ **Unix or MacOS**:
35
+ ```bash
36
+ python -m venv .venv
37
+ source .venv/bin/activate
38
+ ```
39
+
40
+ **Windows**:
41
+ ```batch
42
+ python -m venv .venv
43
+ .\.venv\Scripts\activate
44
+ ```
45
+
46
+ 3\. **Install dependencies**
47
+
48
+ ```bash
49
+ pip install -r requirements.txt
50
+ ```
51
+
52
+ 4\. **Configure environment variables**
53
+
54
+ **Unix or MacOS**:
55
+ ```bash
56
+ export HF_TOKEN="your_huggingface_token"
57
+ export OPENAI_API_KEY="your_openai_api_key"
58
+ export GEMINI_API_KEY="your_gemini_api_key"
59
+ ```
60
+
61
+ **Windows**:
62
+ ```batch
63
+ set HF_TOKEN=your_huggingface_token
64
+ set OPENAI_API_KEY=your_openai_api_key
65
+ set GEMINI_API_KEY=your_gemini_api_key
66
+ ```
67
+
68
+ 5\. **Run the application**
69
+
70
+ ```bash
71
+ python app.py
72
+ ```
73
+
74
+ Upon starting, log in as prompted and run the provided questions.
app.py ADDED
@@ -0,0 +1,387 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Importing necessary libraries and modules
2
+ import os
3
+ import gradio as gr
4
+ import requests
5
+ import inspect
6
+ import pandas as pd
7
+ from langgraph.graph import StateGraph, START, END
8
+ from typing_extensions import TypedDict
9
+ from typing import List, TypedDict, Annotated, Optional
10
+ from langchain_core.messages import AnyMessage, SystemMessage, HumanMessage
11
+ from langgraph.graph.message import add_messages
12
+ from langchain_community.tools import DuckDuckGoSearchRun
13
+ from langgraph.prebuilt import ToolNode, tools_condition
14
+ from PIL import Image
15
+ import requests
16
+ from io import BytesIO
17
+ import PyPDF2
18
+ import base64
19
+ from langchain_google_genai import ChatGoogleGenerativeAI
20
+ from langchain_openai import ChatOpenAI
21
+ from langchain_core.tools import tool
22
+ from dotenv import load_dotenv
23
+ import time
24
+ from langchain_community.tools import DuckDuckGoSearchRun
25
+ from langchain_community.utilities.duckduckgo_search import DuckDuckGoSearchAPIWrapper
26
+ from langchain_community.tools import BraveSearch
27
+ from tools.answer_question_from_file import AnswerQuestionFromFileTool
28
+ from tools.answer_question import AnswerQuestionTool
29
+ from tools.download_file import DownloadFile
30
+ from tools.reverse_string import ReverseString
31
+ from tools.web_search import WebSearchTool
32
+ from tools.wikipedia import WikipediaTool
33
+ from tools.youtube_transcript import YoutubeTranscriptTool
34
+ from tools.code_exec import PythonExecutionTool
35
+ from tools.code_gen import CodeGenTool
36
+ from tools.answer_excel import AnswerExcelTool
37
+ from contextlib import redirect_stdout
38
+ from tools.chess_tool import ChessTool
39
+ from tools.audio_tool import AudioTool
40
+ from tools.fetch_web_page import FetchWebPageTool
41
+
42
+ load_dotenv(".env", override=True)
43
+ BRAVE_API_KEY = os.getenv("BRAVE_API")
44
+
45
+ # Defining the State class which will hold various parameters related to the agent's state
46
+ class State(TypedDict):
47
+ file_path : str
48
+ file: Optional[str]
49
+ parsed_file: Optional[str]
50
+ messages: Annotated[list[AnyMessage], add_messages]
51
+ parsed_file_message: dict
52
+ question: str
53
+ response: str
54
+
55
+ # (Keep Constants as is)
56
+ # --- Constants ---
57
+ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
58
+
59
+ # --- Basic Agent Definition ---
60
+ # Defining the BasicAgent class which contains the logic for the AI agent
61
+ class BasicAgent:
62
+ def __init__(self):
63
+ # Initializing the BasicAgent with tools and an LLM (Large Language Model)
64
+ #tools = [CodeGenTool(), PythonExecutionTool(temp_dir="./"), YoutubeTranscriptTool(),
65
+ # AnswerQuestionFromFileTool(), AnswerQuestionTool(), DownloadFile(),
66
+ # ReverseString(), WebSearchTool(), WikipediaTool(), AnswerExcelTool(), ChessTool(), AudioTool(), FetchWebPageTool()]
67
+
68
+ tools = [CodeGenTool(), PythonExecutionTool(temp_dir="./"), YoutubeTranscriptTool(),
69
+ AnswerQuestionFromFileTool(), AnswerQuestionTool(), DownloadFile(),
70
+ ReverseString(), WebSearchTool(), WikipediaTool(), AnswerExcelTool(), ChessTool(), FetchWebPageTool()]
71
+
72
+ llm = ChatGoogleGenerativeAI(
73
+ model="gemini-2.0-flash",
74
+ temperature=0)
75
+ #llm = ChatOpenAI(model="gpt-4.1-mini", temperature=0) # Configuring the LLM
76
+ self.llm_with_tools = llm.bind_tools(tools)
77
+
78
+ builder = StateGraph(State) # Building a state graph for handling agent's state transitions
79
+
80
+ builder.add_node("assistant", self.assistant) # Adding nodes to the state graph
81
+ builder.add_node("tools", ToolNode(tools))
82
+ builder.add_node("final_answer", BasicAgent.final_answer)
83
+ #builder.add_node("download_file", BasicAgent.download_file_node)
84
+ #builder.add_node("parse_img", BasicAgent.parse_image)
85
+ #builder.add_node("parse_pdf", BasicAgent.parse_pdf)
86
+ #builder.add_node("parse_audio", BasicAgent.parse_audio)
87
+ #builder.add_node("extract_data", BasicAgent.extract_data_from_file)
88
+
89
+ builder.add_edge(START, "assistant")
90
+ #builder.add_conditional_edges("download_file", BasicAgent.determine_file_type,
91
+ # {"img": "parse_img", "pdf": "parse_pdf", "audio": "parse_audio", "end": END})
92
+ #builder.add_edge("parse_img", "assistant")
93
+ #builder.add_edge("parse_pdf", "assistant")
94
+ #builder.add_edge("parse_audio", "assistant")
95
+ builder.add_conditional_edges( # Adding conditional edges to manage state transitions based on tools' availability
96
+ "assistant", # Starting with the assistant node
97
+ tools_condition,
98
+ path_map={
99
+ "tools": "tools",
100
+ "__end__": "final_answer"
101
+ }
102
+ )
103
+
104
+ builder.add_edge("tools", "assistant") # Defining edges for state transitions
105
+ builder.add_edge("final_answer", END)
106
+
107
+ self.react_graph = builder.compile() # Compiling the state graph into a reactive graph
108
+
109
+
110
+ def __call__(self, question: str, task_id: str, file_name: Optional[str]) -> str:
111
+ # Handling the agent's main call
112
+ print(f"Agent received question (first 50 chars): {question[:50]}...")
113
+
114
+ messages = [HumanMessage(question)] # Creating a list of human messages
115
+ messages = self.react_graph.invoke({"messages": messages, "file_path": file_name, "question": question}) # Invoking the reactive graph with the current state
116
+
117
+ with open(f'messages_{task_id}.txt', 'w', encoding='utf-8') as out: # Writing the messages to a file
118
+ with redirect_stdout(out):
119
+ for m in messages['messages']:
120
+ m.pretty_print()
121
+
122
+ final_answer = messages["messages"][-1].content.strip() # Extracting the final answer from the messages
123
+ print(f"Final answer is {final_answer}")
124
+ return final_answer
125
+
126
+
127
+ def assistant(self, state: State):
128
+ # Defining the assistant node which processes the state
129
+ if state["file_path"]:
130
+ file_name = state["file_path"].split(".")[0]
131
+ file_extension = state["file_path"].split(".")[1]
132
+ else:
133
+ file_extension = None
134
+ file_name = None
135
+
136
+ prompt = f""" # Constructing the prompt for the language model
137
+ You are a general AI assistant. When I ask you a question:
138
+
139
+ Share your reasoning process clearly.
140
+
141
+ End with the exact template:
142
+ FINAL ANSWER: [YOUR FINAL ANSWER]
143
+
144
+ -------------------------------------------
145
+ Guidelines for FINAL ANSWER:
146
+
147
+ - Use a single number, a minimal phrase, or a comma-separated list of numbers and/or strings.
148
+
149
+ - For numbers, do not use commas, currency symbols, or percentage signs unless explicitly requested.
150
+
151
+ - For strings, avoid articles and abbreviations (e.g., no city abbreviations). Write digits in full text unless otherwise specified.
152
+
153
+ - Do not change capitalization of the terms you see unless it explicitly specified.
154
+
155
+ NEVER REPEAT THE SAME SEARCH MORE THAN ONCE, EVEN WITH SIMILAR TERMS. If you didn't find anything on the first go, it means there's nothing with that search query available.
156
+ If you can't find an answer just say you can't find it without repeating the same thing over and over.
157
+
158
+ Always read the prompt carefully.
159
+
160
+ Start with Wikipedia when searching for information. If Wikipedia doesn't have the answer, then use the web search tool. Use every available resource to find the correct answer.
161
+
162
+ IMPORTANT: Never make assumptions. Always use the provided tools!! If you are asked a question you think you know without using any tool, do not answer but invoke the answer_question_tool provided the WHOLE question in input.
163
+
164
+ NOTE: the question about the actor is tricky: they want to know who Bartłomiej played in Magda M.
165
+
166
+ If a file is provided (named {file_name} with extension {file_extension}), your first action MUST BE TO CALL the download_file tool with the URL:
167
+ {DEFAULT_API_URL}/files/{file_name}
168
+ Do **NOT** include the file extension in the URL and send WITHOUT MODIFICATION.
169
+ """
170
+
171
+ sys_msg = SystemMessage(content=prompt) # Creating a system message with the prompt
172
+
173
+ time.sleep(40) # Simulating a delay for processing
174
+ return {"messages": [self.llm_with_tools.invoke([sys_msg] + state["messages"])]}
175
+
176
+ def final_answer(state: State):
177
+ # Defining the final answer node which processes the state and returns an answer
178
+ system_prompt = f"""
179
+ You will be given an answer and a question. You MUST remove EVERYTHING not needed from the answer and answer the question exactly without reporting "FINAL ANSWER".
180
+ That is if you are being asked the number of something, you must not return the thought process, but just the number X.
181
+
182
+ You must be VERY CAREFUL of what the question asks!!!
183
+ For example:
184
+ if they ask you to give the full name of a city without abbreviations you should stick to it (for example, St. Petersburg should be Saint Petersburg).
185
+ if the first name is asked, you MUST return the first name only (Claus and not Claus Peter)!
186
+ Remove full stops at the end, they are not needed. If you return something comma separated, there must always be a space between the comma and the next letter. Always!!
187
+ """
188
+
189
+ human_prompt = f"""
190
+ Question: {state['question']}
191
+
192
+ Answer: {state['messages'][-1]}
193
+ """
194
+
195
+ human_msg = HumanMessage(content=human_prompt)
196
+
197
+ sys_msg = SystemMessage(content=system_prompt)
198
+
199
+ time.sleep(1)
200
+
201
+ llm = ChatGoogleGenerativeAI(
202
+ model="gemini-2.0-flash",
203
+ temperature=0)
204
+
205
+ response = llm.invoke([sys_msg, human_msg])
206
+
207
+ return {"messages": state["messages"] + [response]}
208
+
209
+ def run_and_submit_all( profile: gr.OAuthProfile | None):
210
+ """
211
+ Fetches all questions, runs the BasicAgent on them, submits all answers,
212
+ and displays the results.
213
+ """
214
+ # --- Determine HF Space Runtime URL and Repo URL ---
215
+ space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
216
+
217
+ if profile:
218
+ username= f"{profile.username}"
219
+ print(f"User logged in: {username}")
220
+ else:
221
+ print("User not logged in.")
222
+ return "Please Login to Hugging Face with the button.", None
223
+
224
+ api_url = DEFAULT_API_URL
225
+ questions_url = f"{api_url}/questions"
226
+ submit_url = f"{api_url}/submit"
227
+
228
+ # 1. Instantiate Agent ( modify this part to create your agent)
229
+ try:
230
+ agent = BasicAgent()
231
+ except Exception as e:
232
+ print(f"Error instantiating agent: {e}")
233
+ return f"Error initializing agent: {e}", None
234
+ # In the case of an app running as a hugging Face space, this link points toward your codebase ( usefull for others so please keep it public)
235
+ agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
236
+ print(agent_code)
237
+
238
+ # 2. Fetch Questions
239
+ print(f"Fetching questions from: {questions_url}")
240
+ try:
241
+ response = requests.get(questions_url, timeout=15)
242
+ response.raise_for_status()
243
+ questions_data = response.json()
244
+ if not questions_data:
245
+ print("Fetched questions list is empty.")
246
+ return "Fetched questions list is empty or invalid format.", None
247
+ print(f"Fetched {len(questions_data)} questions.")
248
+ except requests.exceptions.RequestException as e:
249
+ print(f"Error fetching questions: {e}")
250
+ return f"Error fetching questions: {e}", None
251
+ except requests.exceptions.JSONDecodeError as e:
252
+ print(f"Error decoding JSON response from questions endpoint: {e}")
253
+ print(f"Response text: {response.text[:500]}")
254
+ return f"Error decoding server response for questions: {e}", None
255
+ except Exception as e:
256
+ print(f"An unexpected error occurred fetching questions: {e}")
257
+ return f"An unexpected error occurred fetching questions: {e}", None
258
+
259
+ # Running the agent on the fetched questions
260
+ results_log = []
261
+ answers_payload = []
262
+ print(f"Running agent on {len(questions_data)} questions...")
263
+ for item in questions_data:
264
+ task_id = item.get("task_id")
265
+ question_text = item.get("question")
266
+ file_name = item.get("file_name")
267
+ if not task_id or question_text is None:
268
+ print(f"Skipping item with missing task_id or question: {item}")
269
+ continue
270
+ try:
271
+ submitted_answer = agent(question_text, task_id, file_name)
272
+
273
+ answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
274
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
275
+ except Exception as e:
276
+ print(f"Error running agent on task {task_id}: {e}")
277
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
278
+
279
+ if not answers_payload:
280
+ print("Agent did not produce any answers to submit.")
281
+ return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
282
+
283
+ # 4. Prepare Submission
284
+ submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload} # Preparing the data for submission
285
+ status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
286
+ print(status_update)
287
+
288
+ # 5. Submit
289
+ print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
290
+ # Submitting the answers
291
+ try:
292
+ response = requests.post(submit_url, json=submission_data, timeout=60)
293
+ response.raise_for_status()
294
+ result_data = response.json()
295
+ final_status = (
296
+ f"Submission Successful!\n"
297
+ f"User: {result_data.get('username')}\n"
298
+ f"Overall Score: {result_data.get('score', 'N/A')}% "
299
+ f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
300
+ f"Message: {result_data.get('message', 'No message received.')}"
301
+ )
302
+ print("Submission successful.")
303
+ results_df = pd.DataFrame(results_log)
304
+ return final_status, results_df
305
+ except requests.exceptions.HTTPError as e:
306
+ error_detail = f"Server responded with status {e.response.status_code}."
307
+ try:
308
+ error_json = e.response.json()
309
+ error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
310
+ except requests.exceptions.JSONDecodeError:
311
+ error_detail += f" Response: {e.response.text[:500]}"
312
+ status_message = f"Submission Failed: {error_detail}"
313
+ print(status_message)
314
+ results_df = pd.DataFrame(results_log)
315
+ return status_message, results_df
316
+ except requests.exceptions.Timeout:
317
+ status_message = "Submission Failed: The request timed out."
318
+ print(status_message)
319
+ results_df = pd.DataFrame(results_log)
320
+ return status_message, results_df
321
+ except requests.exceptions.RequestException as e:
322
+ status_message = f"Submission Failed: Network error - {e}"
323
+ print(status_message)
324
+ results_df = pd.DataFrame(results_log)
325
+ return status_message, results_df
326
+ except Exception as e:
327
+ status_message = f"An unexpected error occurred during submission: {e}"
328
+ print(status_message)
329
+ results_df = pd.DataFrame(results_log)
330
+ return status_message, results_df
331
+
332
+
333
+ # Building the Gradio interface using Blocks
334
+ with gr.Blocks() as demo:
335
+ gr.Markdown("# Basic Agent Evaluation Runner") # Title of the interface
336
+ gr.Markdown(
337
+ """
338
+ # Instructions for the interface usage
339
+
340
+ 1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
341
+ 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
342
+ 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
343
+
344
+ ---
345
+ **Disclaimers:**
346
+ Once clicking on the "submit button, it can take quite some time ( this is the time for the agent to go through all the questions).
347
+ This space provides a basic setup and is intentionally sub-optimal to encourage you to develop your own, more robust solution. For instance for the delay process of the submit button, a solution could be to cache the answers and submit in a seperate action or even to answer the questions in async.
348
+ """
349
+ )
350
+
351
+ gr.LoginButton() # Login button for Hugging Face account
352
+
353
+ run_button = gr.Button("Run Evaluation & Submit All Answers")
354
+
355
+ status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
356
+ # Removed max_rows=10 from DataFrame constructor
357
+ results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
358
+
359
+ run_button.click(
360
+ fn=run_and_submit_all,
361
+ outputs=[status_output, results_table]
362
+ )
363
+
364
+ if __name__ == "__main__":
365
+ # Launching Gradio interface for the application
366
+ print("\n" + "-"*30 + " App Starting " + "-"*30)
367
+ # Check for SPACE_HOST and SPACE_ID at startup for information
368
+ space_host_startup = os.getenv("SPACE_HOST")
369
+ space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
370
+
371
+ if space_host_startup:
372
+ print(f"✅ SPACE_HOST found: {space_host_startup}")
373
+ print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
374
+ else:
375
+ print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
376
+
377
+ if space_id_startup: # Print repo URLs if SPACE_ID is found
378
+ print(f"✅ SPACE_ID found: {space_id_startup}")
379
+ print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
380
+ print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
381
+ else:
382
+ print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
383
+
384
+ print("-"*(60 + len(" App Starting ")) + "\n")
385
+
386
+ print("Launching Gradio Interface for Basic Agent Evaluation...")
387
+ demo.launch(debug=True, share=False)
certificate.jpg ADDED
requirements.txt ADDED
Binary file (8.17 kB). View file
 
tools/answer_excel.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Importing necessary libraries and modules
2
+ from langchain_core.tools.base import BaseTool
3
+ from langchain_experimental.agents.agent_toolkits import create_pandas_dataframe_agent
4
+ import pandas as pd
5
+ from langchain_google_genai import ChatGoogleGenerativeAI
6
+ from langchain.agents.agent_types import AgentType
7
+
8
+ # Defining the AnswerExcelTool class which extends BaseTool
9
+ class AnswerExcelTool(BaseTool):
10
+ name : str = "answer_excel_tool"
11
+ description: str = "Given the path to a file containing an excel file and a query, this tool tries to get an answer by querying the excel file. Provide the whole question in input. Another agent will later break down the task."
12
+
13
+ def _run(self, query: str, file_path: str) -> str:
14
+ # Method to run the tool, using a query and the file path to an Excel file
15
+ df = pd.read_excel(file_path) # Reading the Excel file into a DataFrame
16
+
17
+ llm = ChatGoogleGenerativeAI(model="gemini-2.0-flash", temperature=0) # Configuring the LLM
18
+
19
+ agent_executor = create_pandas_dataframe_agent(
20
+ # Creating a Pandas DataFrame agent with the LLM and DataFrame
21
+ llm,
22
+ df,
23
+ agent_type=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
24
+ verbose=True,
25
+ allow_dangerous_code=True # IMPORTANT: Understand the risks
26
+ )
27
+
28
+ return agent_executor(query) # Executing the query using the agent
tools/answer_question.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Importing necessary libraries and modules
2
+ from langchain_google_genai import ChatGoogleGenerativeAI
3
+ from pydantic import PrivateAttr
4
+ from langchain_core.tools.base import BaseTool
5
+ from langchain_core.messages import AnyMessage, SystemMessage, HumanMessage
6
+ from langchain_openai import ChatOpenAI
7
+ import time
8
+ from openai import OpenAI
9
+
10
+ # Defining the AnswerQuestionTool class which extends BaseTool
11
+ class AnswerQuestionTool(BaseTool):
12
+ name : str = "answer_question_tool"
13
+ description: str = "Use this tool to answer any elementary question that you can solve without needing access to any external tool. Simply provide the question in input, reporting the whole question including desired output format. You can use this tool for example for vegetable classification."
14
+ _llm = PrivateAttr()
15
+ _system_prompt = PrivateAttr()
16
+
17
+ def __init__(self):
18
+ # Initializing the AnswerQuestionTool
19
+ super().__init__()
20
+ #self._llm = ChatGoogleGenerativeAI(
21
+ # model="gemini-2.0-flash",
22
+ # temperature=0)
23
+ #self._llm = ChatOpenAI(model="o4-mini", temperature=0)
24
+
25
+
26
+ self._system_prompt = SystemMessage("""You are a helpful assistant.
27
+ You will be given a question and you will have to answer that question.
28
+ Provide also the reasoning for your answer as well as your final answer.
29
+
30
+ When provided with a list you must stick with the exact terms provided in the list and not make any modification.
31
+ Green beans, corn and zucchini are NOT VEGEATABLES BOTANICALLY!
32
+ Let's think step by step.
33
+ """)
34
+
35
+ def _run(self, question: str) -> str:
36
+ # Method to run the tool and get an answer for the given question
37
+ human_message = HumanMessage(
38
+ # Creating a human message with the question content
39
+ content=[
40
+ {"type": "text", "text": question},
41
+ ]
42
+ )
43
+
44
+ time.sleep(5) # Adding a delay for rate limits
45
+ client = OpenAI() # Initializing the OpenAI client
46
+ response = client.responses.create(
47
+ # Creating a response using OpenAI's API
48
+ model="o4-mini",
49
+ messages = [
50
+ {
51
+ "role": "system", "content": self._system_prompt.text()
52
+ },
53
+ {
54
+ "role": "user", "content": question
55
+ }]
56
+ )
57
+ #response = self._llm.invoke([self._system_prompt, human_message])
58
+
59
+ return response # Returning the response from the OpenAI API
tools/answer_question_from_file.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Importing necessary libraries and modules
2
+ from langchain_core.tools.base import BaseTool
3
+ from langchain_core.messages import AnyMessage, SystemMessage, HumanMessage
4
+ from langchain_google_genai import ChatGoogleGenerativeAI
5
+ from pydantic import PrivateAttr
6
+ import os
7
+ from dotenv import load_dotenv
8
+ import whisper
9
+ import base64
10
+
11
+ load_dotenv(".env", override=True) # Loading environment variables
12
+
13
+ #AZURE_OPENAI_ENDPOINT = os.getenv("AZURE_OPENAI_ENDPOINT") # Fetching Azure OpenAI endpoint from environment
14
+ #AZURE_OPENAI_API_KEY = os.getenv("AZURE_OPENAI_API_KEY")
15
+ #OPENAI_API_VERSION = os.getenv("OPENAI_API_VERSION_GEN", "2023-12-01-preview") # Default API version
16
+ # AZURE_OPENAI_DEPLOYMENT_NAME will be used as the 'model' for API calls
17
+ #AZURE_OPENAI_DEPLOYMENT_NAME = "gpt-4.1"
18
+
19
+
20
+ # Defining the AnswerQuestionFromFileTool class which extends BaseTool
21
+ class AnswerQuestionFromFileTool(BaseTool):
22
+ name: str = "answer_question_from_file_tool"
23
+ description: str = """
24
+ This tool allows you to answer a question taking into account information that were provided inside a file.
25
+ You must provide the file in b64 when processing here.
26
+
27
+ Args:
28
+ The question that needs to be answered.
29
+ The file extension of the file that is being processed.
30
+ """
31
+ _llm = PrivateAttr()
32
+
33
+ def __init__(self):
34
+ # Initializing the AnswerQuestionFromFileTool
35
+ super().__init__()
36
+ self._llm = ChatGoogleGenerativeAI( # Setting up the LLM with specific parameters
37
+ model="gemini-2.0-flash",
38
+ temperature=0)
39
+
40
+
41
+ def _run(self, question: str, file_name: str, file_extension: str) -> str:
42
+
43
+ with open(file_name, "rb") as f:
44
+ file = f.read()
45
+
46
+ if file_extension in ["png", "jpg"]:
47
+ encoded_file = base64.b64encode(file).decode("utf-8")
48
+
49
+ message = {"type": "image_url", "image_url": f"data:image/png;base64,{encoded_file}"}
50
+ elif file_extension == "pdf":
51
+ encoded_file = base64.b64encode(file).decode("utf-8")
52
+ message = {"type": "image_url",
53
+ "image_url": f"data:application/pdf;base64,{encoded_file}"
54
+ }
55
+ else:
56
+ message = {"type": "text", "text": "The file is not supported."}
57
+
58
+ message_local = HumanMessage(
59
+ content=[
60
+ {"type": "text", "text": question + "\nLet's think step by step."},
61
+ message,
62
+ ]
63
+ )
64
+
65
+ response = self._llm.invoke([message_local])
66
+
67
+ return response
68
+
69
+
tools/audio_tool.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Importing necessary libraries and modules
2
+ from langchain_core.tools.base import BaseTool
3
+ import whisper
4
+ from langchain_google_genai import ChatGoogleGenerativeAI
5
+ from langchain_core.messages import AnyMessage, SystemMessage, HumanMessage
6
+ from pathlib import Path
7
+ import os
8
+ from transformers import pipeline
9
+ import torch
10
+ from langchain_openai import ChatOpenAI
11
+ import time
12
+
13
+ # Defining the AudioTool class which extends BaseTool
14
+ class AudioTool(BaseTool):
15
+ name : str = "answer_question_audio_tool"
16
+ description: str = "This tool will reply to a query based on the audio given the path of a locally stored file. This file DOES NOT DOWNLOAD the file from the web. Run the download_file_tool first"
17
+
18
+ def _run(self, query: str, file_path: str) -> str:
19
+ # Method to transcribe the provided audio file and answer the query using LLM
20
+ try:
21
+ #pipe = pipeline(
22
+ # task="automatic-speech-recognition",
23
+ # model="openai/whisper-base",
24
+ # torch_dtype=torch.float32,
25
+ # device=0,
26
+ # return_timestamps=True
27
+ #)
28
+ #result = pipe(str(Path("./") / Path(file_path)), return_timestamps=True)
29
+ model = whisper.load_model("base")
30
+ result = model.transcribe(audio=str(Path("./") / Path(file_path)), language='en') # Transcribing the audio using Whisper model
31
+ except Exception as e:
32
+ print("Exception", e)
33
+
34
+ print(result["text"])
35
+
36
+ human_message = HumanMessage([{"type": "text", "text": query},
37
+ {"type": "text", "text": f"\n\nTranscript: {result['text']}"}])
38
+
39
+ system_message = SystemMessage("""You are a helpful assistant. Whenever you receive a transcript of an audio recording along with a user's query:
40
+
41
+ 1. Carefully read the query multiple times to ensure you fully grasp what is being asked.
42
+
43
+ 2. Start by thinking, in clear bullet points, each precise requirement implied by the user's instructions (e.g., which portions of the transcript to use, what to include or exclude, and any specific formatting).
44
+
45
+ 3. After thinking more about the requirements, fulfill the request exactly as specified. Follow all content and formatting rules without deviation (for instance, “list only names,” “omit quantities,” “use comma-separated values,” “alphabetize,” etc.).
46
+
47
+ 4. Ensure that your final answer adheres strictly to the user's criteria and contains nothing beyond what was requested.
48
+
49
+ Always prioritize accuracy and strict adherence to the user's stated needs before providing the answer. REPLY ONLY WITH WHAT THE HUMAN ASKED. Return only the final answer!""")
50
+
51
+ time.sleep(5)
52
+ llm = ChatOpenAI(model="gpt-4.1-mini", temperature=0)
53
+
54
+ response = llm.invoke([system_message, human_message]) # Getting the response from the LLM
55
+
56
+ return response # Returning the response from the LLM
57
+
58
+
59
+
tools/chess_tool.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Importing necessary libraries and modules
2
+ from langchain_core.tools.base import BaseTool
3
+ from chessimg2pos import predict_fen
4
+ from stockfish import Stockfish
5
+ import chess
6
+
7
+ # Defining the ChessTool class which extends BaseTool
8
+ class ChessTool(BaseTool):
9
+ name : str = "chess_tool"
10
+ description : str = "Given the path of an image, this tool returns the best next move that can be done on the chessboard. You must give ONLY the PATH of the image here! Pass in input b or w as color_turn based on whose turn is it. Use w if unspecified."
11
+
12
+ def _run(self, img_path: str, color_turn: str) -> str:
13
+ # Method to analyze the chessboard image and return the best move
14
+ # Get the FEN string
15
+ fen = predict_fen("./downloaded_files/image.png") # Predicting the FEN string from the chessboard image
16
+
17
+ # The fen predicted is always with a1 at the bottom left.
18
+ # If it's black turn than the bottom left is h8, you need to reverse the positions retrieved.
19
+ if color_turn == "b":
20
+ ranks = fen.split('/')
21
+ rotated_matrix = []
22
+ for old_row in reversed(ranks):
23
+ rotated_matrix.append(list(reversed(old_row)))
24
+ final_fen = "/".join(["".join(row) for row in rotated_matrix])
25
+ for length in reversed(range(2, 9)):
26
+ final_fen = final_fen.replace(length * "1", str(length))
27
+ else:
28
+ final_fen = fen
29
+
30
+ fen = f"{final_fen} {color_turn} - - 0 1"
31
+
32
+ try:
33
+ # Initializing Stockfish chess engine
34
+ stockfish = Stockfish(path="C:/Users/FORMAGGA/Documents/personal/stockfish-windows-x86-64-avx2/stockfish/stockfish-windows-x86-64-avx2.exe")
35
+
36
+ stockfish.set_fen_position(fen)
37
+
38
+ next_move = str(stockfish.get_best_move()) # Getting the best move from Stockfish
39
+ except Exception as e:
40
+ print("Exception", e)
41
+ raise e
42
+
43
+ piece = stockfish.get_what_is_on_square(next_move[:2]) # Getting the piece on the starting square of the move
44
+
45
+ next_move_fen = piece.name + next_move[2:] # Constructing the FEN representation of the move
46
+
47
+ return next_move_fen # Returning the best move in FEN format
tools/code_exec.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Importing necessary libraries and modules
2
+ from langchain_core.tools.base import BaseTool, ToolException
3
+ from typing import Optional
4
+ import subprocess
5
+ import tempfile
6
+ import os
7
+ from pydantic import PrivateAttr
8
+
9
+ # Defining the PythonExecutionTool class which extends BaseTool
10
+ class PythonExecutionTool(BaseTool):
11
+ # A LangChain “tool” that takes a string of Python code,
12
+ # writes it to a temporary .py file, executes it in a fresh
13
+ # Python subprocess, captures stdout/stderr, and returns the result.
14
+
15
+ name : str = "python_execution"
16
+ description : str = (
17
+ "Executes a string of Python code in an isolated subprocess. "
18
+ "Returns stdout on success, or stderr (with exit code) on failure."
19
+ )
20
+ _python_executable: str = PrivateAttr()
21
+ _timeout: int = PrivateAttr()
22
+ _temp_dir: str = PrivateAttr()
23
+
24
+ def __init__(
25
+ self,
26
+ python_executable: str = "C:\\Users\\FORMAGGA\\Documents\\personal\\Final_Assignment_Template\\.venv\\Scripts\\python.exe",
27
+ timeout: int = 5,
28
+ *,
29
+ temp_dir: Optional[str] = None
30
+ ):
31
+
32
+ """
33
+ :param python_executable: Path to the Python interpreter to invoke.
34
+ :param timeout: Maximum seconds to allow the code to run.
35
+ :param temp_dir: Optional directory in which to create the temp file.
36
+ """
37
+ super().__init__()
38
+ self._python_executable = python_executable
39
+ self._timeout = timeout
40
+ self._temp_dir = temp_dir
41
+
42
+ def _run(self, code: str) -> str:
43
+ """
44
+ Synchronously execute the provided Python code.
45
+ :param code: The complete Python source to run.
46
+ :return: Captured stdout if exit code is 0; otherwise stderr + exit code.
47
+ :raises ToolException: On internal error (e.g. unable to write temp file).
48
+ """
49
+ # 1. Write code to a temporary file on disk to avoid shell-quoting issues.
50
+ try:
51
+ with tempfile.NamedTemporaryFile(
52
+ suffix=".py", delete=False, dir=self._temp_dir, mode="w", encoding="utf-8"
53
+ ) as tmp:
54
+ tmp.write(code)
55
+ tmp_path = tmp.name
56
+ except Exception as e:
57
+ raise ToolException(f"Failed to write temp file: {e!r}")
58
+
59
+ # 2. Invoke a fresh Python process on that file, capturing stdout & stderr.
60
+ try:
61
+ result = subprocess.run(
62
+ [self._python_executable, "-u", tmp_path],
63
+ stdout=subprocess.PIPE,
64
+ stderr=subprocess.PIPE,
65
+ text=True,
66
+ timeout=self._timeout,
67
+ )
68
+ except subprocess.TimeoutExpired:
69
+ return f"⚠️ Execution timed out after {self._timeout} seconds."
70
+ except Exception as e:
71
+ raise ToolException(f"Failed to launch subprocess: {e!r}")
72
+ finally:
73
+ # 3. Clean up the temp file no matter what
74
+ try:
75
+ os.remove(tmp_path)
76
+ except OSError:
77
+ pass
78
+
79
+ # 4. Process the result
80
+ if result.returncode != 0:
81
+ return (
82
+ f"❌ Process exited with code {result.returncode}.\n"
83
+ f"stderr:\n{result.stderr}"
84
+ )
85
+ return result.stdout
tools/code_gen.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from langchain_core.tools.base import BaseTool
2
+ from langchain_core.messages import AnyMessage, SystemMessage, HumanMessage
3
+ from langchain_google_genai import ChatGoogleGenerativeAI
4
+ from langchain_openai import AzureChatOpenAI
5
+ import os
6
+ from dotenv import load_dotenv
7
+
8
+ load_dotenv(".env", override=True)
9
+
10
+ AZURE_OPENAI_ENDPOINT = os.getenv("AZURE_OPENAI_ENDPOINT_GEN")
11
+ AZURE_OPENAI_API_KEY = os.getenv("AZURE_OPENAI_API_KEY_GEN")
12
+ OPENAI_API_VERSION = os.getenv("OPENAI_API_VERSION_GEN", "2023-12-01-preview") # Default API version
13
+ # AZURE_OPENAI_DEPLOYMENT_NAME will be used as the 'model' for API calls
14
+ AZURE_OPENAI_DEPLOYMENT_NAME = "gpt-4.1"
15
+
16
+ class CodeGenTool(BaseTool):
17
+ name : str = "code_generator_tool"
18
+ description: str = "Given the instructions provided, it generates Python code as text. It's important that the instructions provide: which args must be provided in input, the content of the function and what is the desired output."
19
+
20
+ def _run(self, function_description: str, input: str, output: str) -> str:
21
+ if not function_description:
22
+ return "You need to pass in a function description. Retry providing the right parameters."
23
+
24
+ system = SystemMessage("""You are an expert software engineer, your goal is to generate a piece of code.
25
+ YOU MUST GENERATE A **PYTHON** FUNCTION.
26
+ You will be given a description of what the function needs to do, for example "Generate a function that retrieves a web page from the internet".
27
+ Then you will be given information about what the input parameters are and the output.
28
+
29
+ In the output code you must list the imports as well.
30
+ It's VERY IMPORTANT that you stick to the contraints given for input and output.
31
+ If you believe there is a better way to do things, IGNORE THIS IDEA and stick to what is given in input.
32
+ """)
33
+
34
+ human = HumanMessage(f"Description of the function:\n{function_description}\n\nInput parameters:\n{input}\n\nOutput result:\n{output}\n\n")
35
+
36
+ llm = ChatGoogleGenerativeAI(
37
+ model="gemini-2.0-flash",
38
+ temperature=0.5)
39
+
40
+ response = llm.invoke([system, human])
41
+
42
+ return response
tools/download_file.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from langchain_core.tools.base import BaseTool
2
+ import requests
3
+ import base64
4
+ import pandas as pd
5
+ import os
6
+ import tempfile
7
+ import whisper
8
+
9
+ class DownloadFile(BaseTool):
10
+ name : str = "download_file_tool"
11
+ description: str = """
12
+ This tool downloads a file (image, pdf, python code, excel, etc.) given the name of the file. The url for the request will be composed in the function so ONLY the name of the file should be passed in.
13
+
14
+ You may have to download a file in 2 different scenarios:
15
+ - A file given already as part of the task. In this case the format of the url must be: {DEFAULT_API_URL}/files/{file_name} THE EXTENSION OF THE FILE MUST NOT(!!) BE INCLUDED!
16
+ - A url retrieved from the internet in the format https://some_url. In that case, you simply need to provide the url of the file that needs to be retrieved.
17
+
18
+ Args:
19
+ file_name: the name of the file to be retrieved DEFAULT_API_URL/files/task_id
20
+ file_extension: the extension of the file, without the dot. So for example "pdf", "img", "py", "xlsx", etc.
21
+
22
+ Output:
23
+ IF the file is a document, image or audio:
24
+ A string with the path to the file.
25
+
26
+ IF the file is a piece of code:
27
+ A dict made of:
28
+ The text of the image
29
+
30
+ IF the file is an excel:
31
+ A dict made of:
32
+ A pandas dataframe
33
+ """
34
+
35
+ def _run(self, file_url: str, file_extension: str) -> dict:
36
+ response = requests.get(file_url)
37
+
38
+ if response.status_code == 200:
39
+ msg = "File downloaded successfully!!"
40
+ if file_extension in ["png", "jpg", "pdf"]:
41
+ file = response.content
42
+
43
+ with open("downloaded_files/image.png", "wb") as f:
44
+ f.write(file)
45
+
46
+ return "downloaded_files/image.png"
47
+ elif file_extension in ["mp3", "wav"]:
48
+ res = response.content
49
+ with open("downloaded_files/audio.mp3", mode="wb") as f:
50
+ f.write(res)
51
+
52
+ return f"./downloaded_files/audio.{file_extension}"
53
+
54
+ elif file_extension == "py":
55
+ return {"text": response.text}
56
+ elif file_extension == "xlsx":
57
+ file_name = file_url.split("/")[-1]
58
+
59
+ with open(f"./downloaded_files/{file_name}.xlsx", "wb") as f:
60
+ f.write(response.content)
61
+
62
+ return f"./downloaded_files/{file_name}.xlsx"
63
+ else:
64
+ return "The file extension is not valid."
65
+ else:
66
+ msg = "There was an error downloading the file."
67
+
68
+ return msg
69
+
70
+
71
+
72
+
73
+
74
+
tools/fetch_web_page.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Importing necessary libraries and modules
2
+ from langchain_core.tools.base import BaseTool
3
+ from typing import List
4
+ import requests
5
+
6
+ # Defining the FetchWebPageTool class which extends BaseTool
7
+ class FetchWebPageTool(BaseTool):
8
+ name : str = "fetch_web_page_tool"
9
+ description: str = "Provided the urls of 1 or more web pages, this tool returns the full content of the web page. This tool needs to be called AFTER calling the web_page_tool. It's important to fetch only pages which are useful to your task!"
10
+
11
+ def _run(self, urls: List[str]) -> List[str]:
12
+ # Method to fetch the full content of the provided web pages
13
+ pages = [requests.get(url).text for url in urls] # Fetching the content of each URL
14
+
15
+ return pages # Returning the fetched content of the web pages
tools/reverse_string.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ from langchain_core.tools.base import BaseTool
2
+
3
+ class ReverseString(BaseTool):
4
+ name: str = "reverse_string_tool"
5
+ description: str = ("This tool inverts the order of the characters within a sentence. It is particularly useful if you can't understand the content in any language.")
6
+
7
+ def _run(self, string: str) -> str:
8
+ return string[::-1]
tools/web_search.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Importing necessary libraries and modules
2
+ from langchain_core.tools.base import BaseTool
3
+ from dotenv import load_dotenv
4
+ from langchain_community.utilities import DuckDuckGoSearchAPIWrapper
5
+ from langchain_community.tools import TavilySearchResults, DuckDuckGoSearchResults
6
+ from langchain_tavily import TavilySearch
7
+ import os
8
+ from pydantic import PrivateAttr
9
+ from langchain_community.document_loaders import WebBaseLoader
10
+ import json
11
+ import requests
12
+
13
+ load_dotenv(".env", override=True) # Loading environment variables
14
+
15
+ # Defining the WebSearchTool class which extends BaseTool
16
+ class WebSearchTool(BaseTool):
17
+ name: str = "web_search_tool"
18
+ description: str = "Perform a web search and extract concise factual answers. The query should be concise, below 400 characters. Use for online facts not in GAIA/Wikipedia—e.g. sports stats, Olympic participation, published papers, museum specimen locations, competition winners, and other up-to-date info."
19
+ _search: TavilySearch = PrivateAttr()
20
+
21
+ def __init__(self):
22
+ # Initializing the WebSearchTool
23
+ super().__init__()
24
+ self._search = TavilySearch(max_results=3, topic="general") # Setting up the TavilySearch with specific parameters
25
+
26
+ def _run(self, query: str) -> dict:
27
+ # Method to run the web search tool with the given query
28
+ search_results = [] # Initializing the list for search results
29
+ search_results.append(self._search.run(query)) # Performing the search and adding the results to the list
30
+
31
+ return search_results # Returning the search results
tools/wikipedia.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Importing necessary libraries and modules
2
+ from langchain_community.tools import WikipediaQueryRun
3
+ from langchain_community.utilities import WikipediaAPIWrapper
4
+ from pydantic import PrivateAttr
5
+ from langchain_core.tools.base import BaseTool
6
+ from langchain_community.document_loaders import WikipediaLoader
7
+ import requests
8
+ from bs4 import BeautifulSoup
9
+ import wikipedia
10
+
11
+ # Defining the WikipediaTool class which extends BaseTool
12
+ class WikipediaTool(BaseTool):
13
+ name: str = "wikipedia_tool"
14
+ description: str = "Search Wikipedia for a given query, retrieving the corresponding page's HTML content. The query should not contain any noise and ask for something specific."
15
+
16
+ def __init__(self):
17
+ # Initializing the WikipediaTool
18
+ super().__init__()
19
+
20
+ def _run(self, query: str):
21
+ # Method to run the Wikipedia tool with the given query
22
+ print(f"wikipedia_search_html called with query='{query}'") # Logging the query
23
+ # Step 1: Get Wikipedia HTML
24
+ page = wikipedia.page(query) # Fetching the Wikipedia page for the query
25
+ html = page.html() # Extracting the HTML content of the page
26
+
27
+ # Step 2: Parse HTML
28
+ soup = BeautifulSoup(html, "html.parser") # Parsing the HTML content
29
+ content_div = soup.find("div", class_="mw-parser-output") # Finding the content division
30
+ # content_div = soup.find("table", class_="wikitable")
31
+ if not content_div:
32
+ return ""
33
+
34
+ # Step 3: Find all tags to remove (style, script, sup, infobox, etc.)
35
+ to_decompose = [] # Collecting tags to be removed
36
+ for tag in content_div.find_all(): # Looping through all tags in the content division
37
+ tag_classes = tag.get("class", [])
38
+ if (
39
+ tag.name in ["style", "script", "sup"]
40
+ or any(cls in ["infobox", "navbox", "reference"] for cls in tag_classes)
41
+ ):
42
+ to_decompose.append(tag)
43
+
44
+ # Remove them after collecting
45
+ for tag in to_decompose: # Decompose and remove the collected tags
46
+ tag.decompose()
47
+
48
+ return str(content_div) # Returning the cleaned content division as string
tools/youtube_transcript.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from langchain_core.tools.base import BaseTool, ToolException
2
+ import requests
3
+ from youtube_transcript_api import YouTubeTranscriptApi
4
+ import re
5
+
6
+ class YoutubeTranscriptTool(BaseTool):
7
+ name: str = "youtube_transcript_tool"
8
+ description: str = "This tool can be used to retrieve the transcript of a youtube video given the FULL youtube link. You must pass the full youtube link!"
9
+
10
+ def _run(self, youtube_link: str) -> str:
11
+ """
12
+ Fetch transcript for a YouTube video URL.
13
+ Args:
14
+ youtube_link: The full URL of the YouTube video.
15
+ Returns:
16
+ The transcript as a single string.
17
+ """
18
+ # Get the video ID from the youtube URL
19
+ re_match = re.search(r"watch\?v=([^&]+)", youtube_link)
20
+ if not re_match:
21
+ raise ValueError(f"Invalid YouTube URL: {youtube_link}")
22
+ video_id = re_match.group(1)
23
+
24
+ # Initialize the transcriptAPI and retrieve the transcript for the given videoID
25
+ ytt_api = YouTubeTranscriptApi()
26
+ fetched_transcript = ytt_api.fetch(video_id)
27
+
28
+ transcript = []
29
+ for snippet in fetched_transcript:
30
+ transcript.append(snippet.text)
31
+
32
+ return "\n".join(transcript)