tools.json — a ready tool definition that lets the model call a real calculator instead of guessing.calc_tool.py — a sandboxed evaluator with a CLI, exact decimal arithmetic, and a character whitelist that rejects anything that is not arithmetic.verify_numbers.py — an auditor that recomputes every number in the model's answer and exits with code 1 when one of them does not match.system.prompt — a copy-paste system prompt that forces the model to route every number through the tool and to emit a machine-checkable claims block.python3 -m venv .venv && source .venv/bin/activate
python3 calc_tool.py "1250*0.07"
python3 verify_numbers.py answer.mdDetails and checks — in the steps below.
You are a calculation assistant. Every number in your final answer must come from the calculate tool.
Rules:
1. Never do arithmetic yourself, not even for "obvious" cases like 2+2. If a number appears in your answer, it must be produced by a tool call.
2. Pass one arithmetic expression per call. Use digits, + - * / ** ( ) and decimal points only. Do not pass function names such as round(), do not pass percent signs, currency symbols or thousands separators.
3. Copy the string the tool returns into your answer exactly as returned. Do not re-round it, do not reformat it.
4. End every answer with a fenced code block tagged json, containing exactly this shape:
{"claims": [{"expression": "<the expression you passed>", "value": "<the string the tool returned>"}]}
Include one entry per tool call that contributed a number to the answer.
5. If an input needed for the calculation is missing, ask for it. Never substitute 0 or 1.
6. If the tool returns an error, read the error text, fix the expression once and retry. If it fails a second time, stop and report the error text verbatim.Replace before use: the tool name calculate (must match the name field in tools.json), and the wording of rule 3 if your product requires fixed decimal places — then state the number of places explicitly.

python3 --version.tools, functions, tool_choice) — check the documentation for your provider.export PROVIDER_API_KEY="...". The variable name is provider-specific — check the documentation.What to do: create tools.json in your project root with a single tool named calculate. The description is not decoration — the model reads it to decide when and how to call the tool.
{
"type": "function",
"function": {
"name": "calculate",
"description": "Evaluate exactly one arithmetic expression and return the exact decimal result. Call this for every number that appears in the answer. Do not call it with function names, percent signs or units.",
"parameters": {
"type": "object",
"properties": {
"expression": {
"type": "string",
"description": "Arithmetic expression using digits, + - * / ** ( ) and '.', for example (1250*0.07)+80"
}
},
"required": ["expression"]
}
}
}Why: the model cannot execute arithmetic; it predicts plausible tokens. A tool definition converts "guess a number" into "ask a program for a number", and a narrow expression field keeps the request machine-checkable. Keeping one expression per call also makes the audit in Step 3 trivial: one call, one claim, one line of output.
How to check: validate the file parses as JSON:
python3 -c "import json;print(json.load(open('tools.json'))['function']['name'])"Expected output: calculate.

