Solving it with Python: an invoice calculator

Language models get exact maths wrong. Give the calculation to a Python code node and the writing to the model.

Advanced8 min

In this lesson

  • Writing a custom Python model
  • JSON input and numeric outputs
  • Combining exact code with a language model

Build it yourself

This workflow and its Python model are created in your account and opened in the editor, where you can change and run them.

Sample input to run it with

[{"name":"A4 paper","qty":3,"price":25},{"name":"Pens","qty":10,"price":6}]

The nodes in this workflow

Items (JSON)

items

The item list: name, qty, price.

Tax percent

tax_percent

For example 10.

Invoice calculator

main.py

Your Python code in the sandbox: computes subtotal, tax and total exactly.

Text template

{{table}} {{total}}

Turns the code’s exact numbers into a writing request.

Language model

Claude Haiku

Only writes the message; the maths was done by code.

Total

total

Returns the result under this key in the API response and in chat.

Customer message

message

Returns the result under this key in the API response and in chat.

Python code

The execute function receives the inputs in inputs and returns a dictionary of outputs. The code runs in a sandbox.

main.pypython
"""Invoice calculator: exact totals for a list of items (from the MLGrid lessons)."""


def execute(inputs: dict, params: dict) -> dict:
    items = inputs.get("items") or []
    if isinstance(items, dict):
        items = items.get("items", [])
    tax_percent = float(inputs.get("tax_percent") or 0)

    lines, subtotal = [], 0.0
    for item in items:
        qty = float(item.get("qty", 1))
        price = float(item.get("price", 0))
        amount = qty * price
        subtotal += amount
        lines.append(f"{item.get('name', '?')}: {qty:g} x {price:,.2f} = {amount:,.2f}")

    tax = round(subtotal * tax_percent / 100, 2)
    total = round(subtotal + tax, 2)
    lines.append(f"subtotal: {subtotal:,.2f}")
    lines.append(f"tax ({tax_percent:g}%): {tax:,.2f}")
    return {"table": "\n".join(lines), "tax": tax, "total": total}