First_agent_template / tools /calculator.py
Realistvik0's picture
Update tools/calculator.py
22f5301 verified
Raw History Blame Contribute Delete
1.3 kB
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