What to do: create calc_tool.py. It parses the expression into a syntax tree and walks it, allowing only five operators, so a malicious or confused expression cannot reach eval().
import ast, operator, re, sys
from decimal import Decimal, getcontext
getcontext().prec = 28
OPS = {ast.Add: operator.add, ast.Sub: operator.sub, ast.Mult: operator.mul,
ast.Div: operator.truediv, ast.Pow: operator.pow, ast.USub: operator.neg}
ALLOWED = re.compile(r"^[0-9eE+\-*/(). ]+$")
def _eval(node):
if isinstance(node, ast.Expression):
return _eval(node.body)
if isinstance(node, ast.Constant) and isinstance(node.value, (int, float)):
return Decimal(str(node.value))
if isinstance(node, ast.BinOp) and type(node.op) in OPS:
return OPS[type(node.op)](_eval(node.left), _eval(node.right))
if isinstance(node, ast.UnaryOp) and type(node.op) in OPS:
return OPS[type(node.op)](_eval(node.operand))
raise ValueError(f"unsupported node: {type(node).__name__}")
def calculate(expression: str) -> str:
if not ALLOWED.match(expression):
raise ValueError("expression contains characters outside 0-9 + - * / ( ) . e E")
return str(_eval(ast.parse(expression, mode="eval")))
if __name__ == "__main__":
print(calculate(sys.argv[1]))Then wire the tool into the model call. The provider-specific part is the message format only; the loop is always the same: send question → receive tool call → execute → send the result back → repeat until the model stops asking.
import json
from calc_tool import calculate
TOOLS = json.load(open("tools.json"))
def run_tool(name, args):
try:
return calculate(args["expression"])
except Exception as e:
return f"ERROR: {type(e).__name__}: {e}"
def answer(question, call_model):
messages = [{"role": "system", "content": open("system.prompt").read()},
{"role": "user", "content": question}]
for _ in range(6):
resp = call_model(messages, TOOLS) # provider SDK call goes here
messages.append(resp.message)
calls = resp.message.get("tool_calls", [])
if not calls:
return resp.message["content"]
for c in calls:
result = run_tool(c["name"], json.loads(c["arguments"]))
messages.append({"role": "tool", "tool_call_id": c["id"], "content": result})
raise RuntimeError("tool loop did not converge after 6 turns")Why: Decimal keeps 1250*0.07 at exactly 87.50 instead of the binary-float tail 87.50000000000001, and returning errors as strings lets the model read the message and repair its own call instead of crashing the run. The six-turn cap stops a model that keeps calling the tool with the same broken expression.
How to check:
python3 calc_tool.py "1250*0.07"
python3 calc_tool.py "round(1250*0.07)"Expected: the first command prints 87.50; the second fails with ValueError: expression contains characters outside 0-9 + - * / ( ) . e E. That failure is the guard working — the model gets this text back and retries with a bare expression.
If the tool will be exposed over a remote MCP server (MCP — a standard protocol for serving tools to a model over the network instead of in-process Python) rather than imported locally, audit the server's permissions before pointing a production agent at it: How to Secure MCP Servers: Auditing Tool Calls and Permissions.

