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

> AI Release · @ai_releaseorg · https://ai-release.org/guides/kak-zastavit-neyroset-schitat-pravilno-kod-interpretato_en.html

## TL;DR

- Time to complete: 30 minutes
- Difficulty: Intermediate
- 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.

## What you will get

- `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.

## Quick start

```bash
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

```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](https://ai-release.org/guides/img/kak-zastavit-neyroset-schitat-pravilno-kod-interpretato-en-1.jpg?v=1795509828)


- 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 PROVIDER_API_KEY="..."`. The variable name is provider-specific — check the documentation.
- No GPU, no database and no network access are needed for the calculator itself; it runs in-process.
- If the numbers you need live in a wiki, a database or a test management system rather than in the prompt, that retrieval step is a separate job: [Step-by-step guide: how to connect an LLM to your wiki, database, and test management system for QA](https://ai-release.org/guides/poshagovoe-rukovodstvo-kak-podklyuchit-neyroset-k-wiki.html?utm_source=tg&utm_medium=channel&utm_campaign=guide_inline&utm_content=guide_to_guide).

## 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.

```json
{
  "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:

```bash
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](https://ai-release.org/guides/img/kak-zastavit-neyroset-schitat-pravilno-kod-interpretato-en-2.jpg?v=1795509834)


**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()`.

```python
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.

```python
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:**

```bash
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](https://ai-release.org/guides/kak-zaschitit-mcp-servery-ot-atak-audit-tool-calls-i-pr.html?utm_source=tg&utm_medium=channel&utm_campaign=guide_inline&utm_content=guide_to_guide).

## Step 3. Verify every number in the answer before shipping
![Illustration: Step 3. Verify every number in the answer before shipping](https://ai-release.org/guides/img/kak-zastavit-neyroset-schitat-pravilno-kod-interpretato-en-3.jpg?v=1795509838)


**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.

```python
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`:

```text
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:

```text
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 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 |

## Troubleshooting

**Problem. The model passes code instead of an expression**
- Ошибка: `ValueError: expression contains characters outside 0-9 + - * / ( ) . e E`
- Причина: the model wrote `round(1250*0.07, 2)` or `7%` because the tool description said "arithmetic" without saying what is forbidden.
- Решение: keep the error string as the tool result (it goes back to the model verbatim), and tighten the `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'>]`
- Причина: an input was missing from the prompt (a blank discount field, an empty row) and the model substituted `0` to keep going.
- Решение: rule 5 of the system prompt forbids substitution. In `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`
- Причина: the model returned prose only, or wrote the JSON under a different key such as `"numbers"`, so the regex `\{"claims".*?\}` does not match.
- Решение: block the answer, append the mismatch line to the conversation, and re-run. If it repeats, paste the exact block shape from rule 4 of the system prompt into the retry message. Check the regex against a saved file with `python3 verify_numbers.py answer.md`; exit code `2` means "contract missing", distinct from `1` meaning "wrong number".

## 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.
