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