mdicio commited on
Commit
b69b087
·
1 Parent(s): 35c8e46

lets give it a go

Browse files
Files changed (11) hide show
  1. .gitignore +5 -1
  2. __init__.py +0 -0
  3. agent.py +286 -485
  4. app.py +15 -12
  5. cocolabelmap.py +186 -0
  6. example_gaiaqa.json +122 -0
  7. langtools.py +104 -0
  8. tools copy.py +352 -0
  9. tools.py +1078 -0
  10. tools_beta.py +550 -0
  11. utils.py +35 -0
.gitignore CHANGED
@@ -1,4 +1,8 @@
1
  .env
2
  ragdata/
3
  chroma_store
4
- .python-version
 
 
 
 
 
1
  .env
2
  ragdata/
3
  chroma_store
4
+ .python-version
5
+ downloads/
6
+ .python_version
7
+ *.jsonl
8
+ *__pycache__/
__init__.py ADDED
File without changes
agent.py CHANGED
@@ -1,495 +1,296 @@
1
- import cmath
2
- import json
3
- import os
4
- import re
5
- import tempfile
6
- import uuid
7
- from typing import Any, Dict, List, Optional
8
- from urllib.parse import urlparse
9
-
10
- import numpy as np
11
- import pandas as pd
12
- import pytesseract
13
- import requests
14
- from code_interpreter import CodeInterpreter
15
  from dotenv import load_dotenv
16
- from PIL import Image, ImageDraw, ImageEnhance, ImageFilter, ImageFont
17
-
18
- interpreter_instance = CodeInterpreter()
19
-
20
- from image_processing import *
21
-
22
- """Langraph"""
23
- from datasets import load_dataset
24
- from dotenv import load_dotenv
25
- from huggingface_hub import login
26
- from langchain.schema import Document
27
- from langchain.tools.retriever import create_retriever_tool
28
- from langchain.vectorstores import Chroma
29
- from langchain_community.document_loaders import ArxivLoader, WikipediaLoader
30
- from langchain_community.embeddings import HuggingFaceEmbeddings
31
- from langchain_community.tools.tavily_search import TavilySearchResults
32
- from langchain_core.messages import AIMessage, HumanMessage, SystemMessage
33
- from langchain_core.tools import tool
34
- from langchain_google_genai import ChatGoogleGenerativeAI
35
- from langchain_groq import ChatGroq
36
- from langchain_huggingface import HuggingFaceEmbeddings, HuggingFaceEndpoint
37
- from langgraph.graph import START, MessagesState, StateGraph
38
- from langgraph.prebuilt import ToolNode, tools_condition
39
- from supabase.client import Client, create_client
40
-
41
- login(token=os.environ["HUGGINGFACE_TOKEN"])
42
-
43
- load_dotenv()
44
-
45
-
46
- @tool
47
- def multiply(a: float, b: float) -> float:
48
- """
49
- Multiplies two numbers.
50
- Args:
51
- a (float): the first number
52
- b (float): the second number
53
- """
54
- return a * b
55
-
56
-
57
- @tool
58
- def add(a: float, b: float) -> float:
59
- """
60
- Adds two numbers.
61
- Args:
62
- a (float): the first number
63
- b (float): the second number
64
- """
65
- return a + b
66
-
67
-
68
- @tool
69
- def subtract(a: float, b: float) -> int:
70
- """
71
- Subtracts two numbers.
72
- Args:
73
- a (float): the first number
74
- b (float): the second number
75
- """
76
- return a - b
77
-
78
-
79
- @tool
80
- def divide(a: float, b: float) -> float:
81
- """
82
- Divides two numbers.
83
- Args:
84
- a (float): the first float number
85
- b (float): the second float number
86
- """
87
- if b == 0:
88
- raise ValueError("Cannot divided by zero.")
89
- return a / b
90
-
91
-
92
- @tool
93
- def modulus(a: int, b: int) -> int:
94
- """
95
- Get the modulus of two numbers.
96
- Args:
97
- a (int): the first number
98
- b (int): the second number
99
- """
100
- return a % b
101
-
102
-
103
- @tool
104
- def power(a: float, b: float) -> float:
105
- """
106
- Get the power of two numbers.
107
- Args:
108
- a (float): the first number
109
- b (float): the second number
110
- """
111
- return a**b
112
-
113
-
114
- @tool
115
- def square_root(a: float) -> float | complex:
116
- """
117
- Get the square root of a number.
118
- Args:
119
- a (float): the number to get the square root of
120
- """
121
- if a >= 0:
122
- return a**0.5
123
- return cmath.sqrt(a)
124
-
125
-
126
- ### =============== DOCUMENT PROCESSING TOOLS =============== ###
127
-
128
-
129
- @tool
130
- def save_and_read_file(content: str, filename: Optional[str] = None) -> str:
131
- """
132
- Save content to a file and return the path.
133
- Args:
134
- content (str): the content to save to the file
135
- filename (str, optional): the name of the file. If not provided, a random name file will be created.
136
- """
137
- temp_dir = tempfile.gettempdir()
138
- if filename is None:
139
- temp_file = tempfile.NamedTemporaryFile(delete=False, dir=temp_dir)
140
- filepath = temp_file.name
141
- else:
142
- filepath = os.path.join(temp_dir, filename)
143
-
144
- with open(filepath, "w") as f:
145
- f.write(content)
146
-
147
- return f"File saved to {filepath}. You can read this file to process its contents."
148
-
149
-
150
- @tool
151
- def download_file_from_url(url: str, filename: Optional[str] = None) -> str:
152
- """
153
- Download a file from a URL and save it to a temporary location.
154
- Args:
155
- url (str): the URL of the file to download.
156
- filename (str, optional): the name of the file. If not provided, a random name file will be created.
157
- """
158
- try:
159
- # Parse URL to get filename if not provided
160
- if not filename:
161
- path = urlparse(url).path
162
- filename = os.path.basename(path)
163
- if not filename:
164
- filename = f"downloaded_{uuid.uuid4().hex[:8]}"
165
-
166
- # Create temporary file
167
- temp_dir = tempfile.gettempdir()
168
- filepath = os.path.join(temp_dir, filename)
169
-
170
- # Download the file
171
- response = requests.get(url, stream=True)
172
- response.raise_for_status()
173
-
174
- # Save the file
175
- with open(filepath, "wb") as f:
176
- for chunk in response.iter_content(chunk_size=8192):
177
- f.write(chunk)
178
-
179
- return f"File downloaded to {filepath}. You can read this file to process its contents."
180
- except Exception as e:
181
- return f"Error downloading file: {str(e)}"
182
-
183
-
184
- @tool
185
- def extract_text_from_image(image_path: str) -> str:
186
- """
187
- Extract text from an image using OCR library pytesseract (if available).
188
- Args:
189
- image_path (str): the path to the image file.
190
- """
191
- try:
192
- # Open the image
193
- image = Image.open(image_path)
194
-
195
- # Extract text from the image
196
- text = pytesseract.image_to_string(image)
197
-
198
- return f"Extracted text from image:\n\n{text}"
199
- except Exception as e:
200
- return f"Error extracting text from image: {str(e)}"
201
-
202
-
203
- @tool
204
- def analyze_csv_file(file_path: str, query: str) -> str:
205
- """
206
- Analyze a CSV file using pandas and answer a question about it.
207
- Args:
208
- file_path (str): the path to the CSV file.
209
- query (str): Question about the data
210
- """
211
- try:
212
- # Read the CSV file
213
- df = pd.read_csv(file_path)
214
-
215
- # Run various analyses based on the query
216
- result = f"CSV file loaded with {len(df)} rows and {len(df.columns)} columns.\n"
217
- result += f"Columns: {', '.join(df.columns)}\n\n"
218
-
219
- # Add summary statistics
220
- result += "Summary statistics:\n"
221
- result += str(df.describe())
222
-
223
- return result
224
-
225
- except Exception as e:
226
- return f"Error analyzing CSV file: {str(e)}"
227
-
228
-
229
- @tool
230
- def analyze_excel_file(file_path: str, query: str) -> str:
231
- """
232
- Analyze an Excel file using pandas and answer a question about it.
233
- Args:
234
- file_path (str): the path to the Excel file.
235
- query (str): Question about the data
236
- """
237
- try:
238
- # Read the Excel file
239
- df = pd.read_excel(file_path)
240
-
241
- # Run various analyses based on the query
242
- result = (
243
- f"Excel file loaded with {len(df)} rows and {len(df.columns)} columns.\n"
244
- )
245
- result += f"Columns: {', '.join(df.columns)}\n\n"
246
-
247
- # Add summary statistics
248
- result += "Summary statistics:\n"
249
- result += str(df.describe())
250
-
251
- return result
252
-
253
- except Exception as e:
254
- return f"Error analyzing Excel file: {str(e)}"
255
-
256
-
257
- ### ============== IMAGE PROCESSING AND GENERATION TOOLS =============== ###
258
-
259
-
260
- @tool
261
- def wiki_search(query: str) -> str:
262
- """Search Wikipedia for a query and return maximum 2 results.
263
- Args:
264
- query: The search query."""
265
- search_docs = WikipediaLoader(query=query, load_max_docs=2).load()
266
- formatted_search_docs = "\n\n---\n\n".join(
267
- [
268
- f'<Document source="{doc.metadata["source"]}" page="{doc.metadata.get("page", "")}"/>\n{doc.page_content}\n</Document>'
269
- for doc in search_docs
270
- ]
271
- )
272
- return {"wiki_results": formatted_search_docs}
273
-
274
-
275
- @tool
276
- def web_search(query: str) -> str:
277
- """Search Tavily for a query and return maximum 3 results.
278
- Args:
279
- query: The search query."""
280
- search_docs = TavilySearchResults(max_results=3).invoke(query=query)
281
- formatted_search_docs = "\n\n---\n\n".join(
282
- [
283
- f'<Document source="{doc.metadata["source"]}" page="{doc.metadata.get("page", "")}"/>\n{doc.page_content}\n</Document>'
284
- for doc in search_docs
285
- ]
286
- )
287
- return {"web_results": formatted_search_docs}
288
-
289
-
290
- @tool
291
- def arxiv_search(query: str) -> str:
292
- """Search Arxiv for a query and return maximum 3 result.
293
- Args:
294
- query: The search query."""
295
- search_docs = ArxivLoader(query=query, load_max_docs=3).load()
296
- formatted_search_docs = "\n\n---\n\n".join(
297
- [
298
- f'<Document source="{doc.metadata["source"]}" page="{doc.metadata.get("page", "")}"/>\n{doc.page_content[:1000]}\n</Document>'
299
- for doc in search_docs
300
- ]
301
- )
302
- return {"arxiv_results": formatted_search_docs}
303
-
304
-
305
- ### =============== CODE INTERPRETER TOOLS =============== ###
306
-
307
-
308
- @tool
309
- def execute_code_multilang(code: str, language: str = "python") -> str:
310
- """Execute code in multiple languages (Python, Bash, SQL, C, Java) and return results.
311
- Args:
312
- code (str): The source code to execute.
313
- language (str): The language of the code. Supported: "python", "bash", "sql", "c", "java".
314
- Returns:
315
- A string summarizing the execution results (stdout, stderr, errors, plots, dataframes if any).
316
- """
317
- supported_languages = ["python", "bash", "sql", "c", "java"]
318
- language = language.lower()
319
-
320
- if language not in supported_languages:
321
- return f"❌ Unsupported language: {language}. Supported languages are: {', '.join(supported_languages)}"
322
-
323
- result = interpreter_instance.execute_code(code, language=language)
324
 
325
- response = []
 
326
 
327
- if result["status"] == "success":
328
- response.append(f"✅ Code executed successfully in **{language.upper()}**")
 
 
 
329
 
330
- if result.get("stdout"):
331
- response.append(
332
- "\n**Standard Output:**\n```\n" + result["stdout"].strip() + "\n```"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
333
  )
334
-
335
- if result.get("stderr"):
336
- response.append(
337
- "\n**Standard Error (if any):**\n```\n"
338
- + result["stderr"].strip()
339
- + "\n```"
 
 
 
 
340
  )
341
-
342
- if result.get("result") is not None:
343
- response.append(
344
- "\n**Execution Result:**\n```\n"
345
- + str(result["result"]).strip()
346
- + "\n```"
347
  )
348
-
349
- if result.get("dataframes"):
350
- for df_info in result["dataframes"]:
351
- response.append(
352
- f"\n**DataFrame `{df_info['name']}` (Shape: {df_info['shape']})**"
353
- )
354
- df_preview = pd.DataFrame(df_info["head"])
355
- response.append("First 5 rows:\n```\n" + str(df_preview) + "\n```")
356
-
357
- if result.get("plots"):
358
- response.append(
359
- f"\n**Generated {len(result['plots'])} plot(s)** (Image data returned separately)"
360
  )
361
-
362
- else:
363
- response.append(f"❌ Code execution failed in **{language.upper()}**")
364
- if result.get("stderr"):
365
- response.append(
366
- "\n**Error Log:**\n```\n" + result["stderr"].strip() + "\n```"
 
 
 
367
  )
368
-
369
- return "\n".join(response)
370
-
371
-
372
- system_prompt = """You are a helpful assistant tasked with answering questions using a set of tools.
373
- Now, I will ask you a question. Report your thoughts, and finish your answer with the following template:
374
- FINAL ANSWER: [YOUR FINAL ANSWER].
375
- YOUR FINAL ANSWER should be a number OR as few words as possible OR a comma separated list of numbers and/or strings. If you are asked for a number, don't use comma to write your number neither use units such as $ or percent sign unless specified otherwise. If you are asked for a string, don't use articles, neither abbreviations (e.g. for cities), and write the digits in plain text unless specified otherwise. If you are asked for a comma separated list, apply the above rules depending of whether the element to be put in the list is a number or a string.
376
- Your answer should only start with "FINAL ANSWER: ", then follows with the answer. """
377
-
378
- # System message
379
- sys_msg = SystemMessage(content=system_prompt)
380
-
381
- # build a retriever
382
- embeddings = HuggingFaceEmbeddings(
383
- model_name="sentence-transformers/all-mpnet-base-v2"
384
- ) # dim=768
385
-
386
- # Load the GAIA validation dataset
387
- dataset = load_dataset(
388
- "gaia-benchmark/GAIA",
389
- name="2023_level1",
390
- split="validation",
391
- trust_remote_code=True,
392
- cache_dir="ragdata",
393
- )
394
-
395
- # Extract questions and their answers
396
- documents = []
397
- for entry in dataset:
398
- question = entry["Question"]
399
- answer = entry["Final answer"]
400
-
401
- # Create a document with both the question and the answer as metadata
402
- metadata = {
403
- "task_id": entry["task_id"],
404
- "steps": entry["Annotator Metadata"]["Steps"],
405
- "tools": entry["Annotator Metadata"]["Tools"],
406
- "answer": answer,
407
- }
408
-
409
- # Add the question to the list of documents
410
- documents.append(Document(page_content=question, metadata=metadata))
411
-
412
- # Insert the documents into Chroma
413
- vector_store = Chroma.from_documents(
414
- documents=documents,
415
- embedding=embeddings,
416
- collection_name="gaia_validation",
417
- persist_directory="./chroma_store",
418
- )
419
-
420
- create_retriever_tool = create_retriever_tool(
421
- retriever=vector_store.as_retriever(),
422
- name="Question Search",
423
- description="A tool to retrieve similar questions from a vector store.",
424
- )
425
-
426
-
427
- tools = [
428
- web_search,
429
- wiki_search,
430
- arxiv_search,
431
- multiply,
432
- add,
433
- subtract,
434
- divide,
435
- modulus,
436
- power,
437
- square_root,
438
- save_and_read_file,
439
- download_file_from_url,
440
- extract_text_from_image,
441
- analyze_csv_file,
442
- analyze_excel_file,
443
- execute_code_multilang,
444
- ]
445
-
446
-
447
- # Build graph function
448
- def build_graph(provider: str = "groq"):
449
- """Build the graph"""
450
- # Load environment variables from .env file
451
- if provider == "google":
452
- # Google Gemini
453
- llm = ChatGoogleGenerativeAI(model="gemini-2.0-flash", temperature=0)
454
- elif provider == "groq":
455
- # Groq https://console.groq.com/docs/models
456
- llm = ChatGroq(
457
- model="qwen-qwq-32b", temperature=0
458
- ) # optional : qwen-qwq-32b gemma2-9b-it
459
- elif provider == "huggingface":
460
- # TODO: Add huggingface endpoint
461
- llm = HuggingFaceEndpoint(
462
- repo_id="Meta-DeepLearning/llama-2-7b-chat-hf",
463
- temperature=0,
464
- )
465
- else:
466
- raise ValueError("Invalid provider. Choose 'google', 'groq' or 'huggingface'.")
467
- # Bind tools to LLM
468
- llm_with_tools = llm.bind_tools(tools)
469
-
470
- # Node
471
- def assistant(state: MessagesState):
472
- """Assistant node"""
473
- return {"messages": [llm_with_tools.invoke(state["messages"])]}
474
-
475
- def retriever(state: MessagesState):
476
- """Retriever node"""
477
- similar_question = vector_store.similarity_search(state["messages"][0].content)
478
- example_msg = HumanMessage(
479
- content=f"Here I provide a similar question and answer for reference: \n\n{similar_question[0].page_content}",
480
  )
