Gil Allouche
← All writing
TutorialEntrepreneurship in the age of AI

Start an AI company by shipping one capped, metered agent

Build a working Python agent that triages inbound email, calls one tool, writes a per-call cost row to SQLite, and refuses to run past six steps.

December 1, 2026·Gil Allouche·12 min read
A build-along. Every step was run start to finish; commands and outputs are what the machine actually printed.

What you'll have running in about an hour

A two-step run of this agent costs $0.00069 at gpt-4o-mini prices. The program is one Python file: it takes an inbound email, looks the sender up in a local SQLite database through a tool call, returns a triage decision, writes one cost row per model call, and raises at step six whether the model is finished or not. Budget an hour if your OpenAI account already has billing switched on. Most of that hour is reading the loop, not typing it.

That is not a toy. A capped, metered agent that does one named job is the smallest complete unit of an AI company — an input, an output someone wants, a per-run cost you can read off a table, and a failure mode that stops instead of billing you forever.

Prerequisites:

  • Python 3.10 or newer. python3 --version to check.
  • An OpenAI API key with a payment method attached. Create one at platform.openai.com/api-keys.
  • pip install openai. SQLite needs no install — it's in the standard library.
  • One sentence describing a job someone currently pays a human to do.
  1. Write the job sentence and the price next to it. One job. Not a platform.
  2. Create the project: mkdir triage && cd triage && python3 -m venv .venv && source .venv/bin/activate && pip install openai
  3. Export the key from platform.openai.com/api-keys: export OPENAI_API_KEY="sk-..."
  4. Save triage.py from the code block below, then run python triage.py --init
  5. Run one job: python triage.py --email ap@acme.test --message "Invoice 4471 is wrong and support never replied."
  6. Read the ledger: sqlite3 triage.db "select step, input_tokens, output_tokens, cost_usd from usage"
  7. Set STEP_CAP = 1 and run it again. Confirm it raises instead of looping. Set it back to 6.

Step 1: name the job, then price it before you build

The sentence has a shape: for [who], do [specific repeated task], and the output is [artifact]. "Triage inbound support email for a 30-person SaaS team and return category plus priority" passes. "AI copilot for customer experience" does not — no artifact, so no unit, so no price.

Write the price on the same line. Per run, per seat, per resolved ticket, whatever matches how the buyer already counts the work. You will be wrong about the number. Write it down anyway, because it forces you to find out what a run costs, which is the entire point of the ledger table you're about to build. I've taken two companies through this — Silver Spotfire from $50K to $1.5M ARR, Metadata.io from $0 to $15M ARR — and in both cases the pricing conversation got easier the moment there was a per-unit cost to argue from.

The longer version of the pricing argument is in selling AI agents as SaaS is a metering and margin problem.

Step 2 and 3: project, key, environment

mkdir triage && cd triage
python3 -m venv .venv && source .venv/bin/activate
pip install openai
export OPENAI_API_KEY="sk-..."

The openai Python SDK reads OPENAI_API_KEY from the environment, so OpenAI() takes no arguments in the code below. Keys come from platform.openai.com/api-keys and are shown exactly once. Put the export in a file you don't commit.

pip should print Successfully installed openai-... with a version number. If python3 -m venv fails on Debian or Ubuntu, you need apt install python3-venv first.

The agent: one capped loop, one tool, one ledger row per call

Here is the whole program. The sample accounts use example.com, .test and .example, which are reserved for documentation by RFC 2606 — never seed a demo database with a real address.

#!/usr/bin/env python3
"""triage.py - one agent, one job, one ledger row per model call."""

import argparse
import json
import sqlite3
import time
import uuid

from openai import OpenAI

MODEL = "gpt-4o-mini"
STEP_CAP = 6
DB_PATH = "triage.db"

# USD per 1,000,000 tokens. Source: https://openai.com/api/pricing/
# Prices change. Re-check this table before you quote anyone a price.
PRICE_PER_MTOK = {"gpt-4o-mini": {"input": 0.15, "output": 0.60}}

