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,85 @@
"""The calculator tool (src/jarvis/tools/builtin/calculator.spec.md): exact arithmetic for the reply
model, evaluated from a whitelist of number operations, never as code."""
from __future__ import annotations
import time
import pytest
from jarvis.tools.builtin.calculator import CalculatorTool
from jarvis.tools.registry import enabled_builtin_tools, run_tool_with_retries
def run(expression):
return CalculatorTool().run({"expression": expression}, None)
def value_of(result):
assert result.success, result.error_message
return result.reply_text.rsplit("=", 1)[1].strip()
@pytest.mark.unit
@pytest.mark.parametrize("expression, expected", [
("3847*2963", str(3847 * 2963)),
("478500*17/100", "81345"),
("2370000 * 14", str(2370000 * 14)),
("2^10", "1024"),
("12 × 3 ÷ 4", "9"),
("sqrt(144) + abs(-3)", "15"),
("(1 + 2) * -3", "-9"),
])
def test_it_gives_the_exact_value(expression, expected):
assert value_of(run(expression)) == expected
@pytest.mark.unit
def test_fractions_are_rounded_to_a_readable_length():
got = float(value_of(run("1.07^12")))
assert got == pytest.approx(1.07 ** 12, rel=1e-9)
assert len(value_of(run("98765/37"))) <= 16
@pytest.mark.unit
def test_the_answer_names_the_expression_it_computed():
assert run("3847*2963").reply_text.startswith("3847*2963")
@pytest.mark.unit
@pytest.mark.parametrize("expression", [
"__import__('os').system('echo hacked')",
"open('/etc/passwd').read()",
"(1).__class__",
"[1, 2, 3]",
"x + 1",
"'a' * 3",
])
def test_anything_but_arithmetic_is_refused(expression):
r = run(expression)
assert not r.success and r.error_message
@pytest.mark.unit
@pytest.mark.parametrize("expression", ["9**9**9", "10**100000", "(10**300)**300"])
def test_a_huge_power_fails_fast_instead_of_hanging(expression):
start = time.monotonic()
r = run(expression)
assert not r.success and r.error_message
assert time.monotonic() - start < 1
@pytest.mark.unit
@pytest.mark.parametrize("expression", ["1/0", "", " ", "2 +", "1" * 300])
def test_a_bad_expression_gets_an_error_the_model_can_act_on(expression):
r = run(expression)
assert not r.success and r.error_message
@pytest.mark.unit
def test_it_is_offered_and_runs_through_the_registry(mock_config):
cfg = mock_config
assert "calculator" in enabled_builtin_tools(cfg)
r = run_tool_with_retries(db=None, cfg=cfg, tool_name="calculator", tool_args={"expression": "6*7"},
system_prompt="", original_prompt="", redacted_text="", max_retries=0)
assert r.success and r.reply_text.endswith("42")