What to do: create verify_numbers.py. It extracts the claims block, recomputes each expression with the same calculate() function and compares the values as decimals, so 87.5 and 87.50 count as equal.
import json, re, sys
from decimal import Decimal, InvalidOperation
from calc_tool import calculate
CLAIMS = re.compile(r'```json\s*(\{"claims".*?\})\s*```', re.S)
def main(path):
text = open(path, encoding="utf-8").read()
m = CLAIMS.search(text)
if not m:
print("NO_CLAIMS_BLOCK: answer does not end with a claims block")
return 2
claims = json.loads(m.group(1))["claims"]
bad = 0
for c in claims:
want = c.get("value")
try:
got = calculate(c["expression"])
ok = Decimal(got) == Decimal(str(want))
except (InvalidOperation, KeyError, ValueError) as e:
ok, got = False, f"{type(e).__name__}: {e}"
print(("OK " if ok else "MISMATCH"), c.get("expression"),
"claimed", want, "recomputed", got)
bad += 0 if ok else 1
print(f"{len(claims)} claims, {bad} mismatch")
return 1 if bad else 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1]))Example: answer.md contains one prose sentence and one fenced block tagged json:
The discount is 87.50 and the total is 1337.50.
{"claims": [{"expression": "1250*0.07", "value": "87.50"}, {"expression": "1250*0.7", "value": "87.50"}]}Run python3 verify_numbers.py answer.md. Expected screen output:
OK 1250*0.07 claimed 87.50 recomputed 87.50
MISMATCH 1250*0.7 claimed 87.50 recomputed 875.0
2 claims, 1 mismatchWhy: the second line is the whole point of the exercise. The model slipped a decimal point, wrote a confident answer, and no human would have spotted it in prose — but the recomputation flags it in one line. Exit code 1 makes the check usable in CI: echo $? prints 1 after the run above.
How to check: run the verifier on the model's real output file and read the last line. 0 mismatch plus exit code 0 is the pass condition.
| Verifier signal | Meaning | Action |
|---|---|---|
| `0 mismatch`, exit `0` | every claim reproduces | ship the answer |
| `MISMATCH …` | value differs from recomputation | block, regenerate with the mismatch text in the prompt |
| `NO_CLAIMS_BLOCK` | model skipped the contract | block, re-run with the system prompt attached |
Problem. The model passes code instead of an expression
ValueError: expression contains characters outside 0-9 + - * / ( ) . e Eround(1250*0.07, 2) or 7% because the tool description said "arithmetic" without saying what is forbidden.expression description to name the allowed characters. Test the repair path with python3 calc_tool.py "round(1250*0.07)", then re-run the agent loop — the second call normally arrives as 1250*0.07.Problem. Division by zero in the middle of a report
decimal.DivisionByZero: [<class 'decimal.DivisionByZero'>]0 to keep going.run_tool, the exception is already returned as a string, so the model sees ERROR: DivisionByZero and asks for the value. Confirm the behaviour with python3 calc_tool.py "1250*0" (returns 0.0) versus python3 calc_tool.py "1250/0", which raises the error above.Problem. The verifier cannot find the claims
NO_CLAIMS_BLOCK: answer does not end with a claims block"numbers", so the regex \{"claims".*?\} does not match.python3 verify_numbers.py answer.md; exit code 2 means "contract missing", distinct from 1 meaning "wrong number".You now have a three-part pipeline: a tool definition that forces the model to ask for arithmetic, a sandboxed decimal evaluator that answers those requests, and a verifier that recomputes every claim before a human reads it. The next step is to run the verifier in CI on every generated report, so a MISMATCH fails the build instead of reaching the customer.
Why not just tell the model to think step by step?
Reasoning traces improve plausibility, not correctness: the same token prediction produces the same wrong digit. Only an external computation changes the value, which is why the claims block points back to a tool result.
Does a code interpreter guarantee correct numbers?
It guarantees the arithmetic inside the tool is correct. It does not guarantee the model copied the returned string into the answer without editing it, which is exactly what verify_numbers.py catches.
How do I stop the model from calling the tool for trivial numbers?
You do not. Allowing exceptions reopens the guessing path. Keep rule 1 absolute; a calculate call costs one round trip and removes an entire class of errors.
What should the comparison tolerance be?
Keep exact Decimal comparison for values that came from the tool, since both sides are the same string. If your inputs are already rounded before they reach the model, fix the number of decimal places in rule 3 of the prompt and compare at that precision — check the documentation for your provider's number serialisation if it reformats floats.
Status: practical guide. Some statements come from vendors; verify in your environment.
Time to complete: 30 minutes Difficulty: Intermediate
Machine data: Citation Map JSON · JSON-LD · Semantic Embeddings — separate stage.
| Entity | Type | Role |
|---|---|---|
| нейросеть неправильно считает | тема/инструмент | упоминается в заголовке, TL;DR или разделах гайда |
| как заставить chatgpt считать правильно | тема/инструмент | упоминается в заголовке, TL;DR или разделах гайда |
| llm ошибки в вычислениях | тема/инструмент | упоминается в заголовке, TL;DR или разделах гайда |
| код-интерпретатор для расчётов | тема/инструмент | упоминается в заголовке, TL;DR или разделах гайда |
| проверка чисел в ответах ии | тема/инструмент | упоминается в заголовке, TL;DR или разделах гайда |
| Windows | платформа/технология | упоминается в заголовке, TL;DR или разделах гайда |
| Linux | платформа/технология | упоминается в заголовке, TL;DR или разделах гайда |
| macOS | платформа/технология | упоминается в заголовке, TL;DR или разделах гайда |
| Python | платформа/технология | упоминается в заголовке, TL;DR или разделах гайда |
No independent confirmation is provided; source claims and editorial conclusions are separated below.
| Source | Type | Role |
|---|---|---|
| No external links | — | — |
Cite as: AI Release. Как заставить нейросеть считать правильно: код-интерпретатор, tool use и проверка цифр. ai-release.org.