File size: 1,300 Bytes
22f5301 598ce65 22f5301 598ce65 22f5301 598ce65 22f5301 598ce65 | 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 | from smolagents.tools import Tool
class Calculator(Tool):
name = "calculator"
description = (
"Performs deterministic arithmetic calculations. "
"Use this when a research task requires numerical computation."
)
inputs = {
"expression": {
"type": "string",
"description": (
"A mathematical expression to evaluate, "
"for example '125 * 0.18' or '(450 - 300) / 300 * 100'."
),
}
}
output_type = "number"
def forward(self, expression: str) -> float:
try:
# Restrict evaluation to arithmetic only.
allowed = set("0123456789+-*/().% ")
if not expression or any(char not in allowed for char in expression):
raise ValueError("Expression contains unsupported characters.")
expression = expression.replace("%", "/100")
result = eval(expression, {"__builtins__": {}}, {})
if not isinstance(result, (int, float)):
raise ValueError("Expression did not produce a number.")
return float(result)
except Exception as e:
raise ValueError(
f"Could not evaluate expression '{expression}': {e}"
) from e
|