Spaces:
Sleeping
Sleeping
mchinea
commited on
Commit
·
5ef9706
1
Parent(s):
1659627
add tools
Browse files- requirements.txt +1 -1
- tools.py +145 -5
requirements.txt
CHANGED
|
@@ -11,4 +11,4 @@ pandas
|
|
| 11 |
Pillow
|
| 12 |
pydub
|
| 13 |
tavily-python
|
| 14 |
-
wikipedia
|
|
|
|
| 11 |
Pillow
|
| 12 |
pydub
|
| 13 |
tavily-python
|
| 14 |
+
wikipedia
|
tools.py
CHANGED
|
@@ -1,8 +1,13 @@
|
|
| 1 |
import os
|
| 2 |
import random
|
|
|
|
|
|
|
|
|
|
| 3 |
|
| 4 |
from typing import Dict
|
| 5 |
from pathlib import Path
|
|
|
|
|
|
|
| 6 |
|
| 7 |
from langchain_core.tools import tool
|
| 8 |
|
|
@@ -138,14 +143,53 @@ def convert_units(value: float, from_unit: str, to_unit: str) -> float:
|
|
| 138 |
|
| 139 |
return conversions[key](value)
|
| 140 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 141 |
@tool
|
| 142 |
-
def query_table_data(file_path: str,
|
| 143 |
"""
|
| 144 |
Loads a table from CSV or Excel and filters it using a pandas query.
|
| 145 |
|
| 146 |
Args:
|
| 147 |
file_path: Path to the table file (.xlsx, .xls).
|
| 148 |
-
|
| 149 |
sheet_name: Optional sheet name if the file is Excel.
|
| 150 |
|
| 151 |
Returns:
|
|
@@ -164,10 +208,10 @@ def query_table_data(file_path: str, query: str, sheet_name: str = None) -> str:
|
|
| 164 |
else:
|
| 165 |
raise ValueError(f"Unsupported file extension: {ext}")
|
| 166 |
try:
|
| 167 |
-
filtered_df = df.query(
|
| 168 |
return filtered_df.head(10).to_markdown(index=False)
|
| 169 |
except Exception as e:
|
| 170 |
-
raise ValueError(f"Invalid query: {
|
| 171 |
except ImportError:
|
| 172 |
return "Error: pandas and openpyxl are not installed. Please install them with 'pip install pandas openpyxl'."
|
| 173 |
|
|
@@ -189,6 +233,98 @@ def arvix_search(query: str) -> str:
|
|
| 189 |
return {"arvix_results": formatted_search_docs}
|
| 190 |
|
| 191 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 192 |
level1_tools = [
|
| 193 |
multiply,
|
| 194 |
add,
|
|
@@ -199,5 +335,9 @@ level1_tools = [
|
|
| 199 |
web_search,
|
| 200 |
arvix_search,
|
| 201 |
convert_units,
|
| 202 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 203 |
]
|
|
|
|
| 1 |
import os
|
| 2 |
import random
|
| 3 |
+
import requests
|
| 4 |
+
import tempfile
|
| 5 |
+
import re
|
| 6 |
|
| 7 |
from typing import Dict
|
| 8 |
from pathlib import Path
|
| 9 |
+
from markitdown import MarkItDown
|
| 10 |
+
from urllib.parse import urlparse
|
| 11 |
|
| 12 |
from langchain_core.tools import tool
|
| 13 |
|
|
|
|
| 143 |
|
| 144 |
return conversions[key](value)
|
| 145 |
|
| 146 |
+
|
| 147 |
+
def convert_query_to_pandas_syntax(natural_query: str, column_names: list) -> str:
|
| 148 |
+
"""
|
| 149 |
+
Converts a natural language query to pandas query syntax using basic heuristics.
|
| 150 |
+
|
| 151 |
+
Args:
|
| 152 |
+
natural_query: A string with a question or filter expression in plain English.
|
| 153 |
+
column_names: List of column names from the DataFrame.
|
| 154 |
+
|
| 155 |
+
Returns:
|
| 156 |
+
A best-effort string in pandas query() format.
|
| 157 |
+
"""
|
| 158 |
+
# Preprocess query
|
| 159 |
+
query = natural_query.lower().strip()
|
| 160 |
+
|
| 161 |
+
# Heuristic rules
|
| 162 |
+
rules = [
|
| 163 |
+
(r"(\w+) greater than (\d+)", r"\1 > \2"),
|
| 164 |
+
(r"(\w+) less than (\d+)", r"\1 < \2"),
|
| 165 |
+
(r"(\w+) equal to ['\"]?([\w\s]+)['\"]?", r"\1 == '\2'"),
|
| 166 |
+
(r"(\w+) not equal to ['\"]?([\w\s]+)['\"]?", r"\1 != '\2'"),
|
| 167 |
+
(r"(\w+) more than (\d+)", r"\1 > \2"),
|
| 168 |
+
(r"(\w+) less than or equal to (\d+)", r"\1 <= \2"),
|
| 169 |
+
(r"(\w+) greater than or equal to (\d+)", r"\1 >= \2"),
|
| 170 |
+
(r"(\w+) is ['\"]?([\w\s]+)['\"]?", r"\1 == '\2'"),
|
| 171 |
+
]
|
| 172 |
+
|
| 173 |
+
for pattern, replacement in rules:
|
| 174 |
+
if re.search(pattern, query):
|
| 175 |
+
query = re.sub(pattern, replacement, query)
|
| 176 |
+
break
|
| 177 |
+
|
| 178 |
+
# Handle AND/OR logic
|
| 179 |
+
query = query.replace(" and ", " and ")
|
| 180 |
+
query = query.replace(" or ", " or ")
|
| 181 |
+
|
| 182 |
+
return query
|
| 183 |
+
|
| 184 |
+
|
| 185 |
@tool
|
| 186 |
+
def query_table_data(file_path: str, query_pandas_syntax: str, sheet_name: str = None) -> str:
|
| 187 |
"""
|
| 188 |
Loads a table from CSV or Excel and filters it using a pandas query.
|
| 189 |
|
| 190 |
Args:
|
| 191 |
file_path: Path to the table file (.xlsx, .xls).
|
| 192 |
+
query_pandas_syntax: A pandas-compatible query string, e.g., "Age > 30 and Country == 'USA'".
|
| 193 |
sheet_name: Optional sheet name if the file is Excel.
|
| 194 |
|
| 195 |
Returns:
|
|
|
|
| 208 |
else:
|
| 209 |
raise ValueError(f"Unsupported file extension: {ext}")
|
| 210 |
try:
|
| 211 |
+
filtered_df = df.query(query_pandas_syntax)
|
| 212 |
return filtered_df.head(10).to_markdown(index=False)
|
| 213 |
except Exception as e:
|
| 214 |
+
raise ValueError(f"Invalid query: {query_pandas_syntax}. Error: {e}")
|
| 215 |
except ImportError:
|
| 216 |
return "Error: pandas and openpyxl are not installed. Please install them with 'pip install pandas openpyxl'."
|
| 217 |
|
|
|
|
| 233 |
return {"arvix_results": formatted_search_docs}
|
| 234 |
|
| 235 |
|
| 236 |
+
@tool
|
| 237 |
+
def read_python_file(file_path: str) -> str:
|
| 238 |
+
"""
|
| 239 |
+
Reads and parses an Python file to markdown.
|
| 240 |
+
Args:
|
| 241 |
+
file_path: Path to the Python file
|
| 242 |
+
Returns:
|
| 243 |
+
Python file content.
|
| 244 |
+
"""
|
| 245 |
+
|
| 246 |
+
try:
|
| 247 |
+
# Just with markitdown
|
| 248 |
+
path = Path(file_path)
|
| 249 |
+
if not path.exists():
|
| 250 |
+
raise FileNotFoundError(f"File not found: {file_path}")
|
| 251 |
+
ext = path.suffix.lower()
|
| 252 |
+
if ext == ".py":
|
| 253 |
+
md = MarkItDown(enable_plugins=True)
|
| 254 |
+
result = md.convert(file_path)
|
| 255 |
+
return result.text_content
|
| 256 |
+
else:
|
| 257 |
+
raise ValueError(f"Unsupported file extension: {ext}")
|
| 258 |
+
except Exception as err:
|
| 259 |
+
raise type(err)(f"Could not parse python file > {err}")
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
@tool
|
| 263 |
+
def save_and_read_file(content: str, filename: str = None) -> str:
|
| 264 |
+
"""
|
| 265 |
+
Save content to a temporary file and return the path.
|
| 266 |
+
Useful for processing files from the GAIA API.
|
| 267 |
+
|
| 268 |
+
Args:
|
| 269 |
+
content: The content to save to the file
|
| 270 |
+
filename: Optional filename, will generate a random name if not provided
|
| 271 |
+
|
| 272 |
+
Returns:
|
| 273 |
+
Path to the saved file
|
| 274 |
+
"""
|
| 275 |
+
temp_dir = tempfile.gettempdir()
|
| 276 |
+
if filename is None:
|
| 277 |
+
temp_file = tempfile.NamedTemporaryFile(delete=False)
|
| 278 |
+
filepath = temp_file.name
|
| 279 |
+
else:
|
| 280 |
+
filepath = os.path.join(temp_dir, filename)
|
| 281 |
+
|
| 282 |
+
# Write content to the file
|
| 283 |
+
with open(filepath, 'w') as f:
|
| 284 |
+
f.write(content)
|
| 285 |
+
|
| 286 |
+
return f"File saved to {filepath}. You can read this file to process its contents."
|
| 287 |
+
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
def download_file_from_url(url: str, filename: str) -> str:
|
| 291 |
+
"""
|
| 292 |
+
Download a file from a URL and save it to a temporary location.
|
| 293 |
+
Args:
|
| 294 |
+
url: The URL to download from
|
| 295 |
+
filename: filename
|
| 296 |
+
Returns:
|
| 297 |
+
Path to the downloaded file
|
| 298 |
+
"""
|
| 299 |
+
try:
|
| 300 |
+
# Parse URL to get filename if not provided
|
| 301 |
+
if not filename:
|
| 302 |
+
path = urlparse(url).path
|
| 303 |
+
filename = os.path.basename(path)
|
| 304 |
+
if not filename:
|
| 305 |
+
# Generate a random name if we couldn't extract one
|
| 306 |
+
import uuid
|
| 307 |
+
|
| 308 |
+
filename = f"downloaded_{uuid.uuid4().hex[:8]}"
|
| 309 |
+
|
| 310 |
+
# Create temporary file
|
| 311 |
+
temp_dir = tempfile.gettempdir()
|
| 312 |
+
filepath = os.path.join(temp_dir, filename)
|
| 313 |
+
|
| 314 |
+
# Download the file
|
| 315 |
+
response = requests.get(url, stream=True)
|
| 316 |
+
response.raise_for_status()
|
| 317 |
+
|
| 318 |
+
# Save the file
|
| 319 |
+
with open(filepath, "wb") as f:
|
| 320 |
+
for chunk in response.iter_content(chunk_size=8192):
|
| 321 |
+
f.write(chunk)
|
| 322 |
+
|
| 323 |
+
return f"File downloaded to {filepath}. You can now process this file."
|
| 324 |
+
except Exception as e:
|
| 325 |
+
return f"Error downloading file: {str(e)}"
|
| 326 |
+
|
| 327 |
+
|
| 328 |
level1_tools = [
|
| 329 |
multiply,
|
| 330 |
add,
|
|
|
|
| 335 |
web_search,
|
| 336 |
arvix_search,
|
| 337 |
convert_units,
|
| 338 |
+
convert_query_to_pandas_syntax,
|
| 339 |
+
query_table_data,
|
| 340 |
+
download_file_from_url,
|
| 341 |
+
save_and_read_file,
|
| 342 |
+
read_python_file
|
| 343 |
]
|