481
- return {"messages": [sys_msg] + state["messages"] + [example_msg]}
482
-
483
- builder = StateGraph(MessagesState)
484
- builder.add_node('retriever', retriever)
485
- builder.add_node('assistant', assistant)
486
- builder.add_node('tools', ToolNode(tools))
487
-
488
- builder.add_edge(START, 'retriever')
489
- builder.add_edge('retriever', 'assistant')
490
- builder.add_conditional_edges('assistant', tools_condition)
491
- builder.add_edge('tools', 'assistant')
492
-
493
- graph = builder.compile()
494
-
495
- return graph
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  from dotenv import load_dotenv
2
+ import os
3
+ from typing import Union, List, Dict, Any, Optional, Tuple, Bool
4
+
5
+ # Import tools from LangChain
6
+ from langchain.agents import get_all_tool_names
7
+ from langchain.agents import load_tools
8
+
9
+ # Import custom tools
10
+ from Final_Assignment_Template.tools import (
11
+ ReadFileContentTool,
12
+ WikipediaSearchTool,
13
+ VisitWebpageTool,
14
+ TranscribeAudioTool,
15
+ TranscibeVideoFileTool,
16
+ BraveWebSearchTool,
17
+ DescribeImageTool,
18
+ ArxivSearchTool,
19
+ DownloadFileFromLinkTool,
20
+ DuckDuckGoSearchTool,
21
+ AddDocumentToVectorStoreTool,
22
+ QueryVectorStoreTool,
23
+ image_question_answering
24
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
 
26
+ # Import utility functions
27
+ from utils import replace_tool_mentions, extract_final_answer
28
 
29
+ # Import SmolaAgents tools
30
+ from smolagents.default_tools import (
31
+ PythonInterpreterTool,
32
+ FinalAnswerTool
33
+ )
34
 
35
+ # Import models from SmolaAgents
36
+ from smolagents import OpenAIServerModel, LiteLLMModel, CodeAgent, HfApiModel
37
+
38
+
39
+ class BoomBot:
40
+ def __init__(self, provider="deepinfra"):
41
+ """
42
+ Initialize the BoomBot with the specified provider.
43
+
44
+ Args:
45
+ provider (str): The model provider to use (e.g., "groq", "qwen", "gemma", "anthropic", "deepinfra", "meta")
46
+ """
47
+ load_dotenv()
48
+ self.provider = provider
49
+ self.model = self._initialize_model()
50
+ self.agent = self._create_agent()
51
+
52
+ def _initialize_model(self):
53
+ """
54
+ Initialize the appropriate model based on the provider.
55
+
56
+ Returns:
57
+ The initialized model object
58
+ """
59
+ if self.provider == "qwen":
60
+ qwen_model = "ollama_chat/qwen3:8b"
61
+ return LiteLLMModel(
62
+ model_id=qwen_model,
63
+ device='cuda',
64
+ num_ctx=32768,
65
+ temperature=0.6,
66
+ top_p=0.95
67
  )
68
+ elif self.provider == "gemma":
69
+ gemma_model = "ollama_chat/gemma3:12b-it-qat"
70
+ return LiteLLMModel(
71
+ model_id=gemma_model,
72
+ num_ctx=65536,
73
+ temperature=1.0,
74
+ device='cuda',
75
+ top_k=64,
76
+ top_p=0.95,
77
+ min_p=0.0
78
  )
79
+ elif self.provider == "anthropic":
80
+ model_id = "anthropic/claude-3-5-sonnet-latest"
81
+ return LiteLLMModel(
82
+ model_id=model_id,
83
+ temperature=0.6,
84
+ max_tokens=8192
85
  )
86
+ elif self.provider == "deepinfra":
87
+ deepinfra_model = "Qwen/Qwen3-235B-A22B"
88
+ return OpenAIServerModel(
89
+ model_id=deepinfra_model,
90
+ api_base="https://api.deepinfra.com/v1/openai",
91
+ api_key=os.environ["DEEPINFRA_API_KEY"],
92
+ flatten_messages_as_text=True,
93
+ max_tokens=8192,
94
+ temperature=0.1
 
 
 
95
  )
96
+ elif self.provider == "meta":
97
+ meta_model = "meta-llama/Llama-3.3-70B-Instruct-Turbo"
98
+ return OpenAIServerModel(
99
+ model_id=meta_model,
100
+ api_base="https://api.deepinfra.com/v1/openai",
101
+ api_key=os.environ["DEEPINFRA_API_KEY"],
102
+ flatten_messages_as_text=True,
103
+ max_tokens=8192,
104
+ temperature=0.7
105
  )
106
+ elif self.provider == "groq":
107
+ # Default to use groq's claude-3-opus or llama-3
108
+ model_id = "claude-3-opus-20240229"
109
+ return LiteLLMModel(
110
+ model_id=model_id,
111
+ temperature=0.7,
112
+ max_tokens=8192
113
+ )
114
+ else:
115
+ raise ValueError(f"Unsupported provider: {self.provider}")
116
+
117
+ def _create_agent(self):
118
+ """
119
+ Create and configure the agent with all necessary tools.
120
+
121
+ Returns:
122
+ The configured CodeAgent
123
+ """
124
+ # Initialize tools
125
+ download_file = DownloadFileFromLinkTool()
126
+ read_file_content = ReadFileContentTool()
127
+ visit_webpage = VisitWebpageTool()
128
+ transcribe_video = TranscibeVideoFileTool()
129
+ transcribe_audio = TranscribeAudioTool()
130
+ get_wikipedia_info = WikipediaSearchTool()
131
+ web_searcher = DuckDuckGoSearchTool()
132
+ arxiv_search = ArxivSearchTool()
133
+ add_doc_vectorstore = AddDocumentToVectorStoreTool()
134
+ retrieve_doc_vectorstore = QueryVectorStoreTool()
135
+
136
+ # SmolaAgents default tools
137
+ python_interpreter = PythonInterpreterTool()
138
+ final_answer = FinalAnswerTool()
139
+
140
+ # Combine all tools
141
+ agent_tools = [
142
+ web_searcher,
143
+ download_file,
144
+ read_file_content,
145
+ visit_webpage,
146
+ transcribe_video,
147
+ transcribe_audio,
148
+ get_wikipedia_info,
149
+ arxiv_search,
150
+ add_doc_vectorstore,
151
+ retrieve_doc_vectorstore,
152
+ python_interpreter,
153
+ final_answer
154
+ ]
155
+
156
+ # Additional imports for the Python interpreter
157
+ additional_imports = [
158
+ "json",
159
+ "os",
160
+ "glob",
161
+ "pathlib",
162
+ "pandas",
163
+ "numpy",
164
+ "matplotlib",
165
+ "seaborn",
166
+ "sklearn",
167
+ "tqdm",
168
+ "argparse",
169
+ "pickle",
170
+ "io",
171
+ "re",
172
+ "datetime",
173
+ "collections",
174
+ "math",
175
+ "random",
176
+ "csv",
177
+ "zipfile",
178
+ "itertools",
179
+ "functools",
180
+ ]
181
+
182
+ # Create the agent
183
+ agent = CodeAgent(
184
+ tools=agent_tools,
185
+ max_steps=12,
186
+ model=self.model,
187
+ add_base_tools=False,
188
+ stream_outputs=True,
189
+ additional_authorized_imports=additional_imports
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
190
  )
191
+
192
+ # Modify the system prompt
193
+ modified_prompt = replace_tool_mentions(agent.system_prompt)
194
+ agent.system_prompt = modified_prompt + self._get_system_prompt()
195
+
196
+ return agent
197
+
198
+ def _get_system_prompt(self):
199
+ """
200
+ Return the system prompt for the agent.
201
+
202
+ Returns:
203
+ str: The system prompt
204
+ """
205
+ return """
206
+ YOUR BEHAVIOR GUIDELINES:
207
+ • Do NOT make unfounded assumptions—always ground answers in reliable sources or search results.
208
+ • For math or puzzles: break the problem into code/math, then solve programmatically.
209
+
210
+ RESEARCH WORKFLOW (in rough priority order):
211
+ 1. SEARCH
212
+ - Try web_search, wikipedia_search, or arxiv_search first.
213
+ - Refine your query rather than repeating the exact same terms.
214
+ - If one search tool yields insufficient info, switch to another before downloading.
215
+ 2. VISIT
216
+ - Use visit_webpage to extract and read page content when a promising link appears after one of the SEARCH tools.
217
+ - For each visited link, also download the file and add to the vector store, you might need to query this later, especially if you have a lot of search results.
218
+ 3. EVALUATE
219
+ - ✅ If the page or search snippet fully answers the question, respond immediately.
220
+ - ❌ If not, move on to deeper investigation.
221
+ 4. DOWNLOAD
222
+ - Use download_file_from_link tool on relevant links found (yes you can download webpages as html).
223
+ - For arXiv papers, target the /pdf/ or DOI link (e.g https://arxiv.org/pdf/2011.10672).
224
+ -
225
+ 5. INDEX & QUERY
226
+ - Add downloaded documents to the vector store with add_document_to_vector_store.
227
+ - Use query_downloaded_documents for detailed answers.
228
+ 6. READ
229
+ - You have access to a read_file_content tool to read most types of files. You can also directly interact with downloaded files in your python code (do this for csv files and excel files)
230
+
231
+
232
+ FALLBACK & ADAPTATION:
233
+ • If a tool fails, reformulate your query or try a different search method before dropping to download.
234
+ • If a tool fails multiple times, try a different tool.
235
+ • For arXiv: you might discover a paper link via web_search tool and then directly use download_file_from_link tool
236
+
237
+ COMMON TOOL CHAINS (conceptual outlines):
238
+ These are just guidelines, each task might require a unique workflow.
239
+ A tool can provide useful information for the task, it will not always contain the answer. You need to work to get to a final_answer that makes sense.
240
+
241
+ • FACTUAL Qs:
242
+ web_search → final_answer
243
+ • CURRENT EVENTS:
244
+ To have some summary information use web_search, that might output a promising website to visit and read content from using (visit_webpage or download_file_from_link and read_file_content)
245
+ web_search → visit_webpage → final_answer
246
+ • DOCUMENT-BASED Qs:
247
+ web_search → download_file_from_link → add_document_to_vector_store → query_downloaded_documents → final_answer
248
+ • ARXIV PAPERS:
249
+ The arxiv search tool provides a list of results with summary content, to inspect the whole paper you need to download it with download_file_from_link tool.
250
+ arxiv_search → download_file_from_link → read_file_content
251
+ If that fails
252
+ arxiv_search → download_file_from_link → add_document_to_vector_store → query_downloaded_documents
253
+ • MEDIA ANALYSIS:
254
+ download_file_from_link → transcribe_video/transcribe_audio/describe_image → final_answer
255
+
256
+ FINAL ANSWER FORMAT:
257
+ - Begin with "FINAL ANSWER: "
258
+ - Number → digits only (e.g., 42)
259
+ - String → exact text (e.g., Pope Francis)
260
+ - List → comma-separated, one space (e.g., 2, 3, 4)
261
+ - Conclude with: FINAL ANSWER: <your_answer>
262
+ """
263
+
264
+ def run(self, question: str, task_id: str, to_download: Bool) -> str:
265
+ """
266
+ Run the agent with the given question, task_id, and download flag.
267
+
268
+ Args:
269
+ question (str): The question or task for the agent to process
270
+ task_id (str): A unique identifier for the task
271
+ to_download (Bool): Flag indicating whether to download resources
272
+
273
+ Returns:
274
+ str: The agent's response
275
+ """
276
+ print(f"BoomBot running with question (first 50 chars): {question[:50]}...")
277
+
278
+ # Configure any task-specific settings based on the parameters
279
+ if to_download:
280
+ # You could set up specific agent configurations here for download tasks
281
+ pass
282
+
283
+ # Run the agent with the given question
284
+ result = self.agent.generate_response(question)
285
+
286
+ # Extract the final answer from the result
287
+ final_answer = extract_final_answer(result)
288
+
289
+ return final_answer
290
+
291
+
292
+ # Example of how to use this code (commented out)
293
+ # if __name__ == "__main__":
294
+ # agent = BasicAgent()
295
+ # response = agent("What is the current population of Tokyo?", "population_query", True)
296
+ # print(f"Response: {response}")
app.py CHANGED
@@ -5,29 +5,25 @@ import gradio as gr
5
  import pandas as pd
6
  import requests
7
  from langchain_core.messages import HumanMessage
 
8
 
9
- from agent import build_graph
10
 
11
  # (Keep Constants as is)
12
  # --- Constants ---
13
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
14
 
15
 
 
16
  # --- Basic Agent Definition ---
17
- # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
18
  class BasicAgent:
19
  def __init__(self):
20
  print("BasicAgent initialized.")
21
- self.graph = build_graph(provider = "groq")
22
- def __call__(self, question: str) -> str:
 
23
  print(f"Agent received question (first 50 chars): {question[:50]}...")
24
- # fixed_answer = "This is a default answer."
25
- # print(f"Agent returning fixed answer: {fixed_answer}")
26
- # return fixed_answer
27
- messages = [HumanMessage(content=question)]
28
- messages = self.graph.invoke({'messages': messages})
29
- ans = messages['messages'][-1].content
30
- return ans[14:]
31
 
32
  def run_and_submit_all(profile: gr.OAuthProfile | None):
33
  """
@@ -86,11 +82,18 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
86
  for item in questions_data:
87
  task_id = item.get("task_id")
88
  question_text = item.get("question")
 
 
 
 
 
 
 
89
  if not task_id or question_text is None:
90
  print(f"Skipping item with missing task_id or question: {item}")
91
  continue
92
  try:
93
- submitted_answer = agent(question_text)
94
  answers_payload.append(
95
  {"task_id": task_id, "submitted_answer": submitted_answer}
96
  )
 
5
  import pandas as pd
6
  import requests
7
  from langchain_core.messages import HumanMessage
8
+ from traitlets import Bool # type: ignore
9
 
10
+ from agent import BoomBot
11
 
12
  # (Keep Constants as is)
13
  # --- Constants ---
14
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
15
 
16
 
17
+ # --- Basic Agent Definition --
18
  # --- Basic Agent Definition ---
 
19
  class BasicAgent:
20
  def __init__(self):
21
  print("BasicAgent initialized.")
22
+ self.agent = BoomBot(provider="groq")
23
+
24
+ def __call__(self, question: str, task_id: str, to_download: Bool) -> str:
25
  print(f"Agent received question (first 50 chars): {question[:50]}...")
26
+ return self.agent.run(question, task_id, to_download)
 
 
 
 
 
 
27
 
28
  def run_and_submit_all(profile: gr.OAuthProfile | None):
29
  """
 
82
  for item in questions_data:
83
  task_id = item.get("task_id")
84
  question_text = item.get("question")
85
+ file_name = item.get("file_name", "")
86
+
87
+ if file_name.strip() != "":
88
+ to_download = True
89
+ else:
90
+ to_download = False
91
+
92
  if not task_id or question_text is None:
93
  print(f"Skipping item with missing task_id or question: {item}")
94
  continue
95
  try:
96
+ submitted_answer = agent(question_text, task_id, to_download = to_download)
97
  answers_payload.append(
98
  {"task_id": task_id, "submitted_answer": submitted_answer}
99
  )
cocolabelmap.py ADDED
@@ -0,0 +1,186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ LABEL_MAP = {
2
+ 0: "unlabeled",
3
+ 1: "person",
4
+ 2: "bicycle",
5
+ 3: "car",
6
+ 4: "motorcycle",
7
+ 5: "airplane",
8
+ 6: "bus",
9
+ 7: "train",
10
+ 8: "truck",
11
+ 9: "boat",
12
+ 10: "traffic",
13
+ 11: "fire",
14
+ 12: "street",
15
+ 13: "stop",
16
+ 14: "parking",
17
+ 15: "bench",
18
+ 16: "bird",
19
+ 17: "cat",
20
+ 18: "dog",
21
+ 19: "horse",
22
+ 20: "sheep",
23
+ 21: "cow",
24
+ 22: "elephant",
25
+ 23: "bear",
26
+ 24: "zebra",
27
+ 25: "giraffe",
28
+ 26: "hat",
29
+ 27: "backpack",
30
+ 28: "umbrella",
31
+ 29: "shoe",
32
+ 30: "eye",
33
+ 31: "handbag",
34
+ 32: "tie",
35
+ 33: "suitcase",
36
+ 34: "frisbee",
37
+ 35: "skis",
38
+ 36: "snowboard",
39
+ 37: "sports",
40
+ 38: "kite",
41
+ 39: "baseball",
42
+ 40: "baseball",
43
+ 41: "skateboard",
44
+ 42: "surfboard",
45
+ 43: "tennis",
46
+ 44: "bottle",
47
+ 45: "plate",
48
+ 46: "wine",
49
+ 47: "cup",
50
+ 48: "fork",
51
+ 49: "knife",
52
+ 50: "spoon",
53
+ 51: "bowl",
54
+ 52: "banana",
55
+ 53: "apple",
56
+ 54: "sandwich",
57
+ 55: "orange",
58
+ 56: "broccoli",
59
+ 57: "carrot",
60
+ 58: "hot",
61
+ 59: "pizza",
62
+ 60: "donut",
63
+ 61: "cake",
64
+ 62: "chair",
65
+ 63: "couch",
66
+ 64: "potted",
67
+ 65: "bed",
68
+ 66: "mirror",
69
+ 67: "dining",
70
+ 68: "window",
71
+ 69: "desk",
72
+ 70: "toilet",
73
+ 71: "door",
74
+ 72: "tv",
75
+ 73: "laptop",
76
+ 74: "mouse",
77
+ 75: "remote",
78
+ 76: "keyboard",
79
+ 77: "cell",
80
+ 78: "microwave",
81
+ 79: "oven",
82
+ 80: "toaster",
83
+ 81: "sink",
84
+ 82: "refrigerator",
85
+ 83: "blender",
86
+ 84: "book",
87
+ 85: "clock",
88
+ 86: "vase",
89
+ 87: "scissors",
90
+ 88: "teddy",
91
+ 89: "hair",
92
+ 90: "toothbrush",
93
+ 91: "hair",
94
+ 92: "banner",
95
+ 93: "blanket",
96
+ 94: "branch",
97
+ 95: "bridge",
98
+ 96: "building",
99
+ 97: "bush",
100
+ 98: "cabinet",
101
+ 99: "cage",
102
+ 100: "cardboard",
103
+ 101: "carpet",
104
+ 102: "ceiling",
105
+ 103: "ceiling",
106
+ 104: "cloth",
107
+ 105: "clothes",
108
+ 106: "clouds",
109
+ 107: "counter",
110
+ 108: "cupboard",
111
+ 109: "curtain",
112
+ 110: "desk",
113
+ 111: "dirt",
114
+ 112: "door",
115
+ 113: "fence",
116
+ 114: "floor",
117
+ 115: "floor",
118
+ 116: "floor",
119
+ 117: "floor",
120
+ 118: "floor",
121
+ 119: "flower",
122
+ 120: "fog",
123
+ 121: "food",
124
+ 122: "fruit",
125
+ 123: "furniture",
126
+ 124: "grass",
127
+ 125: "gravel",
128
+ 126: "ground",
129
+ 127: "hill",
130
+ 128: "house",
131
+ 129: "leaves",
132
+ 130: "light",
133
+ 131: "mat",
134
+ 132: "metal",
135
+ 133: "mirror",
136
+ 134: "moss",
137
+ 135: "mountain",
138
+ 136: "mud",
139
+ 137: "napkin",
140
+ 138: "net",
141
+ 139: "paper",
142
+ 140: "pavement",
143
+ 141: "pillow",
144
+ 142: "plant",
145
+ 143: "plastic",
146
+ 144: "platform",
147
+ 145: "playingfield",
148
+ 146: "railing",
149
+ 147: "railroad",
150
+ 148: "river",
151
+ 149: "road",
152
+ 150: "rock",
153
+ 151: "roof",
154
+ 152: "rug",
155
+ 153: "salad",
156
+ 154: "sand",
157
+ 155: "sea",
158
+ 156: "shelf",
159
+ 157: "sky",
160
+ 158: "skyscraper",
161
+ 159: "snow",
162
+ 160: "solid",
163
+ 161: "stairs",
164
+ 162: "stone",
165
+ 163: "straw",
166
+ 164: "structural",
167
+ 165: "table",
168
+ 166: "tent",
169
+ 167: "textile",
170
+ 168: "towel",
171
+ 169: "tree",
172
+ 170: "vegetable",
173
+ 171: "wall",
174
+ 172: "wall",
175
+ 173: "wall",
176
+ 174: "wall",
177
+ 175: "wall",
178
+ 176: "wall",
179
+ 177: "wall",
180
+ 178: "water",
181
+ 179: "waterdrops",
182
+ 180: "window",
183
+ 181: "window",
184
+ 182: "wood"
185
+ }
186
+
example_gaiaqa.json ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ {
3
+ "task_id": "8e867cd7-cff9-4e6c-867a-ff5ddc2550be",
4
+ "Question": "How many studio albums were published by Mercedes Sosa between 2000 and 2009 (included)? You can use the latest 2022 version of english wikipedia.",
5
+ "Level": "1",
6
+ "file_name": ""
7
+ },
8
+ {
9
+ "task_id": "a1e91b78-d3d8-4675-bb8d-62741b4b68a6",
10
+ "Question": "In the video https://www.youtube.com/watch?v=L1vXCYZAYYM, what is the highest number of bird species to be on camera simultaneously?",
11
+ "Level": "1",
12
+ "file_name": ""
13
+ },
14
+ {
15
+ "task_id": "2d83110e-a098-4ebb-9987-066c06fa42d0",
16
+ "Question": ".rewsna eht sa \"tfel\" drow eht fo etisoppo eht etirw ,ecnetnes siht dnatsrednu uoy fI",
17
+ "Level": "1",
18
+ "file_name": ""
19
+ },
20
+ {
21
+ "task_id": "cca530fc-4052-43b2-b130-b30968d8aa44",
22
+ "Question": "Review the chess position provided in the image. It is black's turn. Provide the correct next move for black which guarantees a win. Please provide your response in algebraic notation.",
23
+ "Level": "1",
24
+ "file_name": "cca530fc-4052-43b2-b130-b30968d8aa44.png"
25
+ },
26
+ {
27
+ "task_id": "4fc2f1ae-8625-45b5-ab34-ad4433bc21f8",
28
+ "Question": "Who nominated the only Featured Article on English Wikipedia about a dinosaur that was promoted in November 2016?",
29
+ "Level": "1",
30
+ "file_name": ""
31
+ },
32
+ {
33
+ "task_id": "6f37996b-2ac7-44b0-8e68-6d28256631b4",
34
+ "Question": "Given this table defining * on the set S = {a, b, c, d, e}\n\n|*|a|b|c|d|e|\n|---|---|---|---|---|---|\n|a|a|b|c|b|d|\n|b|b|c|a|e|c|\n|c|c|a|b|b|a|\n|d|b|e|b|e|d|\n|e|d|b|a|d|c|\n\nprovide the subset of S involved in any possible counter-examples that prove * is not commutative. Provide your answer as a comma separated list of the elements in the set in alphabetical order.",
35
+ "Level": "1",
36
+ "file_name": ""
37
+ },
38
+ {
39
+ "task_id": "9d191bce-651d-4746-be2d-7ef8ecadb9c2",
40
+ "Question": "Examine the video at https://www.youtube.com/watch?v=1htKBjuUWec.\n\nWhat does Teal'c say in response to the Question \"Isn't that hot?\"",
41
+ "Level": "1",
42
+ "file_name": ""
43
+ },
44
+ {
45
+ "task_id": "cabe07ed-9eca-40ea-8ead-410ef5e83f91",
46
+ "Question": "What is the surname of the equine veterinarian mentioned in 1.E Exercises from the chemistry materials licensed by Marisa Alviar-Agnew & Henry Agnew under the CK-12 license in LibreText's Introductory Chemistry materials as compiled 08/21/2023?",
47
+ "Level": "1",
48
+ "file_name": ""
49
+ },
50
+ {
51
+ "task_id": "3cef3a44-215e-4aed-8e3b-b1e3f08063b7",
52
+ "Question": "I'm making a grocery list for my mom, but she's a professor of botany and she's a real stickler when it comes to categorizing things. I need to add different foods to different categories on the grocery list, but if I make a mistake, she won't buy anything inserted in the wrong category. Here's the list I have so far:\n\nmilk, eggs, flour, whole bean coffee, Oreos, sweet potatoes, fresh basil, plums, green beans, rice, corn, bell pepper, whole allspice, acorns, broccoli, celery, zucchini, lettuce, peanuts\n\nI need to make headings for the fruits and vegetables. Could you please create a list of just the vegetables from my list? If you could do that, then I can figure out how to categorize the rest of the list into the appropriate categories. But remember that my mom is a real stickler, so make sure that no botanical fruits end up on the vegetable list, or she won't get them when she's at the store. Please alphabetize the list of vegetables, and place each item in a comma separated list.",
53
+ "Level": "1",
54
+ "file_name": ""
55
+ },
56
+ {
57
+ "task_id": "99c9cc74-fdc8-46c6-8f8d-3ce2d3bfeea3",
58
+ "Question": "Hi, I'm making a pie but I could use some help with my shopping list. I have everything I need for the crust, but I'm not sure about the filling. I got the recipe from my friend Aditi, but she left it as a voice memo and the speaker on my phone is buzzing so I can't quite make out what she's saying. Could you please listen to the recipe and list all of the ingredients that my friend described? I only want the ingredients for the filling, as I have everything I need to make my favorite pie crust. I've attached the recipe as Strawberry pie.mp3.\n\nIn your response, please only list the ingredients, not any measurements. So if the recipe calls for \"a pinch of salt\" or \"two cups of ripe strawberries\" the ingredients on the list would be \"salt\" and \"ripe strawberries\".\n\nPlease format your response as a comma separated list of ingredients. Also, please alphabetize the ingredients.",
59
+ "Level": "1",
60
+ "file_name": "99c9cc74-fdc8-46c6-8f8d-3ce2d3bfeea3.mp3"
61
+ },
62
+ {
63
+ "task_id": "305ac316-eef6-4446-960a-92d80d542f82",
64
+ "Question": "Who did the actor who played Ray in the Polish-language version of Everybody Loves Raymond play in Magda M.? Give only the first name.",
65
+ "Level": "1",
66
+ "file_name": ""
67
+ },
68
+ {
69
+ "task_id": "f918266a-b3e0-4914-865d-4faa564f1aef",
70
+ "Question": "What is the final numeric output from the attached Python code?",
71
+ "Level": "1",
72
+ "file_name": "f918266a-b3e0-4914-865d-4faa564f1aef.py"
73
+ },
74
+ {
75
+ "task_id": "3f57289b-8c60-48be-bd80-01f8099ca449",
76
+ "Question": "How many at bats did the Yankee with the most walks in the 1977 regular season have that same season?",
77
+ "Level": "1",
78
+ "file_name": ""
79
+ },
80
+ {
81
+ "task_id": "1f975693-876d-457b-a649-393859e79bf3",
82
+ "Question": "Hi, I was out sick from my classes on Friday, so I'm trying to figure out what I need to study for my Calculus mid-term next week. My friend from class sent me an audio recording of Professor Willowbrook giving out the recommended reading for the test, but my headphones are broken :(\n\nCould you please listen to the recording for me and tell me the page numbers I'm supposed to go over? I've attached a file called Homework.mp3 that has the recording. Please provide just the page numbers as a comma-delimited list. And please provide the list in ascending order.",
83
+ "Level": "1",
84
+ "file_name": "1f975693-876d-457b-a649-393859e79bf3.mp3"
85
+ },
86
+ {
87
+ "task_id": "840bfca7-4f7b-481a-8794-c560c340185d",
88
+ "Question": "On June 6, 2023, an article by Carolyn Collins Petersen was published in Universe Today. This article mentions a team that produced a paper about their observations, linked at the bottom of the article. Find this paper. Under what NASA award number was the work performed by R. G. Arendt supported by?",
89
+ "Level": "1",
90
+ "file_name": ""
91
+ },
92
+ {
93
+ "task_id": "bda648d7-d618-4883-88f4-3466eabd860e",
94
+ "Question": "Where were the Vietnamese specimens described by Kuznetzov in Nedoshivina's 2010 paper eventually deposited? Just give me the city name without abbreviations.",
95
+ "Level": "1",
96
+ "file_name": ""
97
+ },
98
+ {
99
+ "task_id": "cf106601-ab4f-4af9-b045-5295fe67b37d",
100
+ "Question": "What country had the least number of athletes at the 1928 Summer Olympics? If there's a tie for a number of athletes, return the first in alphabetical order. Give the IOC country code as your answer.",
101
+ "Level": "1",
102
+ "file_name": ""
103
+ },
104
+ {
105
+ "task_id": "a0c07678-e491-4bbc-8f0b-07405144218f",
106
+ "Question": "Who are the pitchers with the number before and after Taishō Tamai's number as of July 2023? Give them to me in the form Pitcher Before, Pitcher After, use their last names only, in Roman characters.",
107
+ "Level": "1",
108
+ "file_name": ""
109
+ },
110
+ {
111
+ "task_id": "7bd855d8-463d-4ed5-93ca-5fe35145f733",
112
+ "Question": "The attached Excel file contains the sales of menu items for a local fast-food chain. What were the total sales that the chain made from food (not including drinks)? Express your answer in USD with two decimal places.",
113
+ "Level": "1",
114
+ "file_name": "7bd855d8-463d-4ed5-93ca-5fe35145f733.xlsx"
115
+ },
116
+ {
117
+ "task_id": "5a0c1adf-205e-4841-a666-7c3ef95def9d",
118
+ "Question": "What is the first name of the only Malko Competition recipient from the 20th Century (after 1977) whose nationality on record is a country that no longer exists?",
119
+ "Level": "1",
120
+ "file_name": ""
121
+ }
122
+ ]
langtools.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from dotenv import load_dotenv
3
+ from langchain_community.tools.tavily_search import TavilySearchResults
4
+ from langchain_community.document_loaders import WikipediaLoader
5
+ from langchain_community.document_loaders import ArxivLoader
6
+ from langchain_core.tools import tool
7
+
8
+
9
+ load_dotenv()
10
+
11
+ @tool
12
+ def multiply(a: int, b: int) -> int:
13
+ """Multiply two numbers.
14
+ Args:
15
+ a: first int
16
+ b: second int
17
+ """
18
+ return a * b
19
+
20
+ @tool
21
+ def add(a: int, b: int) -> int:
22
+ """Add two numbers.
23
+
24
+ Args:
25
+ a: first int
26
+ b: second int
27
+ """
28
+ return a + b
29
+
30
+ @tool
31
+ def subtract(a: int, b: int) -> int:
32
+ """Subtract two numbers.
33
+
34
+ Args:
35
+ a: first int
36
+ b: second int
37
+ """
38
+ return a - b
39
+
40
+ @tool
41
+ def divide(a: int, b: int) -> int:
42
+ """Divide two numbers.
43
+
44
+ Args:
45
+ a: first int
46
+ b: second int
47
+ """
48
+ if b == 0:
49
+ raise ValueError("Cannot divide by zero.")
50
+ return a / b
51
+
52
+ @tool
53
+ def modulus(a: int, b: int) -> int:
54
+ """Get the modulus of two numbers.
55
+
56
+ Args:
57
+ a: first int
58
+ b: second int
59
+ """
60
+ return a % b
61
+
62
+ @tool
63
+ def wiki_search(query: str) -> str:
64
+ """Tool to search Wikipedia for a query about a known or historical person or subject and return maximum 2 results.
65
+
66
+ Args:
67
+ query: The search query."""
68
+ search_docs = WikipediaLoader(query=query, load_max_docs=2).load()
69
+ formatted_search_docs = "\n\n---\n\n".join(
70
+ [
71
+ f'<Document source="{doc.metadata["source"]}" page="{doc.metadata.get("page", "")}"/>\n{doc.page_content}\n</Document>'
72
+ for doc in search_docs
73
+ ])
74
+ return {"wiki_results": formatted_search_docs}
75
+
76
+ @tool
77
+ def web_search(query: str) -> str:
78
+ """Search Tavily for a query and return maximum 3 results.
79
+
80
+ Args:
81
+ query: The search query."""
82
+ search_docs = TavilySearchResults(max_results=3).invoke(query=query)
83
+ formatted_search_docs = "\n\n---\n\n".join(
84
+ [
85
+ f'<Document source="{doc.metadata["source"]}" page="{doc.metadata.get("page", "")}"/>\n{doc.page_content}\n</Document>'
86
+ for doc in search_docs
87
+ ])
88
+ return {"web_results": formatted_search_docs}
89
+
90
+ @tool
91
+ def arvix_search(query: str) -> str:
92
+ """Tool to search Arxiv for a query about a research paper or article and return maximum 3 results.
93
+
94
+ Args:
95
+ query: The search query."""
96
+ search_docs = ArxivLoader(query=query, load_max_docs=3).load()
97
+ # formatted_search_docs = "\n\n---\n\n".join(
98
+ # [
99
+ # f'<Document source="{doc.metadata.get("source", None)}" page="{doc.metadata.get("page", "")}"/>\n{doc.page_content[:1000]}\n</Document>'
100
+ # for doc in search_docs
101
+ # ])
102
+ # return {"arvix_results": formatted_search_docs}
103
+ return search_docs
104
+
tools copy.py ADDED
@@ -0,0 +1,352 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import re
3
+ import tempfile
4
+ import mimetypes
5
+ import requests
6
+ import pandas as pd
7
+ import fitz # PyMuPDF
8
+ from urllib.parse import unquote
9
+ from smolagents import Tool
10
+ from smolagents import Tool
11
+ import requests
12
+ import traceback
13
+ from langchain_community.retrievers import BM25Retriever
14
+ from smolagents import Tool
15
+ import math
16
+
17
+ class DownloadFileFromTaskTool(Tool):
18
+ name = "download_file_from_task"
19
+ description = """Downloads a file for a GAIA task ID and saves it in a temporary directory.
20
+ Use this when question requires information from a mentioned file, before reading a file."""
21
+
22
+ inputs = {
23
+ "task_id": {
24
+ "type": "string",
25
+ "description": "The GAIA task ID (REQUIRED)."
26
+ },
27
+ "filename": {
28
+ "type": "string",
29
+ "description": "Optional custom filename to save the file as (e.g., 'data.xlsx').",
30
+ "nullable": True
31
+ }
32
+ }
33
+ output_type = "string"
34
+
35
+ def forward(self, task_id: str, filename: str = None) -> str:
36
+ if not task_id or not re.match(r"^[0-9a-f\-]{36}$", task_id):
37
+ return "❌ Invalid or missing task_id."
38
+
39
+ file_url = f"https://agents-course-unit4-scoring.hf.space/files/{task_id}"
40
+ try:
41
+ response = requests.get(file_url, timeout=15)
42
+ if response.status_code == 404:
43
+ return "⚠️ No file found for this task."
44
+ response.raise_for_status()
45
+
46
+ # Try extracting filename and extension from header
47
+ disposition = response.headers.get("content-disposition", "")
48
+ header_filename_match = re.search(r'filename="(.+?)"', disposition)
49
+ ext = ""
50
+ if header_filename_match:
51
+ ext = os.path.splitext(header_filename_match.group(1))[1]
52
+
53
+ # Final filename logic
54
+ if not filename:
55
+ filename = f"{task_id}{ext or '.bin'}"
56
+
57
+ temp_dir = tempfile.mkdtemp()
58
+ file_path = os.path.join(temp_dir, filename)
59
+
60
+ with open(file_path, "wb") as f:
61
+ f.write(response.content)
62
+
63
+ print(f"File saved at: {file_path}")
64
+ return file_path
65
+ except Exception as e:
66
+ return f"❌ Error: {e}"
67
+
68
+ class ReadFileContentTool(Tool):
69
+ name = "read_file_content"
70
+ description = """Reads and returns the content of a file. Use after downloading a file using `download_file_from_task`."""
71
+
72
+ inputs = {
73
+ "file_path": {
74
+ "type": "string",
75
+ "description": "Full path to a file to read."
76
+ }
77
+ }
78
+ output_type = "string"
79
+
80
+ def forward(self, file_path: str) -> str:
81
+ if not os.path.exists(file_path):
82
+ return f"❌ File does not exist: {file_path}"
83
+
84
+ ext = os.path.splitext(file_path)[1].lower()
85
+
86
+ try:
87
+ if ext == ".txt":
88
+ with open(file_path, "r", encoding="utf-8") as f:
89
+ return f.read()
90
+
91
+ elif ext == ".csv":
92
+ df = pd.read_csv(file_path)
93
+ return df.head().to_string(index=False)
94
+
95
+ elif ext == ".xlsx":
96
+ df = pd.read_excel(file_path)
97
+ return df.head().to_string(index=False)
98
+
99
+ elif ext == ".pdf":
100
+ doc = fitz.open(file_path)
101
+ text = ""
102
+ for page in doc:
103
+ text += page.get_text()
104
+ doc.close()
105
+ return text.strip() or "⚠️ PDF contains no readable text."
106
+
107
+ elif ext == ".json":
108
+ with open(file_path, "r", encoding="utf-8") as f:
109
+ return f.read()
110
+
111
+ elif ext == ".py":
112
+ with open(file_path, "r", encoding="utf-8") as f:
113
+ return f.read()
114
+
115
+ elif ext in [".mp3", ".wav"]:
116
+ return f"ℹ️ Audio file detected: {os.path.basename(file_path)}. Use audio processing tool if needed."
117
+
118
+ elif ext in [".mp4", ".mov", ".avi"]:
119
+ return f"ℹ️ Video file detected: {os.path.basename(file_path)}. Use video analysis tool if available."
120
+
121
+ else:
122
+ return f"ℹ️ Unsupported file type: {ext}. File saved at {file_path}"
123
+
124
+ except Exception as e:
125
+ return f"❌ Could not read {file_path}: {e}"
126
+
127
+ class GetWikipediaInfoTool(Tool):
128
+ name = "get_wikipedia_info"
129
+ description = """Fetches a short summary about a topic from Wikipedia.
130
+ Use this when a user asks for background information, an explanation, or context on a well-known subject."""
131
+
132
+ inputs = {
133
+ "topic": {
134
+ "type": "string",
135
+ "description": "The topic to search for on Wikipedia."
136
+ }
137
+ }
138
+ output_type = "string"
139
+
140
+ def forward(self, topic: str) -> str:
141
+ print(f"EXECUTING TOOL: get_wikipedia_info(topic='{topic}')")
142
+ try:
143
+ search_url = f"https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch={topic}&format=json"
144
+ search_response = requests.get(search_url, timeout=10)
145
+ search_response.raise_for_status()
146
+ search_data = search_response.json()
147
+
148
+ if not search_data.get('query', {}).get('search', []):
149
+ return f"No Wikipedia info for '{topic}'."
150
+
151
+ page_id = search_data['query']['search'][0]['pageid']
152
+
153
+ content_url = (
154
+ f"https://en.wikipedia.org/w/api.php?action=query&prop=extracts&"
155
+ f"exintro=1&explaintext=1&pageids={page_id}&format=json"
156
+ )
157
+ content_response = requests.get(content_url, timeout=10)
158
+ content_response.raise_for_status()
159
+ content_data = content_response.json()
160
+
161
+ extract = content_data['query']['pages'][str(page_id)]['extract']
162
+ if len(extract) > 1500:
163
+ extract = extract[:1500] + "..."
164
+
165
+ result = f"Wikipedia summary for '{topic}':\n{extract}"
166
+ print(f"-> Tool Result (Wikipedia): {result[:100]}...")
167
+ return result
168
+
169
+ except Exception as e:
170
+ print(f"❌ Error in get_wikipedia_info: {e}")
171
+ traceback.print_exc()
172
+ return f"Error wiki: {e}"
173
+
174
+ class VisitWebpageTool(Tool):
175
+ name = "visit_webpage"
176
+ description = """
177
+ Visits a given URL and returns structured page content including title, metadata, headings, paragraphs,
178
+ tables, lists, and links.
179
+ """
180
+
181
+ inputs = {
182
+ "url": {
183
+ "type": "string",
184
+ "description": "The full URL of the webpage to visit."
185
+ }
186
+ }
187
+ output_type = "string"
188
+
189
+ def forward(self, url: str) -> str:
190
+ try:
191
+ import requests
192
+ from bs4 import BeautifulSoup
193
+ import json
194
+
195
+ response = requests.get(url, timeout=10)
196
+ response.raise_for_status()
197
+ soup = BeautifulSoup(response.text, "html.parser")
198
+
199
+ def clean(text):
200
+ return ' '.join(text.strip().split())
201
+
202
+ def extract_tables(soup):
203
+ tables_data = []
204
+ for table in soup.find_all("table"):
205
+ headers = [clean(th.get_text()) for th in table.find_all("th")]
206
+ rows = []
207
+ for row in table.find_all("tr"):
208
+ cells = [clean(td.get_text()) for td in row.find_all("td")]
209
+ if cells:
210
+ rows.append(cells)
211
+ if headers and rows:
212
+ tables_data.append({"headers": headers, "rows": rows})
213
+ return tables_data
214
+
215
+ def extract_lists(soup):
216
+ all_lists = []
217
+ for ul in soup.find_all("ul"):
218
+ items = [clean(li.get_text()) for li in ul.find_all("li")]
219
+ if items:
220
+ all_lists.append(items)
221
+ for ol in soup.find_all("ol"):
222
+ items = [clean(li.get_text()) for li in ol.find_all("li")]
223
+ if items:
224
+ all_lists.append(items)
225
+ return all_lists
226
+
227
+ def extract_meta(soup):
228
+ metas = {}
229
+ for meta in soup.find_all("meta"):
230
+ name = meta.get("name") or meta.get("property")
231
+ content = meta.get("content")
232
+ if name and content:
233
+ metas[name.lower()] = clean(content)
234
+ return metas
235
+
236
+ result = {
237
+ "title": clean(soup.title.string) if soup.title else None,
238
+ "meta": extract_meta(soup),
239
+ "headings": {
240
+ "h1": [clean(h.get_text()) for h in soup.find_all("h1")],
241
+ "h2": [clean(h.get_text()) for h in soup.find_all("h2")],
242
+ "h3": [clean(h.get_text()) for h in soup.find_all("h3")],
243
+ },
244
+ "paragraphs": [clean(p.get_text()) for p in soup.find_all("p")],
245
+ "lists": extract_lists(soup),
246
+ "tables": extract_tables(soup),
247
+ "links": [
248
+ {"text": clean(a.get_text()), "href": a["href"]}
249
+ for a in soup.find_all("a", href=True)
250
+ ],
251
+ }
252
+
253
+ return json.dumps(result, indent=2)
254
+
255
+ except Exception as e:
256
+ return f"❌ Failed to fetch or parse webpage: {str(e)}"
257
+
258
+ class TranscribeAudioTool(Tool):
259
+ name = "transcribe_audio"
260
+ description = """Transcribes spoken audio (e.g. voice memos, lectures) into plain text."""
261
+
262
+ inputs = {
263
+ "file_path": {
264
+ "type": "string",
265
+ "description": "Path to an audio file."
266
+ }
267
+ }
268
+ output_type = "string"
269
+
270
+ def forward(self, file_path: str) -> str:
271
+ try:
272
+ import speech_recognition as sr
273
+ from pydub import AudioSegment
274
+ import os
275
+ import tempfile
276
+
277
+ # Initialize recognizer
278
+ recognizer = sr.Recognizer()
279
+
280
+ # Convert to WAV if not already (needed for speech_recognition)
281
+ file_ext = os.path.splitext(file_path)[1].lower()
282
+
283
+ if file_ext != '.wav':
284
+ # Create temp WAV file
285
+ temp_wav = tempfile.NamedTemporaryFile(suffix='.wav', delete=False).name
286
+
287
+ # Convert to WAV using pydub
288
+ audio = AudioSegment.from_file(file_path)
289
+ audio.export(temp_wav, format="wav")
290
+ audio_path = temp_wav
291
+ else:
292
+ audio_path = file_path
293
+
294
+ # Transcribe audio using Google's speech recognition
295
+ with sr.AudioFile(audio_path) as source:
296
+ audio_data = recognizer.record(source)
297
+ transcript = recognizer.recognize_google(audio_data)
298
+
299
+ # Clean up temp file if created
300
+ if file_ext != '.wav' and os.path.exists(temp_wav):
301
+ os.remove(temp_wav)
302
+
303
+ return transcript.strip()
304
+
305
+ except Exception as e:
306
+ return f"❌ Transcription failed: {str(e)}"
307
+
308
+ class TranscibeVideoFileTool(Tool):
309
+ name = "transcribe_video"
310
+ description = """Transcribes speech from a video file. Use this to understand video lectures, tutorials, or visual demos."""
311
+
312
+ inputs = {
313
+ "file_path": {
314
+ "type": "string",
315
+ "description": "Path to the video file (e.g., .mp4, .mov)."
316
+ }
317
+ }
318
+ output_type = "string"
319
+
320
+ def forward(self, file_path: str) -> str:
321
+ try:
322
+ import moviepy.editor as mp
323
+ import speech_recognition as sr
324
+ import os
325
+ import tempfile
326
+
327
+ # Extract audio from video
328
+ video = mp.VideoFileClip(file_path)
329
+
330
+ # Create temporary audio file
331
+ temp_audio = tempfile.NamedTemporaryFile(suffix='.wav', delete=False).name
332
+
333
+ # Extract audio to WAV format (required for speech_recognition)
334
+ video.audio.write_audiofile(temp_audio, verbose=False, logger=None)
335
+ video.close()
336
+
337
+ # Initialize recognizer
338
+ recognizer = sr.Recognizer()
339
+
340
+ # Transcribe audio
341
+ with sr.AudioFile(temp_audio) as source:
342
+ audio_data = recognizer.record(source)
343
+ transcript = recognizer.recognize_google(audio_data)
344
+
345
+ # Clean up temp file
346
+ if os.path.exists(temp_audio):
347
+ os.remove(temp_audio)
348
+
349
+ return transcript.strip()
350
+
351
+ except Exception as e:
352
+ return f"❌ Video processing failed: {str(e)}"
tools.py ADDED
@@ -0,0 +1,1078 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import re
3
+ import tempfile
4
+ import mimetypes
5
+ import requests
6
+ import pandas as pd
7
+ import fitz # PyMuPDF
8
+ from urllib.parse import unquote
9
+ from smolagents import Tool
10
+ import requests
11
+ import traceback
12
+ import math
13
+ from langchain_community.tools import BraveSearch
14
+ from typing import List, Dict
15
+ import json
16
+ import html
17
+ import requests, cv2, numpy as np, os
18
+ import html
19
+ import json
20
+ import requests
21
+ from bs4 import BeautifulSoup
22
+ from langchain_community.document_loaders import ArxivLoader
23
+ import arxiv
24
+ from smolagents import tool
25
+
26
+ from smolagents.tools import Tool
27
+ import requests
28
+ import os
29
+ import mimetypes
30
+ import traceback
31
+ from urllib.parse import urlparse
32
+
33
+ import time
34
+ import traceback
35
+ from duckduckgo_search import DDGS
36
+ from duckduckgo_search.exceptions import (
37
+ DuckDuckGoSearchException,
38
+ RatelimitException,
39
+ TimeoutException,
40
+ ConversationLimitException,
41
+ )
42
+
43
+ from smolagents.tools import Tool
44
+ import chromadb
45
+ from pathlib import Path
46
+ import traceback
47
+ import json
48
+ import os
49
+ from langchain.document_loaders import (
50
+ TextLoader, PyPDFLoader, JSONLoader, UnstructuredFileLoader,BSHTMLLoader
51
+ )
52
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
53
+
54
+ import chromadb.utils.embedding_functions as embedding_functions
55
+
56
+ import os
57
+ import pandas as pd
58
+ import fitz # PyMuPDF
59
+ from markdownify import markdownify
60
+ from bs4 import BeautifulSoup
61
+ import re
62
+ from smolagents.utils import truncate_content
63
+ import requests
64
+ from bs4 import BeautifulSoup
65
+ from markdownify import markdownify
66
+ import re
67
+ from smolagents.utils import truncate_content
68
+
69
+ class ReadFileContentTool(Tool):
70
+ name = "read_file_content"
71
+ description = """Reads local files in various formats (text, CSV, Excel, PDF, HTML, etc.) and returns their content as readable text. Automatically detects and processes the appropriate file format."""
72
+
73
+ inputs = {
74
+ "file_path": {
75
+ "type": "string",
76
+ "description": "The full path to the file from which the content should be read."
77
+ }
78
+ }
79
+ output_type = "string"
80
+
81
+ def forward(self, file_path: str) -> str:
82
+ if not os.path.exists(file_path):
83
+ return f"❌ File does not exist: {file_path}"
84
+
85
+ ext = os.path.splitext(file_path)[1].lower()
86
+
87
+ try:
88
+ if ext == ".txt":
89
+ with open(file_path, "r", encoding="utf-8") as f:
90
+ return truncate_content(f.read())
91
+
92
+ elif ext == ".csv":
93
+ df = pd.read_csv(file_path)
94
+ return truncate_content(f"CSV Content:\n{df.to_string(index=False)}\n\nColumn names: {', '.join(df.columns)}")
95
+
96
+ elif ext in [".xlsx", ".xls"]:
97
+ df = pd.read_excel(file_path)
98
+ return truncate_content(f"Excel Content:\n{df.to_string(index=False)}\n\nColumn names: {', '.join(df.columns)}")
99
+
100
+ elif ext == ".pdf":
101
+ doc = fitz.open(file_path)
102
+ text = "".join([page.get_text() for page in doc])
103
+ doc.close()
104
+ return truncate_content(text.strip() or "⚠️ PDF contains no readable text.")
105
+
106
+ elif ext == ".json":
107
+ with open(file_path, "r", encoding="utf-8") as f:
108
+ return truncate_content(f.read())
109
+
110
+ elif ext == ".py":
111
+ with open(file_path, "r", encoding="utf-8") as f:
112
+ return truncate_content(f.read())
113
+
114
+ elif ext in [".html", ".htm"]:
115
+ with open(file_path, "r", encoding="utf-8") as f:
116
+ html = f.read()
117
+ try:
118
+ markdown = markdownify(html).strip()
119
+ markdown = re.sub(r"\n{3,}", "\n\n", markdown)
120
+ return f"📄 HTML content (converted to Markdown):\n\n{truncate_content(markdown)}"
121
+ except Exception:
122
+ soup = BeautifulSoup(html, "html.parser")
123
+ text = soup.get_text(separator="\n").strip()
124
+ return f"📄 HTML content (raw text fallback):\n\n{truncate_content(text)}"
125
+
126
+ elif ext in [".mp3", ".wav"]:
127
+ return f"ℹ️ Audio file detected: {os.path.basename(file_path)}. Use transcribe_audio tool to process the audio content."
128
+
129
+ elif ext in [".mp4", ".mov", ".avi"]:
130
+ return f"ℹ️ Video file detected: {os.path.basename(file_path)}. Use transcribe_video tool to process the video content."
131
+
132
+ else:
133
+ return f"ℹ️ Unsupported file type: {ext}. File saved at {file_path}"
134
+
135
+ except Exception as e:
136
+ return f"❌ Could not read {file_path}: {e}"
137
+
138
+ class WikipediaSearchTool(Tool):
139
+ name = "wikipedia_search"
140
+ description = """Searches Wikipedia for a specific topic and returns a concise summary. Useful for background information on subjects, concepts, historical events, or scientific topics."""
141
+
142
+ inputs = {
143
+ "query": {
144
+ "type": "string",
145
+ "description": "The query or subject to search for on Wikipedia."
146
+ }
147
+ }
148
+ output_type = "string"
149
+
150
+ def forward(self, query: str) -> str:
151
+ print(f"EXECUTING TOOL: wikipedia_search(query='{query}')")
152
+ try:
153
+ search_link = f"https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch={query}&format=json"
154
+ search_response = requests.get(search_link, timeout=10)
155
+ search_response.raise_for_status()
156
+ search_data = search_response.json()
157
+
158
+ if not search_data.get('query', {}).get('search', []):
159
+ return f"No Wikipedia info for '{query}'."
160
+
161
+ page_id = search_data['query']['search'][0]['pageid']
162
+
163
+ content_link = (
164
+ f"https://en.wikipedia.org/w/api.php?action=query&prop=extracts&"
165
+ f"exintro=1&explaintext=1&pageids={page_id}&format=json"
166
+ )
167
+ content_response = requests.get(content_link, timeout=10)
168
+ content_response.raise_for_status()
169
+ content_data = content_response.json()
170
+
171
+ extract = content_data['query']['pages'][str(page_id)]['extract']
172
+ if len(extract) > 1500:
173
+ extract = extract[:1500] + "..."
174
+
175
+ result = f"Wikipedia summary for '{query}':\n{extract}"
176
+ print(f"-> Tool Result (Wikipedia): {result[:100]}...")
177
+ return result
178
+
179
+ except Exception as e:
180
+ print(f"❌ Error in wikipedia_search: {e}")
181
+ traceback.print_exc()
182
+ return f"Error wiki: {e}"
183
+
184
+ class VisitWebpageTool(Tool):
185
+ name = "visit_webpage"
186
+ description = (
187
+ "Loads a webpage from a URL and converts its content to markdown format. Use this to browse websites, extract information, or identify downloadable resources from a specific web address."
188
+ )
189
+ inputs = {
190
+ "url": {
191
+ "type": "string",
192
+ "description": "The url of the webpage to visit.",
193
+ }
194
+ }
195
+ output_type = "string"
196
+
197
+ def forward(self, url: str) -> str:
198
+ try:
199
+ import re
200
+
201
+ import requests
202
+ from markdownify import markdownify
203
+ from requests.exceptions import RequestException
204
+
205
+ from smolagents.utils import truncate_content
206
+ except ImportError as e:
207
+ raise ImportError(
208
+ "You must install packages `markdownify` and `requests` to run this tool: for instance run `pip install markdownify requests`."
209
+ ) from e
210
+ try:
211
+ response = requests.get(url, timeout=20)
212
+ response.raise_for_status() # Raise an exception for bad status codes
213
+ markdown_content = markdownify(response.text).strip()
214
+ markdown_content = re.sub(r"\n{3,}", "\n\n", markdown_content)
215
+ return truncate_content(markdown_content, 5000)
216
+
217
+ except requests.exceptions.Timeout:
218
+ return "The request timed out. Please try again later or check the URL."
219
+ except RequestException as e:
220
+ return f"Error fetching the webpage: {str(e)}"
221
+ except Exception as e:
222
+ return f"An unexpected error occurred: {str(e)}"
223
+
224
+ class TranscribeAudioTool(Tool):
225
+ name = "transcribe_audio"
226
+ description = """Converts spoken content in audio files to text. Handles various audio formats and produces a transcript of the spoken content for analysis."""
227
+
228
+ inputs = {
229
+ "file_path": {
230
+ "type": "string",
231
+ "description": "The full path to the audio file that needs to be transcribed."
232
+ }
233
+ }
234
+ output_type = "string"
235
+
236
+
237
+ def forward(self, file_path: str) -> str:
238
+ try:
239
+ import speech_recognition as sr
240
+ from pydub import AudioSegment
241
+ import os
242
+ import tempfile
243
+
244
+ # Verify file exists
245
+ if not os.path.exists(file_path):
246
+ return f"❌ Audio file not found at: {file_path}. Download the file first."
247
+
248
+ # Initialize recognizer
249
+ recognizer = sr.Recognizer()
250
+
251
+ # Convert to WAV if not already (needed for speech_recognition)
252
+ file_ext = os.path.splitext(file_path)[1].lower()
253
+
254
+ if file_ext != '.wav':
255
+ # Create temp WAV file
256
+ temp_wav = tempfile.NamedTemporaryFile(suffix='.wav', delete=False).name
257
+
258
+ # Convert to WAV using pydub
259
+ audio = AudioSegment.from_file(file_path)
260
+ audio.export(temp_wav, format="wav")
261
+ audio_path = temp_wav
262
+ else:
263
+ audio_path = file_path
264
+
265
+ # Transcribe audio using Google's speech recognition
266
+ with sr.AudioFile(audio_path) as source:
267
+ audio_data = recognizer.record(source)
268
+ transcript = recognizer.recognize_google(audio_data)
269
+
270
+ # Clean up temp file if created
271
+ if file_ext != '.wav' and os.path.exists(temp_wav):
272
+ os.remove(temp_wav)
273
+
274
+ return transcript.strip()
275
+
276
+ except Exception as e:
277
+ return f"❌ Transcription failed: {str(e)}"
278
+
279
+ class TranscibeVideoFileTool(Tool):
280
+ name = "transcribe_video"
281
+ description = """Extracts and transcribes speech from video files. Converts the audio portion of videos into readable text for analysis or reference."""
282
+
283
+ inputs = {
284
+ "file_path": {
285
+ "type": "string",
286
+ "description": "The full path to the video file that needs to be transcribed."
287
+ }
288
+ }
289
+ output_type = "string"
290
+
291
+ def forward(self, file_path: str) -> str:
292
+ try:
293
+ # Verify file exists
294
+ if not os.path.exists(file_path):
295
+ return f"❌ Video file not found at: {file_path}. Download the file first."
296
+
297
+ import moviepy.editor as mp
298
+ import speech_recognition as sr
299
+ import os
300
+ import tempfile
301
+
302
+ # Extract audio from video
303
+ video = mp.VideoFileClip(file_path)
304
+
305
+ # Create temporary audio file
306
+ temp_audio = tempfile.NamedTemporaryFile(suffix='.wav', delete=False).name
307
+
308
+ # Extract audio to WAV format (required for speech_recognition)
309
+ video.audio.write_audiofile(temp_audio, verbose=False, logger=None)
310
+ video.close()
311
+
312
+ # Initialize recognizer
313
+ recognizer = sr.Recognizer()
314
+
315
+ # Transcribe audio
316
+ with sr.AudioFile(temp_audio) as source:
317
+ audio_data = recognizer.record(source)
318
+ transcript = recognizer.recognize_google(audio_data)
319
+
320
+ # Clean up temp file
321
+ if os.path.exists(temp_audio):
322
+ os.remove(temp_audio)
323
+
324
+ return transcript.strip()
325
+
326
+ except Exception as e:
327
+ return f"❌ Video processing failed: {str(e)}"
328
+
329
+ class BraveWebSearchTool(Tool):
330
+ name = "web_search"
331
+ description = """Performs web searches and returns content from top results. Provides real-time information from across the internet including current events, facts, and website content relevant to your query."""
332
+
333
+ inputs = {
334
+ "query": {
335
+ "type": "string",
336
+ "description": "A web search query string (e.g., a question or query)."
337
+ }
338
+ }
339
+ output_type = "string"
340
+
341
+ api_key = os.getenv("BRAVE_SEARCH_API_KEY")
342
+ count = 3
343
+ char_limit = 4000 # Adjust based on LLM context window
344
+ tool = BraveSearch.from_api_key(api_key=api_key, search_kwargs={"count": count})
345
+
346
+ def extract_main_text(self, url: str, char_limit: int) -> str:
347
+ try:
348
+ headers = {"User-Agent": "Mozilla/5.0"}
349
+ response = requests.get(url, headers=headers, timeout=10)
350
+ soup = BeautifulSoup(response.text, "html.parser")
351
+
352
+ # Remove scripts/styles
353
+ for tag in soup(["script", "style", "noscript"]):
354
+ tag.extract()
355
+
356
+ # Heuristic: extract visible text from body
357
+ body = soup.body
358
+ if not body:
359
+ return "⚠️ Could not extract content."
360
+
361
+ text = " ".join(t.strip() for t in body.stripped_strings)
362
+ return text[:char_limit].strip()
363
+ except Exception as e:
364
+ return f"⚠️ Failed to extract article: {e}"
365
+
366
+ def forward(self, query: str) -> str:
367
+ try:
368
+ results_json = self.tool.run(query)
369
+ results = json.loads(results_json) if isinstance(results_json, str) else results_json
370
+
371
+ output_parts = []
372
+ for i, r in enumerate(results[:self.count], start=1):
373
+ title = html.unescape(r.get("title", "").strip())
374
+ link = r.get("link", "").strip()
375
+
376
+ article_text = self.extract_main_text(link, self.char_limit)
377
+
378
+ result_block = (
379
+ f"Result {i}:\n"
380
+ f"Title: {title}\n"
381
+ f"URL: {link}\n"
382
+ f"Extracted Content:\n{article_text}\n"
383
+ )
384
+ output_parts.append(result_block)
385
+
386
+ return "\n\n".join(output_parts).strip()
387
+
388
+ except Exception as e:
389
+ return f"Search failed: {str(e)}"
390
+
391
+ class DescribeImageTool(Tool):
392
+ name = "describe_image"
393
+ description = """Analyzes images and generates detailed text descriptions. Identifies objects, scenes, text, and visual elements within the image to provide context or understanding."""
394
+
395
+ inputs = {
396
+ "image_path": {
397
+ "type": "string",
398
+ "description": "The full path to the image file to describe."
399
+ }
400
+ }
401
+ output_type = "string"
402
+
403
+ def forward(self, image_path: str) -> str:
404
+ import os
405
+ from PIL import Image
406
+ import torch
407
+ from transformers import BlipProcessor, BlipForConditionalGeneration
408
+
409
+ if not os.path.exists(image_path):
410
+ return f"❌ Image file does not exist: {image_path}"
411
+
412
+ try:
413
+ processor = BlipProcessor.from_pretrained("Salesforce/blip-image-captioning-base", use_fast = True)
414
+ model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-base")
415
+
416
+ image = Image.open(image_path).convert("RGB")
417
+ inputs = processor(images=image, return_tensors="pt")
418
+ output_ids = model.generate(**inputs)
419
+
420
+ caption = processor.decode(output_ids[0], skip_special_tokens=True)
421
+ return caption.strip() or "⚠️ No caption could be generated."
422
+ except Exception as e:
423
+ return f"❌ Failed to describe image: {e}"
424
+
425
+ class DownloadFileFromLinkTool(Tool):
426
+ name = "download_file_from_link"
427
+ description = "Downloads files from a URL and saves them locally. Supports various formats including PDFs, documents, images, and data files. Returns the local file path for further processing."
428
+
429
+ inputs = {
430
+ "link": {
431
+ "type": "string",
432
+ "description": "The URL to download the file from."
433
+ },
434
+ "file_name": {
435
+ "type": "string",
436
+ "description": "Desired name of the saved file, without extension.",
437
+ "nullable": True
438
+ }
439
+ }
440
+
441
+ output_type = "string"
442
+ SUPPORTED_EXTENSIONS = {'.xlsx','.pdf', '.txt', '.csv', '.json', '.xml', '.html', '.jpg', '.jpeg', '.png', '.mp4', '.mp3', '.wav', '.zip'}
443
+
444
+ def forward(self, link: str, file_name: str = "taskfile") -> str:
445
+ print(f"⬇️ Downloading file from: {link}")
446
+ dir_path = "./downloads"
447
+ os.makedirs(dir_path, exist_ok=True)
448
+
449
+ try:
450
+ response = requests.get(link, stream=True, timeout=30)
451
+ except requests.RequestException as e:
452
+ return f"❌ Error: Request failed - {e}"
453
+
454
+ if response.status_code != 200:
455
+ return f"❌ Error: Unable to fetch file. Status code: {response.status_code}"
456
+
457
+ # Step 1: Try extracting extension from provided filename
458
+ base_name, provided_ext = os.path.splitext(file_name)
459
+ provided_ext = provided_ext.lower()
460
+
461
+ # Step 2: Check if provided extension is supported
462
+ if provided_ext and provided_ext in self.SUPPORTED_EXTENSIONS:
463
+ ext = provided_ext
464
+ else:
465
+ # Step 3: Try to infer from Content-Type
466
+ content_type = response.headers.get("Content-Type", "").split(";")[0].strip()
467
+ guessed_ext = mimetypes.guess_extension(content_type or "") or ""
468
+
469
+ # Step 4: If mimetype returned .bin or nothing useful, try to fallback to URL
470
+ if guessed_ext in ("", ".bin"):
471
+ parsed_link = urlparse(link)
472
+ _, url_ext = os.path.splitext(parsed_link.path)
473
+ if url_ext.lower() in self.SUPPORTED_EXTENSIONS:
474
+ ext = url_ext.lower()
475
+ else:
476
+ return f"⚠️ Warning: Cannot determine a valid file extension from '{content_type}' or URL. Please retry with an explicit valid filename and extension."
477
+ else:
478
+ ext = guessed_ext
479
+
480
+ # Step 5: Final path and save
481
+ file_path = os.path.join(dir_path, base_name + ext)
482
+ downloaded = 0
483
+
484
+ with open(file_path, "wb") as f:
485
+ for chunk in response.iter_content(chunk_size=1024):
486
+ if chunk:
487
+ f.write(chunk)
488
+ downloaded += len(chunk)
489
+
490
+ return file_path
491
+
492
+ class DuckDuckGoSearchTool(Tool):
493
+ name = "web_search"
494
+ description = """Performs web searches and returns content from top results. Provides real-time information from across the internet including current events, facts, and website content relevant to your query."""
495
+
496
+ inputs = {
497
+ "query": {
498
+ "type": "string",
499
+ "description": "The search query to run on DuckDuckGo"
500
+ },
501
+ }
502
+ output_type = "string"
503
+
504
+ def _configure(self, max_retries: int = 3, retry_sleep: int = 3):
505
+ self._max_retries = max_retries
506
+ self._retry_sleep = retry_sleep
507
+
508
+ def forward(self, query: str) -> str:
509
+ self._configure()
510
+ print(f"EXECUTING TOOL: duckduckgo_search(query='{query}', top_results={top_results})")
511
+
512
+ top_results = 5
513
+
514
+ retries = 0
515
+ max_retries = getattr(self, "_max_retries", 3)
516
+ retry_sleep = getattr(self, "_retry_sleep", 2)
517
+
518
+ while retries < max_retries:
519
+ try:
520
+ results = DDGS().text(
521
+ keywords=query,
522
+ region="wt-wt",
523
+ safesearch="moderate",
524
+ max_results=top_results,
525
+ )
526
+
527
+ if not results:
528
+ return "No results found."
529
+
530
+ output_lines = []
531
+ for idx, res in enumerate(results[:top_results], start=1):
532
+ title = res.get("title", "N/A")
533
+ url = res.get("href", "N/A")
534
+ snippet = res.get("body", "N/A")
535
+
536
+ output_lines.append(
537
+ f"Result {idx}:\n"
538
+ f"Title: {title}\n"
539
+ f"URL: {url}\n"
540
+ f"Snippet: {snippet}\n"
541
+ )
542
+
543
+ output = "\n".join(output_lines)
544
+
545
+ print(f"-> Tool Result (DuckDuckGo): {output[:1500]}...")
546
+ return output
547
+
548
+ except (DuckDuckGoSearchException, TimeoutException, RatelimitException, ConversationLimitException) as e:
549
+ retries += 1
550
+ print(f"⚠️ DuckDuckGo Exception (Attempt {retries}/{max_retries}): {type(e).__name__}: {e}")
551
+ traceback.print_exc()
552
+ time.sleep(retry_sleep)
553
+
554
+ except Exception as e:
555
+ print(f"❌ Unexpected Error: {e}")
556
+ traceback.print_exc()
557
+ return f"Unhandled exception during DuckDuckGo search: {e}"
558
+
559
+ return f"❌ Failed to retrieve results after {max_retries} retries."
560
+
561
+ huggingface_ef = embedding_functions.HuggingFaceEmbeddingFunction(
562
+ api_key=os.environ["HF_TOKEN"],
563
+ model_name="sentence-transformers/all-mpnet-base-v2"
564
+ )
565
+ SUPPORTED_EXTENSIONS = [".txt", ".md", ".py", ".pdf", ".json", ".jsonl", '.html', '.htm']
566
+
567
+ class AddDocumentToVectorStoreTool(Tool):
568
+ name = "add_document_to_vector_store"
569
+ description = "Processes a document and adds it to the vector database for semantic search. Automatically chunks files and creates text embeddings to enable powerful content retrieval."
570
+
571
+ inputs = {
572
+ "file_path": {
573
+ "type": "string",
574
+ "description": "Absolute path to the file to be indexed.",
575
+ }
576
+ }
577
+
578
+ output_type = "string"
579
+
580
+ def _load_file(self, path: Path):
581
+ """Select the right loader for the file extension."""
582
+ if path.suffix == ".pdf":
583
+ return PyPDFLoader(str(path)).load()
584
+ elif path.suffix == ".json":
585
+ return JSONLoader(str(path), jq_schema=".").load()
586
+ elif path.suffix in [".md"]:
587
+ return UnstructuredFileLoader(str(path)).load()
588
+ elif path.suffix in [".html", ".htm"]:
589
+ return BSHTMLLoader(str(path)).load()
590
+ else: # fallback for .txt, .py, etc.
591
+ return TextLoader(str(path)).load()
592
+
593
+ def forward(self, file_path: str) -> str:
594
+ print(f"📄 Adding document to vector store: {file_path}")
595
+ try:
596
+ collection_name = "vectorstore"
597
+ path = Path(file_path)
598
+ if not path.exists() or path.suffix not in SUPPORTED_EXTENSIONS:
599
+ return f"Unsupported or missing file: {file_path}"
600
+
601
+ docs = self._load_file(path)
602
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=50)
603
+ split_docs = text_splitter.split_documents(docs)
604
+
605
+ client = chromadb.Client(chromadb.config.Settings(
606
+ persist_directory="./chroma_store",
607
+ ))
608
+
609
+ collection = client.get_or_create_collection(name=collection_name,configuration={
610
+ "embedding_function": huggingface_ef
611
+ })
612
+
613
+ texts = [doc.page_content for doc in split_docs]
614
+ metadatas = [doc.metadata for doc in split_docs]
615
+
616
+ collection.add(
617
+ documents=texts,
618
+ metadatas=metadatas,
619
+ ids=[f"{path.stem}_{i}" for i in range(len(texts))]
620
+ )
621
+
622
+ return f"✅ Successfully added {len(texts)} chunks from '{file_path}' to collection '{collection_name}'."
623
+
624
+ except Exception as e:
625
+ print(f"❌ Error in add_to_vector_store: {e}")
626
+ traceback.print_exc()
627
+ return f"Error: {e}"
628
+
629
+ class QueryVectorStoreTool(Tool):
630
+ name = "query_downloaded_documents"
631
+ description = "Performs semantic searches across your downloaded documents. Use detailed queries to find specific information, concepts, or answers from your collected resources."
632
+
633
+ inputs = {
634
+ "query": {
635
+ "type": "string",
636
+ "description": "The search query. Ensure this is constructed intelligently so to retrieve the most relevant outputs.",
637
+ },
638
+ "top_k": {
639
+ "type": "integer",
640
+ "description": "Number of top results to retrieve. Usually between 3 and 30",
641
+ "nullable": True
642
+ }
643
+ }
644
+ output_type = "string"
645
+
646
+ def forward(self, query: str, top_k: int = 5) -> str:
647
+ collection_name = "vectorstore"
648
+
649
+ if k < 3:
650
+ k = 3
651
+ if k > 30:
652
+ k = 30
653
+
654
+ print(f"🔎 Querying vector store '{collection_name}' with: '{query}'")
655
+ try:
656
+ client = chromadb.Client(chromadb.config.Settings(
657
+ persist_directory="./chroma_store",
658
+ ))
659
+ collection = client.get_collection(name=collection_name)
660
+
661
+ results = collection.query(
662
+ query_texts=[query],
663
+ n_results=top_k,
664
+ )
665
+
666
+ formatted = []
667
+ for i in range(len(results["documents"][0])):
668
+ doc = results["documents"][0][i]
669
+ metadata = results["metadatas"][0][i]
670
+ formatted.append(
671
+ f"Result {i+1}:\n"
672
+ f"Content: {doc}\n"
673
+ f"Metadata: {metadata}\n"
674
+ )
675
+
676
+ return "\n".join(formatted) or "No relevant documents found."
677
+
678
+ except Exception as e:
679
+ print(f"❌ Error in query_vector_store: {e}")
680
+ traceback.print_exc()
681
+ return f"Error querying vector store: {e}"
682
+
683
+ @tool
684
+ def image_question_answering(image_path: str, prompt: str) -> str:
685
+ """
686
+ Analyzes images and answers specific questions about their content. Can identify objects, read text, describe scenes, or interpret visual information based on your questions.
687
+
688
+ Args:
689
+ image_path: The path to the image file
690
+ prompt: The question to ask about the image
691
+
692
+ Returns:
693
+ A string answer generated by the local Ollama model
694
+ """
695
+ # Check for supported file types
696
+ file_extension = image_path.lower().split(".")[-1]
697
+ if file_extension not in ["jpg", "jpeg", "png", "bmp", "gif", "webp"]:
698
+ return "Unsupported file type. Please provide an image."
699
+
700
+ path = Path(image_path)
701
+ if not path.exists():
702
+ return f"File not found at: {image_path}"
703
+
704
+ # Send the image and prompt to Ollama's local model
705
+ response = chat(
706
+ model='llava', # Assuming your model is named 'lava'
707
+ messages=[
708
+ {
709
+ 'role': 'user',
710
+ 'content': prompt,
711
+ 'images': [path],
712
+ },
713
+ ],
714
+ options={'temperature': 0.2} # Slight randomness for naturalness
715
+ )
716
+
717
+ return response.message.content.strip()
718
+
719
+
720
+ class VisitWebpageTool(Tool):
721
+ name = "visit_webpage"
722
+ description = (
723
+ "Loads a webpage from a URL and converts its content to markdown format. Use this to browse websites, extract information, or identify downloadable resources from a specific web address."
724
+ )
725
+ inputs = {
726
+ "url": {
727
+ "type": "string",
728
+ "description": "The url of the webpage to visit.",
729
+ }
730
+ }
731
+ output_type = "string"
732
+
733
+ def forward(self, url: str) -> str:
734
+ try:
735
+ import re
736
+ from urllib.parse import urlparse
737
+
738
+ import requests
739
+ from bs4 import BeautifulSoup
740
+ from markdownify import markdownify
741
+ from requests.exceptions import RequestException
742
+
743
+ from smolagents.utils import truncate_content
744
+ except ImportError as e:
745
+ raise ImportError(
746
+ "You must install packages `markdownify`, `requests`, and `beautifulsoup4` to run this tool: for instance run `pip install markdownify requests beautifulsoup4`."
747
+ ) from e
748
+
749
+ try:
750
+ # Get the webpage content
751
+ headers = {
752
+ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
753
+ }
754
+ response = requests.get(url, headers=headers, timeout=20)
755
+ response.raise_for_status()
756
+
757
+ # Parse the HTML with BeautifulSoup
758
+ soup = BeautifulSoup(response.text, 'html.parser')
759
+
760
+ # Extract domain name for context
761
+ domain = urlparse(url).netloc
762
+
763
+ # Remove common clutter elements
764
+ self._remove_clutter(soup)
765
+
766
+ # Try to identify and prioritize main content
767
+ main_content = self._extract_main_content(soup)
768
+
769
+ if main_content:
770
+ # Convert the cleaned HTML to markdown
771
+ markdown_content = markdownify(str(main_content)).strip()
772
+ else:
773
+ # Fallback to full page content if main content extraction fails
774
+ markdown_content = markdownify(str(soup)).strip()
775
+
776
+ # Post-process the markdown content
777
+ markdown_content = self._clean_markdown(markdown_content)
778
+
779
+ # Add source information
780
+ result = f"Content from {domain}:\n\n{markdown_content}"
781
+
782
+ return truncate_content(result, 40000)
783
+
784
+ except requests.exceptions.Timeout:
785
+ return "The request timed out. Please try again later or check the URL."
786
+ except RequestException as e:
787
+ return f"Error fetching the webpage: {str(e)}"
788
+ except Exception as e:
789
+ return f"An unexpected error occurred: {str(e)}"
790
+
791
+ def _remove_clutter(self, soup):
792
+ """Remove common elements that clutter web pages."""
793
+ # Common non-content elements to remove
794
+ clutter_selectors = [
795
+ 'header', 'footer', 'nav', '.nav', '.navigation', '.menu', '.sidebar',
796
+ '.footer', '.header', '#footer', '#header', '#nav', '#sidebar',
797
+ '.widget', '.cookie', '.cookies', '.ad', '.ads', '.advertisement',
798
+ 'script', 'style', 'noscript', 'iframe', '.social', '.share',
799
+ '.comment', '.comments', '.subscription', '.newsletter',
800
+ '[role="banner"]', '[role="navigation"]', '[role="complementary"]'
801
+ ]
802
+
803
+ for selector in clutter_selectors:
804
+ for element in soup.select(selector):
805
+ element.decompose()
806
+
807
+ # Remove hidden elements
808
+ for hidden in soup.select('[style*="display: none"], [style*="display:none"], [style*="visibility: hidden"], [style*="visibility:hidden"], [hidden]'):
809
+ hidden.decompose()
810
+
811
+ def _extract_main_content(self, soup):
812
+ """Try to identify and extract the main content of the page."""
813
+ # Priority order for common main content containers
814
+ main_content_selectors = [
815
+ 'main',
816
+ '[role="main"]',
817
+ 'article',
818
+ '.content',
819
+ '.main-content',
820
+ '.post-content',
821
+ '#content',
822
+ '#main',
823
+ '#main-content',
824
+ '.article',
825
+ '.post',
826
+ '.entry',
827
+ '.page-content',
828
+ '.entry-content',
829
+ ]
830
+
831
+ # Try to find the main content container
832
+ for selector in main_content_selectors:
833
+ main_content = soup.select(selector)
834
+ if main_content:
835
+ # If multiple matches, find the one with the most text content
836
+ if len(main_content) > 1:
837
+ return max(main_content, key=lambda x: len(x.get_text()))
838
+ return main_content[0]
839
+
840
+ # If no main content container found, look for the largest text block
841
+ paragraphs = soup.find_all('p')
842
+ if paragraphs:
843
+ # Find the parent that contains the most paragraphs
844
+ parents = {}
845
+ for p in paragraphs:
846
+ if p.parent:
847
+ if p.parent not in parents:
848
+ parents[p.parent] = 0
849
+ parents[p.parent] += 1
850
+
851
+ if parents:
852
+ # Return the parent with the most paragraphs
853
+ return max(parents.items(), key=lambda x: x[1])[0]
854
+
855
+ # Return None if we can't identify main content
856
+ return None
857
+
858
+ def _clean_markdown(self, content):
859
+ """Clean up the markdown content."""
860
+ # Normalize whitespace
861
+ content = re.sub(r'\n{3,}', '\n\n', content)
862
+
863
+ # Remove consecutive duplicate links
864
+ content = re.sub(r'(\[.*?\]\(.*?\))\s*\1+', r'\1', content)
865
+
866
+ # Remove very short lines that are likely menu items
867
+ lines = content.split('\n')
868
+ filtered_lines = []
869
+
870
+ # Skip consecutive short lines (likely menus)
871
+ short_line_threshold = 40 # characters
872
+ consecutive_short_lines = 0
873
+ max_consecutive_short_lines = 3
874
+
875
+ for line in lines:
876
+ stripped_line = line.strip()
877
+ if len(stripped_line) < short_line_threshold and not stripped_line.startswith('#'):
878
+ consecutive_short_lines += 1
879
+ if consecutive_short_lines > max_consecutive_short_lines:
880
+ continue
881
+ else:
882
+ consecutive_short_lines = 0
883
+
884
+ filtered_lines.append(line)
885
+
886
+ content = '\n'.join(filtered_lines)
887
+
888
+ # Remove duplicate headers
889
+ seen_headers = set()
890
+ lines = content.split('\n')
891
+ filtered_lines = []
892
+
893
+ for line in lines:
894
+ if line.startswith('#'):
895
+ header_text = line.strip()
896
+ if header_text in seen_headers:
897
+ continue
898
+ seen_headers.add(header_text)
899
+ filtered_lines.append(line)
900
+
901
+ content = '\n'.join(filtered_lines)
902
+
903
+ # Remove lines containing common footer patterns
904
+ footer_patterns = [
905
+ r'^copyright', r'^©', r'^all rights reserved',
906
+ r'^terms', r'^privacy policy', r'^contact us',
907
+ r'^follow us', r'^social media', r'^disclaimer',
908
+ ]
909
+
910
+ footer_pattern = '|'.join(footer_patterns)
911
+ lines = content.split('\n')
912
+ filtered_lines = []
913
+
914
+ for line in lines:
915
+ if not re.search(footer_pattern, line.lower()):
916
+ filtered_lines.append(line)
917
+
918
+ content = '\n'.join(filtered_lines)
919
+
920
+ return content
921
+
922
+
923
+ class ArxivSearchTool(Tool):
924
+ name = "arxiv_search"
925
+ description = """Searches arXiv for academic papers and returns structured information including titles, authors, publication dates, abstracts, and download links."""
926
+
927
+
928
+ inputs = {
929
+ "query": {"type": "string", "description": "A research-related query (e.g., 'AI regulation')"},
930
+ "from_date":{"type": "string", "description": "Optional search start date in format (YYYY or YYYY-MM or YYYY-MM-DD) (e.g., '2022-06' or '2022' or '2022-04-12')", "nullable": True},
931
+ "to_date": {"type": "string", "description": "Optional search end date in (YYYY or YYYY-MM or YYYY-MM-DD) (e.g., '2022-06' or '2022' or '2022-04-12')", "nullable": True},
932
+ }
933
+
934
+ output_type = "string"
935
+
936
+ def forward(
937
+ self,
938
+ query: str,
939
+ from_date: str = None,
940
+ to_date: str = None,
941
+ ) -> str:
942
+ # 1) build URL
943
+ url = build_arxiv_url(query, from_date, to_date, size=50)
944
+
945
+ # 2) fetch & parse
946
+ try:
947
+ papers = fetch_and_parse_arxiv(url)
948
+ except Exception as e:
949
+ return f"❌ Failed to fetch or parse arXiv results: {e}"
950
+
951
+ if not papers:
952
+ return "No results found for your query."
953
+
954
+ # 3) format into a single string
955
+ output_lines = []
956
+ for idx, p in enumerate(papers, start=1):
957
+ output_lines += [
958
+ f"🔍 RESULT {idx}",
959
+ f"Title : {p['title']}",
960
+ f"Authors : {p['authors']}",
961
+ f"Published : {p['published']}",
962
+ f"Summary : {p['abstract'][:500]}{'...' if len(p['abstract'])>500 else ''}",
963
+ f"Entry ID : {p['entry_link']}",
964
+ f"Download link: {p['download_link']}",
965
+ ""
966
+ ]
967
+
968
+ return "\n".join(output_lines).strip()
969
+
970
+
971
+ import requests
972
+ from bs4 import BeautifulSoup
973
+ from typing import List, Dict
974
+
975
+ def fetch_and_parse_arxiv(url: str) -> List[Dict[str, str]]:
976
+ """
977
+ Fetches the given arXiv advanced‐search URL, parses the HTML,
978
+ and returns a list of results. Each result is a dict containing:
979
+ - title
980
+ - authors
981
+ - published
982
+ - abstract
983
+ - entry_link
984
+ - doi (or "[N/A]" if none)
985
+ """
986
+ resp = requests.get(url)
987
+ resp.raise_for_status()
988
+ soup = BeautifulSoup(resp.text, "html.parser")
989
+
990
+ results = []
991
+ for li in soup.find_all("li", class_="arxiv-result"):
992
+ # Title
993
+ t = li.find("p", class_="title")
994
+ title = t.get_text(strip=True) if t else ""
995
+
996
+ # Authors
997
+ a = li.find("p", class_="authors")
998
+ authors = a.get_text(strip=True).replace("Authors:", "").strip() if a else ""
999
+
1000
+ # Abstract
1001
+ ab = li.find("span", class_="abstract-full")
1002
+ abstract = ab.get_text(strip=True).replace("Abstract:", "").strip() if ab else ""
1003
+
1004
+ # Published date
1005
+ d = li.find("p", class_="is-size-7")
1006
+ published = d.get_text(strip=True) if d else ""
1007
+
1008
+ # Entry link
1009
+ lt = li.find("p", class_="list-title")
1010
+ entry_link = lt.find("a")["href"] if lt and lt.find("a") else ""
1011
+
1012
+ # DOI
1013
+ idblock = li.find("p", class_="list-identifier")
1014
+ if idblock:
1015
+ for a_tag in idblock.find_all("a", href=True):
1016
+ if "doi.org" in a_tag["href"]:
1017
+ doi = a_tag["href"]
1018
+ break
1019
+
1020
+ results.append({
1021
+ "title": title,
1022
+ "authors": authors,
1023
+ "published": published,
1024
+ "abstract": abstract,
1025
+ "entry_link": entry_link,
1026
+ "download_link": entry_link.replace("abs", "pdf") if "abs" in entry_link else "N/A"
1027
+ })
1028
+
1029
+ return results
1030
+
1031
+ from urllib.parse import quote_plus
1032
+
1033
+ def build_arxiv_url(
1034
+ query: str,
1035
+ from_date: str = None,
1036
+ to_date: str = None,
1037
+ size: int = 50
1038
+ ) -> str:
1039
+ """
1040
+ Build an arXiv advanced-search URL matching the exact segment order:
1041
+ 1) ?advanced
1042
+ 2) terms-0-operator=AND
1043
+ 3) terms-0-term=…
1044
+ 4) terms-0-field=all
1045
+ 5) classification-physics_archives=all
1046
+ 6) classification-include_cross_list=include
1047
+ [ optional date‐range block ]
1048
+ 7) abstracts=show
1049
+ 8) size=…
1050
+ 9) order=-announced_date_first
1051
+ If from_date or to_date is None, the date-range block is omitted.
1052
+ """
1053
+ base = "https://arxiv.org/search/advanced?advanced="
1054
+ parts = [
1055
+ "&terms-0-operator=AND",
1056
+ f"&terms-0-term={quote_plus(query)}",
1057
+ "&terms-0-field=all",
1058
+ "&classification-physics_archives=all",
1059
+ "&classification-include_cross_list=include",
1060
+ ]
1061
+
1062
+ # optional date-range filtering
1063
+ if from_date and to_date:
1064
+ parts += [
1065
+ "&date-year=",
1066
+ "&date-filter_by=date_range",
1067
+ f"&date-from_date={from_date}",
1068
+ f"&date-to_date={to_date}",
1069
+ "&date-date_type=submitted_date",
1070
+ ]
1071
+
1072
+ parts += [
1073
+ "&abstracts=show",
1074
+ f"&size={size}",
1075
+ "&order=-announced_date_first",
1076
+ ]
1077
+
1078
+ return base + "".join(parts)
tools_beta.py ADDED
@@ -0,0 +1,550 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import re
3
+ import tempfile
4
+ import mimetypes
5
+ import requests
6
+ import pandas as pd
7
+ import fitz # PyMuPDF
8
+ from urllib.parse import unquote
9
+ from smolagents import Tool
10
+ from smolagents import Tool
11
+ import requests
12
+ import traceback
13
+ from langchain_community.retrievers import BM25Retriever
14
+ from smolagents import Tool
15
+ import math
16
+
17
+ import subprocess
18
+ import sys
19
+ import os
20
+ import re
21
+
22
+
23
+
24
+ class DetectVisualElementsTool(Tool):
25
+ name = "detect_visual_elements"
26
+ description = """Detects objects, people, and common visual elements in an image using a pretrained object detection model."""
27
+
28
+ inputs = {
29
+ "image_path": {
30
+ "type": "string",
31
+ "description": "The full path to the image file to analyze."
32
+ }
33
+ }
34
+ output_type = "string"
35
+
36
+ def forward(self, image_path: str) -> list:
37
+ import os
38
+ from PIL import Image
39
+ import torch
40
+ import torchvision.transforms as T
41
+ import torchvision.models.detection as models
42
+
43
+ label_map = {
44
+ 0: "unlabeled",
45
+ 1: "person",
46
+ 2: "bicycle",
47
+ 3: "car",
48
+ 4: "motorcycle",
49
+ 5: "airplane",
50
+ 6: "bus",
51
+ 7: "train",
52
+ 8: "truck",
53
+ 9: "boat",
54
+ 10: "traffic",
55
+ 11: "fire",
56
+ 12: "street",
57
+ 13: "stop",
58
+ 14: "parking",
59
+ 15: "bench",
60
+ 16: "bird",
61
+ 17: "cat",
62
+ 18: "dog",
63
+ 19: "horse",
64
+ 20: "sheep",
65
+ 21: "cow",
66
+ 22: "elephant",
67
+ 23: "bear",
68
+ 24: "zebra",
69
+ 25: "giraffe",
70
+ 26: "hat",
71
+ 27: "backpack",
72
+ 28: "umbrella",
73
+ 29: "shoe",
74
+ 30: "eye",
75
+ 31: "handbag",
76
+ 32: "tie",
77
+ 33: "suitcase",
78
+ 34: "frisbee",
79
+ 35: "skis",
80
+ 36: "snowboard",
81
+ 37: "sports",
82
+ 38: "kite",
83
+ 39: "baseball",
84
+ 40: "baseball",
85
+ 41: "skateboard",
86
+ 42: "surfboard",
87
+ 43: "tennis",
88
+ 44: "bottle",
89
+ 45: "plate",
90
+ 46: "wine",
91
+ 47: "cup",
92
+ 48: "fork",
93
+ 49: "knife",
94
+ 50: "spoon",
95
+ 51: "bowl",
96
+ 52: "banana",
97
+ 53: "apple",
98
+ 54: "sandwich",
99
+ 55: "orange",
100
+ 56: "broccoli",
101
+ 57: "carrot",
102
+ 58: "hot",
103
+ 59: "pizza",
104
+ 60: "donut",
105
+ 61: "cake",
106
+ 62: "chair",
107
+ 63: "couch",
108
+ 64: "potted",
109
+ 65: "bed",
110
+ 66: "mirror",
111
+ 67: "dining",
112
+ 68: "window",
113
+ 69: "desk",
114
+ 70: "toilet",
115
+ 71: "door",
116
+ 72: "tv",
117
+ 73: "laptop",
118
+ 74: "mouse",
119
+ 75: "remote",
120
+ 76: "keyboard",
121
+ 77: "cell",
122
+ 78: "microwave",
123
+ 79: "oven",
124
+ 80: "toaster",
125
+ 81: "sink",
126
+ 82: "refrigerator",
127
+ 83: "blender",
128
+ 84: "book",
129
+ 85: "clock",
130
+ 86: "vase",
131
+ 87: "scissors",
132
+ 88: "teddy",
133
+ 89: "hair",
134
+ 90: "toothbrush",
135
+ 91: "hair",
136
+ 92: "banner",
137
+ 93: "blanket",
138
+ 94: "branch",
139
+ 95: "bridge",
140
+ 96: "building",
141
+ 97: "bush",
142
+ 98: "cabinet",
143
+ 99: "cage",
144
+ 100: "cardboard",
145
+ 101: "carpet",
146
+ 102: "ceiling",
147
+ 103: "ceiling",
148
+ 104: "cloth",
149
+ 105: "clothes",
150
+ 106: "clouds",
151
+ 107: "counter",
152
+ 108: "cupboard",
153
+ 109: "curtain",
154
+ 110: "desk",
155
+ 111: "dirt",
156
+ 112: "door",
157
+ 113: "fence",
158
+ 114: "floor",
159
+ 115: "floor",
160
+ 116: "floor",
161
+ 117: "floor",
162
+ 118: "floor",
163
+ 119: "flower",
164
+ 120: "fog",
165
+ 121: "food",
166
+ 122: "fruit",
167
+ 123: "furniture",
168
+ 124: "grass",
169
+ 125: "gravel",
170
+ 126: "ground",
171
+ 127: "hill",
172
+ 128: "house",
173
+ 129: "leaves",
174
+ 130: "light",
175
+ 131: "mat",
176
+ 132: "metal",
177
+ 133: "mirror",
178
+ 134: "moss",
179
+ 135: "mountain",
180
+ 136: "mud",
181
+ 137: "napkin",
182
+ 138: "net",
183
+ 139: "paper",
184
+ 140: "pavement",
185
+ 141: "pillow",
186
+ 142: "plant",
187
+ 143: "plastic",
188
+ 144: "platform",
189
+ 145: "playingfield",
190
+ 146: "railing",
191
+ 147: "railroad",
192
+ 148: "river",
193
+ 149: "road",
194
+ 150: "rock",
195
+ 151: "roof",
196
+ 152: "rug",
197
+ 153: "salad",
198
+ 154: "sand",
199
+ 155: "sea",
200
+ 156: "shelf",
201
+ 157: "sky",
202
+ 158: "skyscraper",
203
+ 159: "snow",
204
+ 160: "solid",
205
+ 161: "stairs",
206
+ 162: "stone",
207
+ 163: "straw",
208
+ 164: "structural",
209
+ 165: "table",
210
+ 166: "tent",
211
+ 167: "textile",
212
+ 168: "towel",
213
+ 169: "tree",
214
+ 170: "vegetable",
215
+ 171: "wall",
216
+ 172: "wall",
217
+ 173: "wall",
218
+ 174: "wall",
219
+ 175: "wall",
220
+ 176: "wall",
221
+ 177: "wall",
222
+ 178: "water",
223
+ 179: "waterdrops",
224
+ 180: "window",
225
+ 181: "window",
226
+ 182: "wood"
227
+ }
228
+
229
+
230
+ if not os.path.exists(image_path):
231
+ return [f"❌ Image file does not exist: {image_path}"]
232
+
233
+ try:
234
+ model = models.fasterrcnn_resnet50_fpn(pretrained=True)
235
+ model.eval()
236
+
237
+ image = Image.open(image_path).convert("RGB")
238
+ transform = T.Compose([T.ToTensor()])
239
+ img_tensor = transform(image).unsqueeze(0)
240
+
241
+ with torch.no_grad():
242
+ predictions = model(img_tensor)[0]
243
+
244
+ labels_list = []
245
+ for label_id, score in zip(predictions["labels"], predictions["scores"]):
246
+ if score > 0.8:
247
+ print(str(label_id.item()))
248
+ labels_list.append(label_map.get(label_id.item()))
249
+
250
+ labels = ",".join(labels_list)
251
+
252
+ return labels or ["⚠️ No confident visual elements detected."]
253
+ except Exception as e:
254
+ return [f"❌ Failed to detect visual elements: {e}"]
255
+
256
+
257
+ class ChessPositionSolverTool(Tool):
258
+ name = "chess_position_solver"
259
+ description = """Analyzes a chessboard image (from a URL or a local file path), detects the position using computer vision,
260
+ and returns the best move in algebraic notation using the Stockfish engine (e.g., 'Qh5#')."""
261
+
262
+ inputs = {
263
+ "url": {
264
+ "type": "string",
265
+ "description": "Optional. URL pointing to an image of a chessboard position.",
266
+ "nullable": True
267
+ },
268
+ "file_path": {
269
+ "type": "string",
270
+ "description": "Optional. Local file path to an image of a chessboard position.",
271
+ "nullable": True
272
+ }
273
+ }
274
+
275
+ output_type = "string"
276
+
277
+
278
+
279
+ def forward(self, url: str = None, file_path: str = None) -> str:
280
+ if not url and not file_path:
281
+ return "❌ Please provide either a URL or a local file path to the chessboard image."
282
+ if url and file_path:
283
+ return "❌ Provide only one of: 'url' or 'file_path', not both."
284
+
285
+ try:
286
+ # Step 1 - Load image
287
+ if url:
288
+ img_bytes = requests.get(url, timeout=30).content
289
+ img = cv2.imdecode(np.frombuffer(img_bytes, np.uint8), cv2.IMREAD_COLOR)
290
+ else:
291
+ if not os.path.exists(file_path):
292
+ return f"❌ File not found: {file_path}"
293
+ img = cv2.imread(file_path)
294
+
295
+ if img is None:
296
+ return "❌ Could not decode the image. Ensure the file is a valid chessboard image."
297
+
298
+ # Step 2 - Infer FEN with chesscog
299
+ detector = Chesscog(device="cpu")
300
+ fen = detector.get_fen(img)
301
+ if fen is None:
302
+ return "❌ Could not detect chessboard or recognize position."
303
+
304
+ board = chess.Board(fen)
305
+
306
+ STOCKFISH_PATH = os.getenv("STOCKFISH_PATH", "/home/boom/Desktop/repos/boombot/engines/stockfish-ubuntu-x86-64-bmi2") # Ensure Stockfish is available
307
+
308
+ # Step 3 - Analyze with Stockfish
309
+ engine = chess.engine.SimpleEngine.popen_uci(STOCKFISH_PATH)
310
+ result = engine.play(board, chess.engine.Limit(depth=18)) # fixed depth
311
+ engine.quit()
312
+
313
+ best_move = board.san(result.move)
314
+ return best_move
315
+
316
+ except Exception as e:
317
+ return f"❌ chess_position_solver failed: {str(e)}"
318
+
319
+
320
+ def patch_pyproject(path):
321
+ pyproject_path = os.path.join(path, "pyproject.toml")
322
+ if not os.path.exists(pyproject_path):
323
+ raise FileNotFoundError(f"No pyproject.toml found in {path}")
324
+
325
+ with open(pyproject_path, "r", encoding="utf-8") as f:
326
+ lines = f.readlines()
327
+
328
+ with open(pyproject_path, "w", encoding="utf-8") as f:
329
+ for line in lines:
330
+ if re.match(r'\s*python\s*=', line):
331
+ f.write('python = ">=3.8,<3.12"\n')
332
+ else:
333
+ f.write(line)
334
+
335
+ def install_chesscog():
336
+ TARGET_DIR = "chesscog"
337
+ REPO_URL = "https://github.com/georg-wolflein/chesscog.git"
338
+
339
+ try:
340
+ import chesscog
341
+ print("✅ chesscog already installed.")
342
+ # return
343
+ except ImportError:
344
+ print("⬇️ Installing chesscog...")
345
+
346
+ if not os.path.exists(TARGET_DIR):
347
+ subprocess.run(["git", "clone", REPO_URL, TARGET_DIR], check=True)
348
+
349
+ patch_pyproject(TARGET_DIR)
350
+
351
+ subprocess.run([sys.executable, "-m", "pip", "install", f"./{TARGET_DIR}"], check=True)
352
+ print("✅ chesscog installed successfully.")
353
+
354
+ class RetrieverTool(Tool):
355
+ name = "retriever"
356
+ description = "Retrieves the most similar known question to the query."
357
+ inputs = {
358
+ "query": {
359
+ "type": "string",
360
+ "description": "The query from the user (a question).",
361
+ }
362
+ }
363
+ output_type = "string"
364
+
365
+ def __init__(self, docs, **kwargs):
366
+ super().__init__(**kwargs)
367
+ self.retriever = BM25Retriever.from_documents(docs, k=1)
368
+
369
+ def forward(self, query: str) -> str:
370
+ docs = self.retriever.invoke(query)
371
+ if docs:
372
+ doc = docs[0]
373
+ return f"{doc.page_content}\n\nEXAMPLE FINAL ANSWER:\n{doc.metadata['answer']}\n"
374
+ else:
375
+ return "No similar question found."
376
+
377
+ class CalculatorTool(Tool):
378
+ name = "calculator"
379
+ description = """Performs basic mathematical calculations (e.g., addition, subtraction, multiplication, division, exponentiation, square root).
380
+ Use this tool whenever math is required, especially for numeric reasoning."""
381
+
382
+ inputs = {
383
+ "expression": {
384
+ "type": "string",
385
+ "description": "A basic math expression, e.g., '5 + 3 * 2', 'sqrt(49)', '2 ** 3'. No variables or natural language."
386
+ }
387
+ }
388
+ output_type = "string"
389
+
390
+ def forward(self, expression: str) -> str:
391
+ try:
392
+ allowed_names = {
393
+ k: v for k, v in math.__dict__.items()
394
+ if not k.startswith("__")
395
+ }
396
+ allowed_names.update({"abs": abs, "round": round})
397
+ result = eval(expression, {"__builtins__": {}}, allowed_names)
398
+ return str(result)
399
+ except Exception as e:
400
+ return f"Error: Invalid math expression. ({e})"
401
+
402
+ class AnalyzeChessImageTool(Tool):
403
+ name = "analyze_chess_image"
404
+ description = """Extracts the board state from a chessboard image and returns the best move for black (in algebraic notation)."""
405
+
406
+ inputs = {
407
+ "file_path": {
408
+ "type": "string",
409
+ "description": "Path to the image file of the chess board."
410
+ }
411
+ }
412
+ output_type = "string"
413
+
414
+ def forward(self, file_path: str) -> str:
415
+ try:
416
+ import chess
417
+ import chess.engine
418
+ import chessvision # hypothetical or use OpenCV + custom board parser
419
+
420
+ board = chessvision.image_to_board(file_path)
421
+ if not board or not board.turn == chess.BLACK:
422
+ return "❌ Invalid board or not black's turn."
423
+
424
+ engine = chess.engine.SimpleEngine.popen_uci("/usr/bin/stockfish")
425
+ result = engine.play(board, chess.engine.Limit(time=0.1))
426
+ move = result.move.uci()
427
+ engine.quit()
428
+
429
+ return move
430
+ except Exception as e:
431
+ return f"❌ Chess analysis failed: {e}"
432
+
433
+
434
+
435
+ class ExecutePythonCodeTool(Tool):
436
+ name = "execute_python_code"
437
+ description = """Executes a provided Python code snippet in a controlled, sandboxed environment.
438
+ This tool is used to safely run Python code and return the output or result of the execution."""
439
+
440
+ inputs = {
441
+ "code": {
442
+ "type": "string",
443
+ "description": "A valid Python code block that needs to be executed. It should be a string containing executable Python code."
444
+ }
445
+ }
446
+ output_type = "string"
447
+
448
+ def forward(self, code: str) -> str:
449
+ try:
450
+ # Create a restricted environment to execute the code safely
451
+ # Only allow standard Python libraries and prevent unsafe functions like `os.system` or `eval`
452
+ restricted_globals = {
453
+ "__builtins__": {
454
+ "abs": abs,
455
+ "all": all,
456
+ "any": any,
457
+ "bin": bin,
458
+ "bool": bool,
459
+ "chr": chr,
460
+ "complex": complex,
461
+ "dict": dict,
462
+ "divmod": divmod,
463
+ "float": float,
464
+ "hash": hash,
465
+ "hex": hex,
466
+ "int": int,
467
+ "isinstance": isinstance,
468
+ "len": len,
469
+ "max": max,
470
+ "min": min,
471
+ "oct": oct,
472
+ "pow": pow,
473
+ "range": range,
474
+ "round": round,
475
+ "set": set,
476
+ "sorted": sorted,
477
+ "str": str,
478
+ "tuple": tuple,
479
+ "zip": zip,
480
+ }
481
+ }
482
+
483
+ # Execute the code in the restricted environment
484
+ exec_locals = {}
485
+ exec(code, restricted_globals, exec_locals)
486
+
487
+ # If the code produces a result, we return that as output
488
+ if 'result' in exec_locals:
489
+ return str(exec_locals['result'])
490
+ else:
491
+ return "❌ The code did not produce a result."
492
+
493
+ except Exception as e:
494
+ return f"❌ Error executing code: {str(e)}"
495
+
496
+
497
+
498
+ class ArxivSearchTool(Tool):
499
+ name = "arxiv_search"
500
+ description = """Searches arXiv for academic papers and returns structured information including titles, authors, publication dates, and abstracts. Ideal for finding scientific research on specific topics."""
501
+
502
+ inputs = {
503
+ "query": {
504
+ "type": "string",
505
+ "description": "A research-related query string (e.g., 'Superstring Cosmology')"
506
+ }
507
+ }
508
+ output_type = "string"
509
+
510
+ def forward(self, query: str) -> str:
511
+ max_results = 10
512
+
513
+ try:
514
+ search_docs = ArxivLoader(
515
+ query=query,
516
+ load_max_docs=max_results,
517
+ load_all_available_meta=True
518
+ ).load()
519
+ except Exception as e:
520
+ return f"❌ Arxiv search failed: {e}"
521
+
522
+ if not search_docs:
523
+ return "No results found for your query."
524
+
525
+ output_lines = []
526
+ for idx, doc in enumerate(search_docs):
527
+ meta = getattr(doc, "metadata", {}) or {}
528
+ content = getattr(doc, "page_content", "").strip()
529
+
530
+ output_lines.append(f"🔍 RESULT {idx + 1}")
531
+ output_lines.append(f"Title : {meta.get('Title', '[No Title]')}")
532
+ output_lines.append(f"Authors : {meta.get('Authors', '[No Authors]')}")
533
+ output_lines.append(f"Published : {meta.get('Published', '[No Date]')}")
534
+ output_lines.append(f"Summary : {meta.get('Summary', '[No Summary]')}")
535
+ output_lines.append(f"Entry ID : {meta.get('entry_id', '[N/A]')}")
536
+ # output_lines.append(f"First Pub. : {meta.get('published_first_time', '[N/A]')}")
537
+ # output_lines.append(f"Comment : {meta.get('comment', '[N/A]')}")
538
+ output_lines.append(f"DOI : {meta.get('doi', '[N/A]')}")
539
+ # output_lines.append(f"Journal Ref : {meta.get('journal_ref', '[N/A]')}")
540
+ # output_lines.append(f"Primary Cat. : {meta.get('primary_category', '[N/A]')}")
541
+ # output_lines.append(f"Categories : {', '.join(meta.get('categories', [])) or '[N/A]'}")
542
+ output_lines.append(f"Links : {', '.join(meta.get('links', [])) or '[N/A]'}")
543
+
544
+ if content:
545
+ preview = content[:30] + ("..." if len(content) > 30 else "")
546
+ output_lines.append(f"Content : {preview}")
547
+
548
+ output_lines.append("") # spacing between results
549
+
550
+ return "\n".join(output_lines).strip()
utils.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+
3
+ def extract_final_answer(output: str) -> str:
4
+ """
5
+ Extracts the text after 'FINAL ANSWER:' in the model's output.
6
+ Strips whitespace and ensures clean formatting.
7
+ If the answer is a comma-separated list, ensures a space after each comma.
8
+ """
9
+ output = str(output)
10
+ marker = "FINAL ANSWER:"
11
+ lower_output = output.lower()
12
+
13
+ if marker.lower() in lower_output:
14
+ # Find actual case version in original output (for safety)
15
+ idx = lower_output.rfind(marker.lower())
16
+ raw_answer = output[idx + len(marker):].strip()
17
+
18
+ # Normalize comma-separated lists: ensure single space after commas
19
+ cleaned_answer = re.sub(r',\s*', ', ', raw_answer)
20
+ return cleaned_answer
21
+
22
+ return output
23
+
24
+
25
+ def replace_tool_mentions(prompt: str) -> str:
26
+ # Replace tool mentions in backticks: `search` -> `web_search`, `wiki` -> `wikipedia_search`
27
+ prompt = re.sub(r'(?<!\w)`search`(?!\w)', '`web_search`', prompt)
28
+ prompt = re.sub(r'(?<!\w)`wiki`(?!\w)', '`wikipedia_search`', prompt)
29
+
30
+ # Replace function calls: search(...) -> web_search(...), wiki(...) -> wikipedia_search(...)
31
+ # This ensures we only catch function calls (not words like arxiv_search)
32
+ prompt = re.sub(r'(?<!\w)(?<!_)search\(', 'web_search(', prompt)
33
+ prompt = re.sub(r'(?<!\w)(?<!_)wiki\(', 'wikipedia_search(', prompt)
34
+
35
+ return prompt