diff --git a/src/jarvis/tools/builtin/calculator.py b/src/jarvis/tools/builtin/calculator.py index 3cee170..b2a5f6f 100644 --- a/src/jarvis/tools/builtin/calculator.py +++ b/src/jarvis/tools/builtin/calculator.py @@ -1,12 +1,15 @@ """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. +pi/e are evaluated; anything else is refused, never run as code. Numbers are exact fractions as +written (1.1 is 11/10), so + - * / // % and whole-number powers have no binary rounding; only the +math functions and fractional powers work in floats. """ import ast import math import operator +from fractions import Fraction from typing import Any, Dict, Optional from ...debug import debug_log @@ -14,7 +17,7 @@ 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. +# Largest exact power worked out (about 3000 digits); bigger ones are refused. _MAX_POWER_BITS = 10_000 _BINARY = { @@ -37,9 +40,11 @@ class _Refused(ValueError): 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") + if isinstance(base, (int, Fraction)) and isinstance(exponent, (int, Fraction)) and exponent == int(exponent): + base, exponent = Fraction(base), int(exponent) + size = max(abs(base.numerator).bit_length(), base.denominator.bit_length()) + if size > 1 and size * abs(exponent) > _MAX_POWER_BITS: + raise _Refused("the result has too many digits") return base ** exponent result = float(base) ** float(exponent) if isinstance(result, complex): @@ -49,7 +54,8 @@ def _power(base, exponent): def _eval(node): if isinstance(node, ast.Constant) and type(node.value) in (int, float): - return node.value + # As written: the float 1.1 becomes 11/10, not the binary 1.100000000000000088... + return Fraction(repr(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: @@ -66,11 +72,12 @@ def _eval(node): def _readable(value) -> str: - if isinstance(value, int): + if isinstance(value, (int, Fraction)) and value == int(value): try: - return str(value) + return str(int(value)) except ValueError: # more digits than Python turns into text - raise _Refused("the result is too large") + raise _Refused("the result has too many digits") + value = float(value) if not math.isfinite(value): raise _Refused("the result is not a finite number") if value.is_integer() and abs(value) < 1e15: diff --git a/src/jarvis/tools/builtin/calculator.spec.md b/src/jarvis/tools/builtin/calculator.spec.md index 272ae8b..9bb4ec7 100644 --- a/src/jarvis/tools/builtin/calculator.spec.md +++ b/src/jarvis/tools/builtin/calculator.spec.md @@ -11,12 +11,16 @@ idea comes from OpenJarvis's calculator tool (github.com/open-jarvis/openjarvis, 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 +- **Bounded.** At most 200 characters. An exact power whose result would be over about 10,000 + bits (about 3000 digits, also tiny ones such as `2^-100000`) 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. +- **Exact as written.** Numbers are exact fractions as written (`1.1` is 11/10, not the nearest + binary float), so `+ - * / // %` and whole-number powers have no rounding error: `ceil(1.1*100)` + is 110 and `floor(0.3/0.1)` is 3. Only the math functions, `pi`, `e` and fractional powers work + in floats. - **Signs people write.** `^` is a power, `×` multiplies, `÷` divides, `−` is a minus. - **Raw data.** No LLM call. The answer is ` = `: whole numbers exact, - a float that is a whole number below 10^15 as that whole number, other floats to 10 significant + a float that is a whole number below 10^15 as that whole number, other values 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 @@ -34,7 +38,7 @@ idea comes from OpenJarvis's calculator tool (github.com/open-jarvis/openjarvis, ## Tests -- `tests/test_calculator_tool.py`: exact values, readable fractions, refused code and non-math, +- `tests/test_calculator_tool.py`: exact values, decimals exact as written, 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: diff --git a/tests/test_calculator_tool.py b/tests/test_calculator_tool.py index 83b13d1..46f3322 100644 --- a/tests/test_calculator_tool.py +++ b/tests/test_calculator_tool.py @@ -34,6 +34,20 @@ def test_it_gives_the_exact_value(expression, expected): assert value_of(run(expression)) == expected +@pytest.mark.unit +@pytest.mark.parametrize("expression, expected", [ + ("ceil(1.1*100)", "110"), + ("floor(0.3/0.1)", "3"), + ("0.1+0.2", "0.3"), + ("1.1*3 - 3.3", "0"), + ("10.5 % 0.1", "0"), + ("2.675*100 // 1", "267"), + ("0.5^-2", "4"), +]) +def test_decimals_are_exact_as_written(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"))) @@ -61,7 +75,7 @@ def test_anything_but_arithmetic_is_refused(expression): @pytest.mark.unit -@pytest.mark.parametrize("expression", ["9**9**9", "10**100000", "(10**300)**300"]) +@pytest.mark.parametrize("expression", ["9**9**9", "10**100000", "(10**300)**300", "1.5**100000", "2**-100000"]) def test_a_huge_power_fails_fast_instead_of_hanging(expression): start = time.monotonic() r = run(expression)