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

@@ -25,6 +25,7 @@ Any code change must either adhere to our spec files perfectly or you should ask
| `src/jarvis/tools/builtin/chat_channels.spec.md` | chatChannels tool (v2): list, read, search, send, edit, react, delete, pin registered Discord chat channels through the voice worker and app | Offered only with a chat backend; per-channel switches; chat is fenced data; delete needs the user's yes in a later turn |
| `src/jarvis/tools/builtin/schedule.spec.md` | schedule tool (v2): reminders, timers and scheduled tasks of the asker; the app keeps, fires and delivers them | Offered only with a schedule backend; only the asker's own; tasks get read-only tools; never claimed without the tool |
| `src/jarvis/tools/builtin/personal_notes.spec.md` | personalNotes tool (v2): each person's standing instructions for how they are answered; the app keeps them and sends the asker's with every reply | Offered only with a notes backend; only the asker's own, only in their answers; fenced, never permits an action |
| `src/jarvis/tools/builtin/calculator.spec.md` | calculator tool: exact arithmetic from a whitelisted `ast` evaluation (numbers, operators, a few math functions), bounded length and power size | Never runs code; raw data, no LLM; refuses with a reason the model can act on; expression text never logged |
| `src/jarvis/tools/builtin/collected_news.spec.md` | collectedNews tool (v2): read the background collection's results (targets, newest items) | Offered only with the app's collection file and the feature on; web content fenced as data; read-only, no LLM |
| `src/jarvis/tools/builtin/screen_view.spec.md` | screenView tool (v2): see the whole screen, one monitor or one window through the app; pictures go to the reply model for that reply only | Offered only when the app makes screen viewing available; the app decides who may see; screen text is data; pictures never kept or logged |
| `src/jarvis/tools/builtin/pc_control.spec.md` | pcControl tool (v2 M7): list windows, read a window, click, type, keys, run and close programs through the app's agent-desktop | Offered only when the app makes PC control available; ask-level actions need the asker's own next message; payments, passwords, deleting files and admin never; screen text is data |

View File

@@ -36,6 +36,7 @@
- 원하면 게임 중에는 봇을 일시정지할 수 있습니다.
- **안티치트 보호**: 뱅가드 같은 안티치트가 걸린 게임이 실행 중이면 키보드·마우스 자동 조작을 막고 그 이유를 알려 줍니다.
- **기존 기능 유지**: 메모리, 날씨, 웹 검색, 식단 기록, MCP, 브라우저 제어를 그대로 가져갑니다.
- **계산기**: "3847 곱하기 2963은?", "47만 8500원의 17%는?"처럼 물으면 모델이 암산하지 않고 계산기 도구로 정확한 값을 구해 답합니다.
- **기상청 날씨**: 관리 앱 "기능" 화면에 기상청 API허브 인증키를 넣으면 한국 안의 현재 날씨와 10일 뒤까지의 예보("내일 날씨", "주말 날씨")를 기상청에서 받습니다. "부산 연제구"처럼 구 단위로 물으면 그 구의 날씨를 답하고(장소는 OpenStreetMap에서 찾습니다), "자세히" 물으면 습도, 바람, 강수량까지 답합니다(초단기실황조회, 초단기예보조회, 단기예보조회, 중기기온조회, 중기육상예보조회 활용신청 필요). 키가 없거나 한국 밖이면 open-meteo에서 받고, 현재 날씨는 그다음 met.no에서 받습니다.
- **관리 앱**:
- 첫 실행 마법사, 대시보드, 모델 다운로드, 기능별 켜기/끄기를 제공합니다.

View File

