-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtools.py
More file actions
261 lines (224 loc) · 10.1 KB
/
Copy pathtools.py
File metadata and controls
261 lines (224 loc) · 10.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
"""
tools.py — All tool definitions for the Multi-Tool Agent.
Tools: web_search, calculator, file_reader
"""
import json
import math
import re
import os
from io import BytesIO
import requests
# ─────────────────────────────────────────────
# 1. WEB SEARCH
# ─────────────────────────────────────────────
def web_search(query: str, max_results: int = 5) -> str:
"""Search the web using Google (via SerpAPI) and return summarised results."""
# 1. Grab the API key from your environment
api_key = os.getenv("SERPAPI_KEY")
if not api_key or api_key == "your_serpapi_key_here":
return "Error: SERPAPI_KEY is not set. Please add it to your .env file."
# 2. Set up the API request parameters
params = {
"engine": "google",
"q": query,
"api_key": api_key,
"num": max_results
}
try:
# 3. Make the request to SerpAPI
response = requests.get("https://serpapi.com/search", params=params, timeout=15)
response.raise_for_status() # Raises an error for bad HTTP status codes
data = response.json()
organic_results = data.get("organic_results", [])
if not organic_results:
return "No results found for the query."
# 4. Format the JSON data into a clean string for the LLM
output = []
for i, r in enumerate(organic_results[:max_results], 1):
title = r.get("title", "No title")
url = r.get("link", "")
snippet = r.get("snippet", "No snippet")
output.append(f"[{i}] {title}\n URL: {url}\n {snippet}")
return "\n\n".join(output)
except requests.exceptions.RequestException as e:
return f"Web search network error: {str(e)}"
except Exception as e:
return f"Web search processing error: {str(e)}"
# ─────────────────────────────────────────────
# 2. CALCULATOR
# ─────────────────────────────────────────────
def calculator(expression: str) -> str:
"""
Safely evaluate a mathematical expression.
Supports: +, -, *, /, **, sqrt, sin, cos, tan, log, pi, e, abs, round, etc.
"""
try:
# Allow only safe characters
safe_chars = re.compile(r'^[\d\s\+\-\*\/\(\)\.\,\%\^a-zA-Z\_]+$')
if not safe_chars.match(expression):
return "Error: Expression contains invalid characters."
# Build a safe namespace
safe_ns = {
"abs": abs, "round": round,
"sqrt": math.sqrt, "log": math.log, "log10": math.log10,
"log2": math.log2, "exp": math.exp,
"sin": math.sin, "cos": math.cos, "tan": math.tan,
"asin": math.asin, "acos": math.acos, "atan": math.atan,
"pi": math.pi, "e": math.e, "inf": math.inf,
"ceil": math.ceil, "floor": math.floor,
"factorial": math.factorial, "gcd": math.gcd,
"pow": pow,
}
# Replace ^ with ** for user convenience
expression = expression.replace("^", "**")
result = eval(expression, {"__builtins__": {}}, safe_ns) # noqa: S307
return f"Result: {result}"
except ZeroDivisionError:
return "Error: Division by zero."
except Exception as e:
return f"Calculator error: {str(e)}"
# ─────────────────────────────────────────────
# 3. FILE READER
# ─────────────────────────────────────────────
def file_reader(file_path: str) -> str:
"""
Read a local file and return its contents as text.
Supports: .txt, .md, .py, .js, .json, .csv, .pdf, .docx
"""
if not os.path.exists(file_path):
return f"Error: File not found at path '{file_path}'."
ext = os.path.splitext(file_path)[1].lower()
try:
# ── Plain text-based files ──────────────────────
if ext in {".txt", ".md", ".py", ".js", ".ts", ".html", ".css",
".json", ".yaml", ".yml", ".env", ".sh", ".bat"}:
with open(file_path, "r", encoding="utf-8", errors="replace") as f:
content = f.read()
if len(content) > 8000:
content = content[:8000] + "\n\n[... file truncated at 8000 chars ...]"
return content
# ── CSV ─────────────────────────────────────────
elif ext == ".csv":
with open(file_path, "r", encoding="utf-8", errors="replace") as f:
lines = f.readlines()
preview = "".join(lines[:50])
note = f"\n\n[Showing first 50 rows of {len(lines)} total rows]" if len(lines) > 50 else ""
return preview + note
# ── PDF ─────────────────────────────────────────
elif ext == ".pdf":
try:
import PyPDF2
with open(file_path, "rb") as f:
reader = PyPDF2.PdfReader(f)
pages = [reader.pages[i].extract_text() for i in range(min(10, len(reader.pages)))]
text = "\n\n".join(filter(None, pages))
if len(text) > 8000:
text = text[:8000] + "\n\n[... truncated ...]"
return text or "PDF appears to contain no extractable text."
except ImportError:
return "PyPDF2 not installed. Run: pip install PyPDF2"
# ── DOCX ────────────────────────────────────────
elif ext == ".docx":
try:
from docx import Document
doc = Document(file_path)
paragraphs = [p.text for p in doc.paragraphs if p.text.strip()]
text = "\n\n".join(paragraphs)
if len(text) > 8000:
text = text[:8000] + "\n\n[... truncated ...]"
return text or "DOCX file appears empty."
except ImportError:
return "python-docx not installed. Run: pip install python-docx"
else:
return f"Unsupported file type '{ext}'. Supported: .txt, .md, .py, .js, .json, .csv, .pdf, .docx"
except Exception as e:
return f"File reader error: {str(e)}"
# ─────────────────────────────────────────────
# TOOL REGISTRY — used by the agent
# ─────────────────────────────────────────────
TOOL_DEFINITIONS = [
{
"type": "function",
"function": {
"name": "web_search",
"description": (
"Search the internet for current information, news, facts, or any topic. "
"Use when the user asks about recent events, factual questions, or anything "
"that requires up-to-date data from the web."
),
"parameters": {
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "The search query to look up on the web."
}
# NOTICE: max_results has been completely deleted from here!
},
"required": ["query"]
}
}
},
{
"type": "function",
"function": {
"name": "calculator",
"description": (
"Evaluate mathematical expressions and perform calculations. "
"Supports arithmetic, algebra, trigonometry, logarithms, and more. "
"Use for any math problem."
),
"parameters": {
"type": "object",
"properties": {
"expression": {
"type": "string",
"description": (
"A valid mathematical expression to evaluate. "
"Examples: '2 + 2', 'sqrt(144)', 'sin(pi/2)', '(3**2 + 4**2)**0.5'"
)
}
},
"required": ["expression"]
}
}
},
{
"type": "function",
"function": {
"name": "file_reader",
"description": (
"Read and return the contents of a local file. "
"Supports text, Python, JSON, CSV, PDF, and DOCX files. "
"Use when the user wants to analyze, summarize, or ask questions about a local file."
),
"parameters": {
"type": "object",
"properties": {
"file_path": {
"type": "string",
"description": (
"The absolute or relative path to the file. "
"Example: './data/report.pdf' or 'C:/Users/John/notes.txt'"
)
}
},
"required": ["file_path"]
}
}
}
]
TOOL_FUNCTION_MAP = {
"web_search": web_search,
"calculator": calculator,
"file_reader": file_reader,
}
def execute_tool(tool_name: str, tool_args: dict) -> str:
"""Dispatch a tool call and return its string result."""
fn = TOOL_FUNCTION_MAP.get(tool_name)
if fn is None:
return f"Error: Unknown tool '{tool_name}'."
try:
return fn(**tool_args)
except TypeError as e:
return f"Tool argument error for '{tool_name}': {str(e)}"