Models work numbers out in their heads and get multi-digit products and powers wrong (qwen3:8b: 3847 x 2963 as 11,378,261; in the reply loop it searched the web for it and gave no answer). The calculator evaluates a whitelisted ast (numbers, operators, a few math functions, pi/e), never code, with a 200 character cap and a power size limit so nothing hangs. Idea from OpenJarvis's calculator tool (Apache 2.0). Eval (qwen3:8b, v2 setup): 0/2 before, 12/12 over four runs after; the unrelated question never calls it. Router evals unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
147 lines
5.8 KiB
Python
147 lines
5.8 KiB
Python
"""calculator tool: exact arithmetic for the reply model (calculator.spec.md).
|
||
|
||
The expression is parsed with ``ast`` and only numbers, + - * / // % **, a few math functions and
|
||
pi/e are evaluated; anything else is refused, never run as code.
|
||
"""
|
||
|
||
import ast
|
||
import math
|
||
import operator
|
||
from typing import Any, Dict, Optional
|
||
|
||
from ...debug import debug_log
|
||
from ..base import Tool, ToolContext
|
||
from ..types import ToolExecutionResult
|
||
|
||
MAX_EXPRESSION_CHARS = 200
|
||
# Largest whole-number power worked out exactly (about 3000 digits); bigger ones are refused.
|
||
_MAX_POWER_BITS = 10_000
|
||
|
||
_BINARY = {
|
||
ast.Add: operator.add, ast.Sub: operator.sub, ast.Mult: operator.mul,
|
||
ast.Div: operator.truediv, ast.FloorDiv: operator.floordiv, ast.Mod: operator.mod,
|
||
}
|
||
_UNARY = {ast.UAdd: operator.pos, ast.USub: operator.neg}
|
||
_FUNCTIONS = {
|
||
"abs": abs, "round": round, "min": min, "max": max, "sqrt": math.sqrt, "exp": math.exp,
|
||
"log": math.log, "ln": math.log, "log10": math.log10, "log2": math.log2,
|
||
"sin": math.sin, "cos": math.cos, "tan": math.tan, "ceil": math.ceil, "floor": math.floor,
|
||
}
|
||
_CONSTANTS = {"pi": math.pi, "e": math.e}
|
||
# Signs people and models write for the same operations.
|
||
_SIGNS = {"^": "**", "×": "*", "÷": "/", "−": "-"}
|
||
|
||
|
||
class _Refused(ValueError):
|
||
pass
|
||
|
||
|
||
def _power(base, exponent):
|
||
if isinstance(base, int) and isinstance(exponent, int) and exponent >= 0:
|
||
if abs(base) > 1 and abs(base).bit_length() * exponent > _MAX_POWER_BITS:
|
||
raise _Refused("the result is too large")
|
||
return base ** exponent
|
||
result = float(base) ** float(exponent)
|
||
if isinstance(result, complex):
|
||
raise _Refused("the result is not a real number")
|
||
return result
|
||
|
||
|
||
def _eval(node):
|
||
if isinstance(node, ast.Constant) and type(node.value) in (int, float):
|
||
return node.value
|
||
if isinstance(node, ast.BinOp) and isinstance(node.op, ast.Pow):
|
||
return _power(_eval(node.left), _eval(node.right))
|
||
if isinstance(node, ast.BinOp) and type(node.op) in _BINARY:
|
||
return _BINARY[type(node.op)](_eval(node.left), _eval(node.right))
|
||
if isinstance(node, ast.UnaryOp) and type(node.op) in _UNARY:
|
||
return _UNARY[type(node.op)](_eval(node.operand))
|
||
if isinstance(node, ast.Name) and node.id in _CONSTANTS:
|
||
return _CONSTANTS[node.id]
|
||
if (isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id in _FUNCTIONS
|
||
and not node.keywords):
|
||
return _FUNCTIONS[node.func.id](*[_eval(a) for a in node.args])
|
||
raise _Refused("only numbers, + - * / ^ %, parentheses, "
|
||
+ ", ".join([*_FUNCTIONS, *_CONSTANTS]) + " are allowed")
|
||
|
||
|
||
def _readable(value) -> str:
|
||
if isinstance(value, int):
|
||
try:
|
||
return str(value)
|
||
except ValueError: # more digits than Python turns into text
|
||
raise _Refused("the result is too large")
|
||
if not math.isfinite(value):
|
||
raise _Refused("the result is not a finite number")
|
||
if value.is_integer() and abs(value) < 1e15:
|
||
return str(int(value))
|
||
return f"{value:.10g}"
|
||
|
||
|
||
def calculate(expression: str) -> str:
|
||
"""The value of ``expression`` as text; raises ValueError with a reason the model can act on."""
|
||
text = (expression or "").strip()
|
||
if not text:
|
||
raise _Refused("no expression was given")
|
||
if len(text) > MAX_EXPRESSION_CHARS:
|
||
raise _Refused(f"the expression is longer than {MAX_EXPRESSION_CHARS} characters")
|
||
for sign, python in _SIGNS.items():
|
||
text = text.replace(sign, python)
|
||
try:
|
||
tree = ast.parse(text, mode="eval")
|
||
except (SyntaxError, ValueError, RecursionError, MemoryError):
|
||
raise _Refused("the expression is not valid math")
|
||
try:
|
||
return _readable(_eval(tree.body))
|
||
except ZeroDivisionError:
|
||
raise _Refused("it divides by zero")
|
||
except OverflowError:
|
||
raise _Refused("the result is too large")
|
||
except (TypeError, RecursionError):
|
||
raise _Refused("a function got the wrong number of values")
|
||
except _Refused:
|
||
raise
|
||
except ValueError:
|
||
raise _Refused("a function got a value outside its range")
|
||
|
||
|
||
class CalculatorTool(Tool):
|
||
@property
|
||
def name(self) -> str:
|
||
return "calculator"
|
||
|
||
@property
|
||
def description(self) -> str:
|
||
return (
|
||
"Exact arithmetic: returns the exact value of a math expression. Use it for any "
|
||
"calculation with numbers (sums, products, percentages, powers, unit prices, totals) "
|
||
"instead of working it out yourself, then answer with its value."
|
||
)
|
||
|
||
@property
|
||
def inputSchema(self) -> Dict[str, Any]:
|
||
return {
|
||
"type": "object",
|
||
"properties": {
|
||
"expression": {
|
||
"type": "string",
|
||
"description": (
|
||
"Numbers and operators only, e.g. '3847*2963', '478500*17/100' (a percentage "
|
||
"as /100), '1.07^12', 'sqrt(2)'. No units, words or thousands separators."
|
||
),
|
||
},
|
||
},
|
||
"required": ["expression"],
|
||
}
|
||
|
||
def run(self, args: Optional[Dict[str, Any]], context: ToolContext) -> ToolExecutionResult:
|
||
expression = str((args or {}).get("expression") or "")
|
||
try:
|
||
value = calculate(expression)
|
||
except ValueError as e:
|
||
# The expression may hold the asker's own numbers: its length only, never its text.
|
||
debug_log(f"calculator: refused ({len(expression)} chars): {e}", "tools")
|
||
return ToolExecutionResult(success=False, reply_text=f"Error: {e}.", error_message=f"{e}.")
|
||
debug_log(f"calculator: computed ({len(expression)} chars)", "tools")
|
||
return ToolExecutionResult(success=True, reply_text=f"{expression.strip()} = {value}")
|