Realistvik0 commited on
Commit
22f5301
·
verified ·
1 Parent(s): 389b23b

Update tools/calculator.py

Browse files
Files changed (1) hide show
  1. tools/calculator.py +39 -6
tools/calculator.py CHANGED
@@ -1,12 +1,45 @@
1
- from smolagents.tools import Tools
2
- from typing import Any, Optional
3
- import duckduckgo_search
4
 
5
  class Calculator(Tool):
6
  name = "calculator"
7
- description = "takes numbers and performs some arithmetic eg addition, subtraction"
 
 
 
 
 
8
  inputs = {
9
- numbers: {float}
 
 
 
 
 
 
10
  }
11
- output_type = float
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
 
 
1
+ from smolagents.tools import Tool
2
+
 
3
 
4
  class Calculator(Tool):
5
  name = "calculator"
6
+
7
+ description = (
8
+ "Performs deterministic arithmetic calculations. "
9
+ "Use this when a research task requires numerical computation."
10
+ )
11
+
12
  inputs = {
13
+ "expression": {
14
+ "type": "string",
15
+ "description": (
16
+ "A mathematical expression to evaluate, "
17
+ "for example '125 * 0.18' or '(450 - 300) / 300 * 100'."
18
+ ),
19
+ }
20
  }
21
+
22
+ output_type = "number"
23
+
24
+ def forward(self, expression: str) -> float:
25
+ try:
26
+ # Restrict evaluation to arithmetic only.
27
+ allowed = set("0123456789+-*/().% ")
28
+
29
+ if not expression or any(char not in allowed for char in expression):
30
+ raise ValueError("Expression contains unsupported characters.")
31
+
32
+ expression = expression.replace("%", "/100")
33
+
34
+ result = eval(expression, {"__builtins__": {}}, {})
35
+
36
+ if not isinstance(result, (int, float)):
37
+ raise ValueError("Expression did not produce a number.")
38
+
39
+ return float(result)
40
+
41
+ except Exception as e:
42
+ raise ValueError(
43
+ f"Could not evaluate expression '{expression}': {e}"
44
+ ) from e
45