Spaces:
Runtime error
Runtime error
Update tools/calculator.py
Browse files- tools/calculator.py +10 -6
tools/calculator.py
CHANGED
|
@@ -1,7 +1,7 @@
|
|
| 1 |
# tools/calculator.py
|
| 2 |
import ast, operator as op
|
|
|
|
| 3 |
|
| 4 |
-
# Allowed operators
|
| 5 |
_ops = {
|
| 6 |
ast.Add: op.add, ast.Sub: op.sub, ast.Mult: op.mul,
|
| 7 |
ast.Div: op.truediv, ast.Pow: op.pow, ast.Mod: op.mod,
|
|
@@ -9,17 +9,21 @@ _ops = {
|
|
| 9 |
}
|
| 10 |
|
| 11 |
def _safe_eval(node):
|
| 12 |
-
if isinstance(node, ast.Expression):
|
| 13 |
return _safe_eval(node.body)
|
| 14 |
-
if isinstance(node, ast.Constant):
|
| 15 |
return node.value
|
| 16 |
-
if isinstance(node, ast.BinOp):
|
| 17 |
return _ops[type(node.op)](_safe_eval(node.left), _safe_eval(node.right))
|
| 18 |
-
if isinstance(node, ast.UnaryOp):
|
| 19 |
return _ops[type(node.op)](_safe_eval(node.operand))
|
| 20 |
raise ValueError("Unsupported expression")
|
| 21 |
|
|
|
|
| 22 |
def calculator(expression: str) -> str:
|
| 23 |
-
"""
|
|
|
|
|
|
|
|
|
|
| 24 |
tree = ast.parse(expression, mode="eval")
|
| 25 |
return str(_safe_eval(tree))
|
|
|
|
| 1 |
# tools/calculator.py
|
| 2 |
import ast, operator as op
|
| 3 |
+
from smolagents import tool
|
| 4 |
|
|
|
|
| 5 |
_ops = {
|
| 6 |
ast.Add: op.add, ast.Sub: op.sub, ast.Mult: op.mul,
|
| 7 |
ast.Div: op.truediv, ast.Pow: op.pow, ast.Mod: op.mod,
|
|
|
|
| 9 |
}
|
| 10 |
|
| 11 |
def _safe_eval(node):
|
| 12 |
+
if isinstance(node, ast.Expression):
|
| 13 |
return _safe_eval(node.body)
|
| 14 |
+
if isinstance(node, ast.Constant):
|
| 15 |
return node.value
|
| 16 |
+
if isinstance(node, ast.BinOp):
|
| 17 |
return _ops[type(node.op)](_safe_eval(node.left), _safe_eval(node.right))
|
| 18 |
+
if isinstance(node, ast.UnaryOp):
|
| 19 |
return _ops[type(node.op)](_safe_eval(node.operand))
|
| 20 |
raise ValueError("Unsupported expression")
|
| 21 |
|
| 22 |
+
@tool
|
| 23 |
def calculator(expression: str) -> str:
|
| 24 |
+
"""Evaluate a simple arithmetic expression safely.
|
| 25 |
+
Args:
|
| 26 |
+
expression: The math expression to evaluate.
|
| 27 |
+
"""
|
| 28 |
tree = ast.parse(expression, mode="eval")
|
| 29 |
return str(_safe_eval(tree))
|