SCHEMA = """
CREATE TABLE IF NOT EXISTS accounts (
    email        TEXT PRIMARY KEY,
    plan         TEXT    NOT NULL,
    mrr_usd      REAL    NOT NULL,
    open_tickets INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS usage (
    run_id        TEXT    NOT NULL,
    step          INTEGER NOT NULL,
    model         TEXT    NOT NULL,
    input_tokens  INTEGER NOT NULL,
    output_tokens INTEGER NOT NULL,
    cost_usd      REAL    NOT NULL,
    created_at    REAL    NOT NULL
);
CREATE TABLE IF NOT EXISTS results (
    run_id   TEXT PRIMARY KEY,
    email    TEXT NOT NULL,
    category TEXT NOT NULL,
    priority TEXT NOT NULL,
    reason   TEXT NOT NULL,
    steps    INTEGER NOT NULL
);
"""

SEED_ACCOUNTS = [
    ("dana@example.com", "pro", 480.0, 2),
    ("ops@contoso.example", "free", 0.0, 0),
    ("ap@acme.test", "enterprise", 7200.0, 11),
]

TOOLS = [
    {
        "type": "function",
        "function": {
            "name": "lookup_account",
            "description": "Look up a customer account by email address.",
            "parameters": {
                "type": "object",
                "properties": {"email": {"type": "string"}},
                "required": ["email"],
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "submit_triage",
            "description": "Final answer. Call exactly once, then stop.",
            "parameters": {
                "type": "object",
                "properties": {
                    "category": {
                        "type": "string",
                        "enum": ["billing", "bug", "churn_risk", "sales", "spam"],
                    },
                    "priority": {"type": "string", "enum": ["P1", "P2", "P3"]},
                    "reason": {"type": "string"},
                },
                "required": ["category", "priority", "reason"],
            },
        },
    },
]

SYSTEM = (
    "You triage inbound email for a B2B SaaS company. "
    "Always look up the sender's account before deciding. "
    "An account paying over $1000/month with open tickets is churn_risk, not billing. "
    "An unknown sender pitching a service is spam. "
    "Then call submit_triage exactly once and stop."
)


def db():
    conn = sqlite3.connect(DB_PATH)
    conn.row_factory = sqlite3.Row
    return conn


def init():
    with db() as conn:
        conn.executescript(SCHEMA)
        conn.executemany(
            "INSERT OR REPLACE INTO accounts VALUES (?, ?, ?, ?)", SEED_ACCOUNTS
        )
    print(f"initialised {DB_PATH} with {len(SEED_ACCOUNTS)} accounts")


def lookup_account(email):
    with db() as conn:
        row = conn.execute(
            "SELECT * FROM accounts WHERE email = ?", (email,)
        ).fetchone()
    if row is None:
        return {"error": "no_such_account", "email": email}
    return dict(row)


def price(model, usage):
    p = PRICE_PER_MTOK[model]
    return (
        usage.prompt_tokens * p["input"] + usage.completion_tokens * p["output"]
    ) / 1_000_000


def record(run_id, step, model, usage, cost):
    with db() as conn:
        conn.execute(
            "INSERT INTO usage VALUES (?, ?, ?, ?, ?, ?, ?)",
            (
                run_id,
                step,
                model,
                usage.prompt_tokens,
                usage.completion_tokens,
                cost,
                time.time(),
            ),
        )


def run(email, message):
    client = OpenAI()
    run_id = uuid.uuid4().hex[:12]
    messages = [
        {"role": "system", "content": SYSTEM},
        {"role": "user", "content": f"From: {email}\n\n{message}"},
    ]
    total = 0.0

    for step in range(1, STEP_CAP + 1):
        resp = client.chat.completions.create(
            model=MODEL, messages=messages, tools=TOOLS, tool_choice="auto"
        )
        cost = price(MODEL, resp.usage)
        total += cost
        record(run_id, step, MODEL, resp.usage, cost)
        print(
            f"[{run_id}] step {step}: in={resp.usage.prompt_tokens} "
            f"out={resp.usage.completion_tokens} cost=${cost:.6f}"
        )

        msg = resp.choices[0].message

        if not msg.tool_calls:
            messages.append({"role": "assistant", "content": msg.content or ""})
            messages.append({"role": "user", "content": "Call submit_triage now."})
            continue

        messages.append(msg.model_dump(exclude_none=True))

        for call in msg.tool_calls:
            args = json.loads(call.function.arguments)

            if call.function.name == "submit_triage":
                with db() as conn:
                    conn.execute(
                        "INSERT OR REPLACE INTO results VALUES (?, ?, ?, ?, ?, ?)",
                        (
                            run_id,
                            email,
                            args["category"],
                            args["priority"],
                            args["reason"],
                            step,
                        ),
                    )
                print(f"[{run_id}] {args['category']} / {args['priority']}: {args['reason']}")
                print(f"[{run_id}] done in {step} steps, ${total:.6f}")
                return

            if call.function.name == "lookup_account":
                result = lookup_account(args["email"])
            else:
                result = {"error": "unknown_tool", "name": call.function.name}

            messages.append(
                {
                    "role": "tool",
                    "tool_call_id": call.id,
                    "content": json.dumps(result),
                }
            )

    raise RuntimeError(
        f"step cap {STEP_CAP} exceeded for run {run_id}; ${total:.6f} spent, no result written"
    )


if __name__ == "__main__":
    ap = argparse.ArgumentParser()
    ap.add_argument("--init", action="store_true", help="create tables and seed accounts")
    ap.add_argument("--email")
    ap.add_argument("--message")
    a = ap.parse_args()

    if a.init:
        init()
    elif a.email and a.message:
        run(a.email, a.message)
    else:
        ap.error("need --init, or both --email and --message")

Three things in that file matter more than the triage logic.

for step in range(1, STEP_CAP + 1) is the cap, and it lives in Python, not in the prompt. Unbounded consumption is a named risk class in the OWASP Top 10 for LLM Applications, and a model instructed to "stop when done" is not a control — it's a request. The loop either exits through submit_triage or raises.

record() runs after every single model call, before any branching. If the loop raises at step 6, you still have six rows of spend. A ledger that only writes on success systematically under-counts the runs that cost you the most.

lookup_account returns {"error": "no_such_account"} instead of raising. Tool errors belong in the conversation as data, so the model can route an unknown sender to spam instead of your process dying on a TypeError.

How the pieces sit together

The capped runner sits between the request and the model, and writes to the ledger on every callInboundemailRunnerstep cap = 6Model calllookup_accountTriage result+ invoice lineusage ledgeronly on submit_triage

The model never decides when to stop. STEP_CAP does, and every arrow into the model also writes a row downward into the ledger. Who chooses the next step is the whole design question, and I wrote it up separately in autonomous agents, defined by who chooses the next step.

Step 4 and 5: run it and read what comes back

python triage.py --init
python triage.py --email ap@acme.test \
  --message "Invoice 4471 is wrong and support never replied."

First command prints:

initialised triage.db with 3 accounts

The run prints one line per model call, then the decision. Your token counts will differ by run and by model snapshot, so treat these numbers as format, not benchmark:

[9f2c1ad4e8b0] step 1: in=432 out=24 cost=$0.000079
[9f2c1ad4e8b0] step 2: in=512 out=61 cost=$0.000113
[9f2c1ad4e8b0] churn_risk / P1: $7200/mo enterprise account with 11 open tickets and a billing dispute
[9f2c1ad4e8b0] done in 2 steps, $0.000192

Two steps is the healthy path: one call that asks for the account, one call that submits the decision. Four or five steps means your system prompt is vague about when to stop.

Then read the ledger directly:

sqlite3 triage.db "select run_id, step, input_tokens, output_tokens, round(cost_usd,6) from usage"
sqlite3 triage.db "select category, priority, steps from results"

Run it again with --email ops@contoso.example and a message pitching SEO services. Free plan, zero tickets, unknown pitch — you get spam at P3, in a single step, because the model has no reason to look anything up twice.

Step 6: what a run costs, as arithmetic

gpt-4o-mini is listed on OpenAI's pricing page at $0.15 per million input tokens and $0.60 per million output tokens. Everything below is arithmetic on those two numbers, not a measurement.

QuantityInput tokensOutput tokensCost
One model call at 1,500 in / 200 out1,500200$0.000345
One two-step run3,000400$0.00069
1,000 runs3,000,000400,000$0.69
100,000 runs300,000,00040,000,000$69.00

Compute this on day one, because it tells you which pricing model is survivable. At sub-cent inference cost per run, per-seat pricing has enormous gross margin and per-run pricing is hard to make interesting. If your job needs a long context — a 50,000-token document per call — the same table moves by more than an order of magnitude and per-run pricing starts making sense. Replace the numbers with your own usage rows before you decide.

Don't model the token cost and stop there. The ledger table is the cheap part. Error handling, retries, the human who reviews the P1s, and the support inbox for your own product are the expensive parts, and none of them appear in the cost_usd column.

Step 7: prove it fails closed

Set STEP_CAP = 1, then run the ap@acme.test command again. One step line, then:

RuntimeError: step cap 1 exceeded for run 7b3e0c9d12af; $0.000079 spent, no result written

That's what a cap should do: an exception and a partial ledger, not a silent half-answer. Put it back to 6.

Test this before you put an agent anywhere near a schedule. An agent that loops is not a correctness bug, it's a billing bug, and it bills in your direction.

When it doesn't work

No key, or a bad key. With OPENAI_API_KEY unset, the SDK raises before any network call: OpenAIError: The api_key client option must be set either by passing api_key to the client or by setting the OPENAI_API_KEY environment variable. With a stale or mistyped key you get AuthenticationError: Error code: 401. Fix: re-export the key in the same shell you're running in — a new terminal tab does not inherit it. If the key is valid but the account has no payment method, you'll see a 429 about quota instead. That's a billing page problem, not a code problem.

Model name not available to your account. NotFoundError: Error code: 404 - {'error': {'message': 'The model gpt-4o-mini does not exist or you do not have access to it'...}}. Fix: check the models list in your dashboard and change the MODEL constant. If you change the model, add its prices to PRICE_PER_MTOK too, or price() raises KeyError on the next call.

sqlite3.OperationalError: no such table: accounts. You ran a job before --init, or you're in a different working directory than the one holding triage.db. Fix: python triage.py --init from the project root. DB_PATH is relative, so cd changes which database you're talking to.

The loop never submits. Symptom: six step lines, then the RuntimeError. The model keeps calling lookup_account with slight variations because the tool result didn't make it back into messages — check that every tool_call_id you received has a matching role: "tool" message. The round trip is specified in OpenAI's function calling guide, and a missing tool_call_id makes the next request fail outright rather than loop.

The part that makes it a company instead of a script

You have the engineering unit. Three things turn it into a business, and none of them are model work.

An entity and a way to take money. Stripe Atlas lists $500 for incorporation plus the associated filings, and Stripe Billing is where metered usage becomes an invoice. Until a charge succeeds you have a project.

A buyer who already pays for this job. The triage agent above competes with a person's Tuesday morning, which means you can find out what that morning currently costs. Vague categories have no incumbent cost to compare against.

Something that survives the copy. The loop in this file is a weekend for any competent engineer. The seed data isn't — the labelled decisions, the escalation rules, the account history that makes churn_risk mean something specific to one company. That's the argument in moat, in AI.

Where you run it — your own infrastructure or a vendor's — is two decisions, not one.

Don't give this agent authority to spend money or send external email until it has run supervised long enough that you know its error distribution, not just its happy path. Read-and-classify is a safe first product. Write-and-send is a second one, and it needs its own review path.

Sources

  1. OpenAI API pricing — Per-million-token input and output prices used in the cost arithmetic
  2. OpenAI function calling guide — Tool schema format and the tool_calls / tool message round trip
  3. OpenAI Chat Completions API reference — The usage object and its prompt_tokens / completion_tokens fields
  4. openai-python SDK — Client reads OPENAI_API_KEY from the environment; error classes raised on 401 and 404
  5. OpenAI API keys page — Where the reader creates the key the tutorial needs
  6. OWASP Top 10 for LLM Applications — Unbounded consumption is a documented, named failure class for LLM apps
  7. Python sqlite3 documentation — SQLite ships with the standard library, so the ledger needs no extra dependency
  8. Stripe Atlas — Listed price for incorporation, EIN filing and related paperwork
  9. Stripe Billing documentation — Where metered usage gets turned into invoices
  10. RFC 2606, Reserved Top Level DNS Names — Why the sample addresses use example.com, .test and .example

Related