← All guides AI Release
RU Subscribe to @ai_releaseorg

How to Make an LLM Do Math Correctly: Code Interpreter, Tool Use and Number Verification

Updated: 24.11.2026 · AI Release · @ai_releaseorg
How to Make an LLM Do Math Correctly: Code Interpreter, Tool Use and Number Verification

TL;DR

What you will get

Quick start

python3 -m venv .venv && source .venv/bin/activate
python3 calc_tool.py "1250*0.07"
python3 verify_numbers.py answer.md

Details and checks — in the steps below.

Prompt to copy

PromptCopy the whole block — this is the ready-to-use system prompt
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.

Requirements and setup

Illustration: Requirements and setup
Illustration: Requirements and setup

Step 1. Define the calculation tool and the number contract

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.

Step 2. Run the tool loop with a sandboxed evaluator

Illustration: Step 2. Run the tool loop with a sandboxed evaluator
Illustration: Step 2. Run the tool loop with a sandboxed evaluator

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.

Step 3. Verify every number in the answer before shipping

Illustration: Step 3. Verify every number in the answer before shipping
Illustration: Step 3. Verify every number in the answer before shipping

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 mismatch

Why: 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 signalMeaningAction
`0 mismatch`, exit `0`every claim reproducesship the answer
`MISMATCH …`value differs from recomputationblock, regenerate with the mismatch text in the prompt
`NO_CLAIMS_BLOCK`model skipped the contractblock, re-run with the system prompt attached

Troubleshooting

Problem. The model passes code instead of an expression

Problem. Division by zero in the middle of a report

Problem. The verifier cannot find the claims

Summary and next steps

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.

FAQ

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.

🤖 AI summary

AI Release Knowledge Layer
Machine-readable description · Version 1.0

Status: practical guide. Some statements come from vendors; verify in your environment.

1. Summary

Time to complete: 30 minutes Difficulty: Intermediate

Inside: direct answers, key facts, entities, context, reliability, unknowns and sources.

Machine data: Citation Map JSON · JSON-LD · Semantic Embeddings — separate stage.

Full Knowledge Layer: sections 2–8

2. Direct answers

What is required?
Python 3.10 or newer; check with python3 --version.; An LLM endpoint that supports tool calling and accepts a JSON Schema tool definition. The wrapper field names differ between providers (tools, functions, tool_choice) — check the documentation for your provider.; An API key exported in the shell, e.g. export… → details (AR-GUIDE-KAKZASTAVI-003)
How to do it?
Step 1. Define the calculation tool and the number contract → Step 2. Run the tool loop with a sandboxed evaluator → Step 3. Verify every number in the answer before shipping → details (AR-GUIDE-KAKZASTAVI-004)
Which topics does it cover?
нейросеть неправильно считает, как заставить chatgpt считать правильно, llm ошибки в вычислениях, код-интерпретатор для расчётов, проверка чисел в ответах ии → details (AR-GUIDE-KAKZASTAVI-002)
What are the key points?
Time to complete: 30 minutes Difficulty: Intermediate → details (AR-GUIDE-KAKZASTAVI-007)

3. Key facts

  1. Time to complete: 30 minutes — evidence; status: заявление источника.
  2. Difficulty: Intermediate — evidence; status: заявление источника.
  3. You will need: Python 3.10+ on Linux/macOS/Windows, an LLM with tool calling (a.k.a. function calling — the model can request a named function instead of answering in text), an API key for that provider stored in an environment variable, a text editor, ~50 MB of free disk space for the virtual environment. — evidence; status: заявление источника.
  4. Python 3.10 or newer; check with python3 --version. — evidence; status: заявление источника.
  5. An LLM endpoint that supports tool calling and accepts a JSON Schema tool definition. The wrapper field names differ between providers (tools, functions, tool_choice) — check the documentation for your provider. — evidence; status: заявление источника.
  6. An API key exported in the shell, e.g. export PROVIDER_API_KEY="...". The variable name is provider-specific — check the documentation. — evidence; status: заявление источника.

4. Entities

EntityTypeRole
нейросеть неправильно считаеттема/инструментупоминается в заголовке, TL;DR или разделах гайда
как заставить chatgpt считать правильнотема/инструментупоминается в заголовке, TL;DR или разделах гайда
llm ошибки в вычисленияхтема/инструментупоминается в заголовке, TL;DR или разделах гайда
код-интерпретатор для расчётовтема/инструментупоминается в заголовке, TL;DR или разделах гайда
проверка чисел в ответах иитема/инструментупоминается в заголовке, TL;DR или разделах гайда
Windowsплатформа/технологияупоминается в заголовке, TL;DR или разделах гайда
Linuxплатформа/технологияупоминается в заголовке, TL;DR или разделах гайда
macOSплатформа/технологияупоминается в заголовке, TL;DR или разделах гайда
Pythonплатформа/технологияупоминается в заголовке, TL;DR или разделах гайда

5. Context

  • Guide — describes → How to Make an LLM Do Math Correctly: Code Interpreter, Tool Use and Number Verification (AR-GUIDE-KAKZASTAVI-001).
  • Guide — includes step → Step 1. Define the calculation tool and the number contract (AR-GUIDE-KAKZASTAVI-001).

6. Reliability

Confirmed

No independent confirmation is provided; source claims and editorial conclusions are separated below.

Source claims

  • Product features, versions, prices and limits come from vendors and the guide.
  • Commands and steps are recommendations, not guaranteed results.

AI Release analysis

  • Structure, comparison and selection criteria are editorial.
  • The guide does not replace an independent audit or legal advice.

7. Unknowns

  • Current versions, prices and limits.
  • Independent benchmarks and quality checks.
  • Terms of use and data policy.

8. Sources

SourceTypeRole
No external links——

Cite as: AI Release. Как заставить нейросеть считать правильно: код-интерпретатор, tool use и проверка цифр. ai-release.org.