feat(tools): calculator tool for exact arithmetic

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>
This commit is contained in:
javis-bot
2026-11-23 11:33:53 +09:00
parent b39aabd368
commit 99b7234336
8 changed files with 345 additions and 0 deletions

View File

@@ -0,0 +1,146 @@
"""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}")

View File

@@ -0,0 +1,41 @@
# calculator tool spec
Exact arithmetic for the reply model. Models work numbers out in their heads and get multi-digit
products and powers wrong (qwen3:8b on 2026-11-23: 3847 x 2963 as 11,378,261, 1.07^12 as 3.84;
in the reply loop without this tool it searched the web for the product and gave no answer). The
idea comes from OpenJarvis's calculator tool (github.com/open-jarvis/openjarvis, Apache 2.0).
## Principles
- **Never code.** The expression is parsed with `ast` and only a whitelist is evaluated: int and
float numbers, `+ - * / // % **`, unary `+ -`, parentheses, the functions `abs round min max sqrt
exp log ln log10 log2 sin cos tan ceil floor` (positional values only) and the constants `pi e`.
Names, attributes, strings, lists, keyword values and anything else are refused.
- **Bounded.** At most 200 characters. A whole-number power whose result would be over about
10,000 bits (about 3000 digits) is refused before it is worked out, and a float that overflows
or is not finite is refused, so no expression can hang the worker.
- **Signs people write.** `^` is a power, `×` multiplies, `÷` divides, `−` is a minus.
- **Raw data.** No LLM call. The answer is `<expression as given> = <value>`: whole numbers exact,
a float that is a whole number below 10^15 as that whole number, other floats to 10 significant
digits. The reply model says it in the user's language.
- **Errors the model can act on.** A refused or failed expression (division by zero, a function
outside its range, not valid math, too long, too large) comes back as `success=False` with the
reason, so the model can fix the expression.
- **Private numbers stay out of logs.** Debug logs carry the expression's length and the outcome,
never its text.
- **Always offered.** It reads and sends nothing, so it has no feature switch; `disabled_tools`
still turns it off like any built-in.
## Schema
| field | type | meaning |
|---|---|---|
| `expression` | string, required | 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 |
## Tests
- `tests/test_calculator_tool.py`: exact values, readable fractions, refused code and non-math,
huge powers failing fast, bad expressions, offered and run through the registry.
- `evals/test_calculator_tool.py`: a four-digit product and a fractional power use the tool and
the answer carries the exact value; an unrelated question does not use it (qwen3:8b, v2 setup:
0 of 2 before the tool, 12 of 12 over four runs after).

View File

@@ -25,6 +25,7 @@ from .builtin.collected_news import CollectedNewsTool, COLLECT_ENV
from .builtin.bot_browser import BotBrowserTool, CDP_ENV
from .builtin.refresh_mcp_tools import RefreshMCPToolsTool
from .builtin.weather import WeatherTool
from .builtin.calculator import CalculatorTool
from .builtin.stop import StopTool
from .builtin.tool_search import ToolSearchTool
from .builtin.browse_and_play import BrowseAndPlayTool
@@ -47,6 +48,7 @@ BUILTIN_TOOLS = {
"deleteMeal": DeleteMealTool(),
"refreshMCPTools": RefreshMCPToolsTool(),
"getWeather": WeatherTool(),
"calculator": CalculatorTool(),
"stop": StopTool(),
"toolSearchTool": ToolSearchTool(),
"browseAndPlay": BrowseAndPlayTool(),