diff --git a/src/jarvis/tools/builtin/calculator.py b/src/jarvis/tools/builtin/calculator.py index b2a5f6f..db50298 100644 --- a/src/jarvis/tools/builtin/calculator.py +++ b/src/jarvis/tools/builtin/calculator.py @@ -9,6 +9,7 @@ math functions and fractional powers work in floats. import ast import math import operator +from decimal import Decimal, InvalidOperation from fractions import Fraction from typing import Any, Dict, Optional @@ -19,6 +20,8 @@ from ..types import ToolExecutionResult MAX_EXPRESSION_CHARS = 200 # Largest exact power worked out (about 3000 digits); bigger ones are refused. _MAX_POWER_BITS = 10_000 +# Largest power of ten a written number may carry (1e4000); bigger ones are refused unparsed. +_MAX_LITERAL_EXPONENT = 4000 _BINARY = { ast.Add: operator.add, ast.Sub: operator.sub, ast.Mult: operator.mul, @@ -52,21 +55,34 @@ def _power(base, exponent): return result -def _eval(node): - if isinstance(node, ast.Constant) and type(node.value) in (int, float): - # As written: the float 1.1 becomes 11/10, not the binary 1.100000000000000088... +def _number(node, text): + if type(node.value) is int: + return Fraction(node.value) + # A float as written in the expression, not the float ast already rounded it to: 1.1 is 11/10, + # 1.0000000000000001 stays above 1, and 1e-400 is not 0. + try: + written = Decimal(ast.get_source_segment(text, node) or "") + except InvalidOperation: return Fraction(repr(node.value)) + if not written.is_finite() or abs(written.adjusted()) > _MAX_LITERAL_EXPONENT: + raise _Refused("a number has too many digits") + return Fraction(written) + + +def _eval(node, text): + if isinstance(node, ast.Constant) and type(node.value) in (int, float): + return _number(node, text) if isinstance(node, ast.BinOp) and isinstance(node.op, ast.Pow): - return _power(_eval(node.left), _eval(node.right)) + return _power(_eval(node.left, text), _eval(node.right, text)) if isinstance(node, ast.BinOp) and type(node.op) in _BINARY: - return _BINARY[type(node.op)](_eval(node.left), _eval(node.right)) + return _BINARY[type(node.op)](_eval(node.left, text), _eval(node.right, text)) if isinstance(node, ast.UnaryOp) and type(node.op) in _UNARY: - return _UNARY[type(node.op)](_eval(node.operand)) + return _UNARY[type(node.op)](_eval(node.operand, text)) 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]) + return _FUNCTIONS[node.func.id](*[_eval(a, text) for a in node.args]) raise _Refused("only numbers, + - * / ^ %, parentheses, " + ", ".join([*_FUNCTIONS, *_CONSTANTS]) + " are allowed") @@ -99,7 +115,7 @@ def calculate(expression: str) -> str: except (SyntaxError, ValueError, RecursionError, MemoryError): raise _Refused("the expression is not valid math") try: - return _readable(_eval(tree.body)) + return _readable(_eval(tree.body, text)) except ZeroDivisionError: raise _Refused("it divides by zero") except OverflowError: diff --git a/src/jarvis/tools/builtin/calculator.spec.md b/src/jarvis/tools/builtin/calculator.spec.md index 9bb4ec7..417e626 100644 --- a/src/jarvis/tools/builtin/calculator.spec.md +++ b/src/jarvis/tools/builtin/calculator.spec.md @@ -18,6 +18,9 @@ idea comes from OpenJarvis's calculator tool (github.com/open-jarvis/openjarvis, 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. + A number is read from its written text, so decimals longer than 17 digits and exponents beyond + the float range stay as written too (`ceil(1.0000000000000001)` is 2, `1e-400/1e-400` is 1); a + written number past 1e4000 (or below 1e-4000) is refused. - **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 values to 10 significant diff --git a/tests/test_calculator_tool.py b/tests/test_calculator_tool.py index 46f3322..3fc2d69 100644 --- a/tests/test_calculator_tool.py +++ b/tests/test_calculator_tool.py @@ -43,6 +43,9 @@ def test_it_gives_the_exact_value(expression, expected): ("10.5 % 0.1", "0"), ("2.675*100 // 1", "267"), ("0.5^-2", "4"), + ("ceil(1.0000000000000001)", "2"), + ("1e-400/1e-400", "1"), + ("1e400-1e400", "0"), ]) def test_decimals_are_exact_as_written(expression, expected): assert value_of(run(expression)) == expected @@ -75,7 +78,7 @@ def test_anything_but_arithmetic_is_refused(expression): @pytest.mark.unit -@pytest.mark.parametrize("expression", ["9**9**9", "10**100000", "(10**300)**300", "1.5**100000", "2**-100000"]) +@pytest.mark.parametrize("expression", ["9**9**9", "10**100000", "(10**300)**300", "1.5**100000", "2**-100000", "1e99999999", "1e-99999999*2"]) def test_a_huge_power_fails_fast_instead_of_hanging(expression): start = time.monotonic() r = run(expression)