@@ -27,6 +27,7 @@ Every distinct LLM call in Jarvis, what feeds it, what consumes it, and how it i
- **v2 schedule tool and scheduled tasks**: when the voice worker's brain sets a schedule backend (`turn_state.set_schedule`, every voice and chat reply), `schedule` is in the catalogue for the router (#7) and `prepare_intent()` (not force-offered every turn); without a backend it is not in the catalogue at all ([spec](src/jarvis/tools/builtin/schedule.spec.md)). A scheduled `task` the app fires is one more run of this loop (`reply` `via: "task"`, at the task's time, in the worker's chat lane, waiting for LLM switches like any reply): the asker's history scope, a fresh short-term memory, no prepared pick, no chat or schedule backend, `mcps={}` and `disabled_tools` widened to everything but `TASK_TOOLS` (`getWeather`, `webSearch`, `fetchWebPage`, `fetchMeals`, `collectedNews`, `toolSearchTool`), so the router, planner and loop see only those. The app waits at most 300 s for its answer and delivers it (`app/src/admin.spec.md`, "Schedules"). Eval: `evals/test_schedule_tool.py`.
- **v2 personal notes**: the app sends the asker's standing instructions with every voice, chat and task reply; `run_reply_engine(person_notes=...)` adds them to the system message (after the warm profile, before the history block) inside a `<person_notes>` fence, labelled as that person's own answer preferences that never permit an action or a tool. Only the asker's notes, at most 20 of 300 characters. The `personalNotes` tool (add, list, delete) is in the catalogue only with a notes backend (`turn_state.set_notes`, every voice and chat reply; not tasks), also for `prepare_intent()`. No extra LLM call ([spec](src/jarvis/tools/builtin/personal_notes.spec.md)). Eval: `evals/test_personal_notes.py`.
- **v2 collected news**: the `collectedNews` tool (list targets, read a target's newest items) puts the background collection's results into the loop inside an UNTRUSTED COLLECTED CONTENT fence; offered only with the app's collection file (`JARVIS_COLLECT_PATH`) and `features.collect` on, and one of the scheduled tasks' tools (`TASK_TOOLS`). No LLM call inside. The app's news notifications post titles and links with no LLM ([spec](src/jarvis/tools/builtin/collected_news.spec.md)). Eval: `evals/test_collected_news.py`.
- **calculator**: the `calculator` tool is in every catalogue (no feature switch, `disabled_tools` still applies) and evaluates a math expression from a whitelist with `ast`, so arithmetic comes from the tool instead of the model's head. No LLM call inside ([spec](src/jarvis/tools/builtin/calculator.spec.md)). Eval: `evals/test_calculator_tool.py`.
- **v2 screen view (pictures)**: the `screenView` tool (whole screen, one monitor, one window or someone's Discord screen share in its popped-out window, or the list of monitors and windows) returns base64 JPEG pictures with its result; the loop puts them on the tool message (`images`) and `llm.py` sends them to Strata as a user message of `image_url` parts right after the tool messages (about 768 / 1280 px long side, or four parts for `detailed`; at most 3 MiB). Offered only when the app makes screen viewing available (Windows, someone registered for PC control), which also starts the LLM with `--vision gpu` (normal stage) or `cpu` (game stage), else `--vision off`. Pictures stay in the one reply: not in the tool carryover, logs or prompt dumps. No extra LLM call ([spec](src/jarvis/tools/builtin/screen_view.spec.md)). Eval: `evals/test_screen_view_tool.py`.
- Tool schema: native via `generate_tools_json_schema()` ([src/jarvis/tools/registry.py](src/jarvis/tools/registry.py)) or text fallback via `_text_tool_call_guidance()` ([engine.py:68](src/jarvis/reply/engine.py:68))
- Tool results from prior turns (raw or digested — see #5)

View File

@@ -0,0 +1,68 @@
"""
Eval: the model works out arithmetic with the calculator tool and answers with its exact value
instead of computing it in its head (src/jarvis/tools/builtin/calculator.spec.md).
Cases (numbers chosen so a model guessing in its head gets them wrong; qwen3:8b without the tool
answered 3847 x 2963 as 11,378,261 and 1.07^12 as 3.84 on 2026-11-23):
- a product of two four-digit numbers uses the calculator and the answer carries the exact value,
- a power with a fraction does the same,
- an unrelated question does not use the calculator.
Run: EVAL_JUDGE_MODEL=qwen3:8b python -m pytest evals/test_calculator_tool.py -v
(v2 brain setup: EVAL_COMPACT_PROMPT=1 EVAL_INTENT_JUDGE=1)
"""
import re
import pytest
from conftest import requires_judge_llm
def _run(mock_config, eval_db, eval_dialogue_memory, query):
from helpers import JUDGE_BASE_URL, JUDGE_MODEL
from jarvis.memory.history import HistoryContext
from jarvis.reply import turn_state
from jarvis.reply.engine import run_reply_engine
from jarvis.tools.builtin import calculator
mock_config.ollama_base_url = JUDGE_BASE_URL
mock_config.ollama_chat_model = JUDGE_MODEL
calls = []
original = calculator.calculate
calculator.calculate = lambda expression: calls.append(expression) or original(expression)
turn_state.reset()
turn_state.set_user("100")
try:
reply = run_reply_engine(db=eval_db, cfg=mock_config, tts=None, text=query,
dialogue_memory=eval_dialogue_memory, history=HistoryContext(),
legacy_memory=False, default_language="Korean") or ""
finally:
turn_state.reset()
calculator.calculate = original
print(f"\n calculator [{JUDGE_MODEL}] {query!r}: calls={calls} reply={reply[:200]!r}")
return calls, reply
def _digits(text):
"""The reply with digit-group separators and spaces removed ("11,398,661" -> "11398661")."""
return re.sub(r"(?<=\d)[,\s](?=\d)", "", text).replace(" ", "")
@pytest.mark.eval
@requires_judge_llm
class TestCalculator:
def test_a_large_product_is_computed_exactly(self, mock_config, eval_db, eval_dialogue_memory):
calls, reply = _run(mock_config, eval_db, eval_dialogue_memory, "3847 곱하기 2963은 얼마야?")
assert calls, "the calculator was not used"
assert any(v in _digits(reply) for v in ("11398661", "1139만8661")), reply
def test_a_fractional_power_is_computed_exactly(self, mock_config, eval_db, eval_dialogue_memory):
calls, reply = _run(mock_config, eval_db, eval_dialogue_memory, "1.07의 12제곱은 얼마야?")
assert calls, "the calculator was not used"
assert "2.25" in reply, reply
def test_an_unrelated_question_does_not_calculate(self, mock_config, eval_db, eval_dialogue_memory):
calls, _ = _run(mock_config, eval_db, eval_dialogue_memory, "고양이는 하루에 몇 시간 자?")
assert not calls, calls

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(),

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")