Download tools/calculator.py from Realistvik0/First_agent_template: direct link, hf CLI and curl.
- Browser
- Download file 1.3 kB
-
https://huggingface.co/spaces/Realistvik0/First_agent_template/resolve/main/tools/calculator.py
- Command line
-
hf download hf://spaces/Realistvik0/First_agent_template/tools/calculator.py
-
curl -L -o calculator.py https://huggingface.co/spaces/Realistvik0/First_agent_template/resolve/main/tools/calculator.py
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 | |