How to make an AI startup, starting with the meter
A build-along: a FastAPI endpoint that runs a step-capped tool-using agent and writes tokens, dollars and stop reasons per customer into SQLite.
What you'll have running
An hour from now: POST /ask on localhost:8000. An agent that calls a tool, stops itself at 6 model calls, and writes input tokens, output tokens, stop reason and dollars for every single request into a SQLite file. Plus GET /usage, which totals that by customer.
That second endpoint is the startup. The model is rented — Claude Sonnet 4.5 lists at $3 per million input tokens and $15 per million output tokens on Anthropic's pricing page. The meter is the only part you own.
I took Metadata.io from $0 to $15M ARR on $50M raised, and I'm building a zero-human company now — agents do the work, I pay the bills. An AI company that cannot state cost per request per customer is not a company yet. It's a demo with a credit card attached.
Prerequisites. Python 3.10 or newer; check with python3 --version. An Anthropic API key from console.anthropic.com, billed per token at the rates above. curl. The sqlite3 CLI is handy at the end but optional, because the code uses the stdlib sqlite3 module. No Docker, no vector database, no agent framework.
The shape of it
Four moving parts. The endpoint accepts a request. A loop alternates model calls and tool calls until the model stops asking for tools. A counter outside the model kills the loop at 6 steps. One row lands in SQLite before the response goes back.
The cap lives in Python, not in the prompt. Unbounded consumption is a documented risk class in the OWASP Top 10 for LLM Applications, and a model asked politely to stop after six tries is not a control. A while steps < MAX_STEPS is a control.
Who picks the next step is also the line between a workflow and an agent — I've written about that boundary in Autonomous agents, defined by who picks the next step. Here the model picks. The cap decides how many times it gets to.
The file
Save this as app.py. It runs as written, once ANTHROPIC_API_KEY is set.
# app.py — a metered, step-capped agent endpoint
import json
import os
import sqlite3
import time
import uuid
from anthropic import Anthropic
from fastapi import FastAPI
from pydantic import BaseModel
MODEL = "claude-sonnet-4-5"
PRICE_IN_PER_MTOK = 3.00 # USD / 1M input tokens
PRICE_OUT_PER_MTOK = 15.00 # USD / 1M output tokens
MAX_STEPS = 6 # hard ceiling on model calls per request
DB_PATH = "meter.db"
client = Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])
app = FastAPI()
SCHEMA = """
CREATE TABLE IF NOT EXISTS calls (
id TEXT PRIMARY KEY,
ts REAL NOT NULL,
tenant TEXT NOT NULL,
steps INTEGER NOT NULL,
stop_reason TEXT NOT NULL,
input_tokens INTEGER NOT NULL,
output_tokens INTEGER NOT NULL,
cost_usd REAL NOT NULL
);
"""
def db():
conn = sqlite3.connect(DB_PATH)
conn.row_factory = sqlite3.Row
return conn
with db() as conn:
conn.executescript(SCHEMA)
TOOLS = [
{
"name": "lookup_account",
"description": "Look up a customer account by email. Returns plan, seats, MRR.",
"input_schema": {
"type": "object",
"properties": {"email": {"type": "string"}},
"required": ["email"],
},
}
]
# Stand-in for your database. Reserved documentation domains on purpose.
ACCOUNTS = {
"dana@example.com": {"plan": "team", "seats": 12, "mrr_usd": 480},
"sam@example.test": {"plan": "free", "seats": 1, "mrr_usd": 0},
}
def run_tool(name: str, args: dict) -> dict:
if name != "lookup_account":
return {"error": f"unknown tool: {name}"}
return ACCOUNTS.get(args.get("email", ""), {"error": "no such account"})
def cost_usd(input_tokens: int, output_tokens: int) -> float:
return round(
input_tokens / 1_000_000 * PRICE_IN_PER_MTOK
+ output_tokens / 1_000_000 * PRICE_OUT_PER_MTOK,
6,
)
class Ask(BaseModel):
tenant: str
question: str
@app.post("/ask")
def ask(req: Ask):
messages = [{"role": "user", "content": req.question}]
input_tokens = output_tokens = steps = 0
stop_reason = "step_cap"
resp = None
while steps < MAX_STEPS:
steps += 1
resp = client.messages.create(
model=MODEL,
max_tokens=1024,
tools=TOOLS,
messages=messages,
)
input_tokens += resp.usage.input_tokens
output_tokens += resp.usage.output_tokens
messages.append({"role": "assistant", "content": resp.content})
if resp.stop_reason != "tool_use":
stop_reason = resp.stop_reason
break
results = []
for block in resp.content:
if block.type == "tool_use":
results.append(
{
"type": "tool_result",
"tool_use_id": block.id,
"content": json.dumps(run_tool(block.name, block.input)),
}
)
messages.append({"role": "user", "content": results})
answer = ""
if resp is not None:
answer = "".join(b.text for b in resp.content if b.type == "text")
row = {
"id": str(uuid.uuid4()),
"ts": time.time(),
"tenant": req.tenant,
"steps": steps,
"stop_reason": stop_reason,
"input_tokens": input_tokens,
"output_tokens": output_tokens,
"cost_usd": cost_usd(input_tokens, output_tokens),
}
with db() as conn:
conn.execute(
"INSERT INTO calls VALUES (:id,:ts,:tenant,:steps,:stop_reason,"
":input_tokens,:output_tokens,:cost_usd)",
row,
)
return {"answer": answer, "meter": row}
@app.get("/usage")
def usage():
with db() as conn:
rows = conn.execute(
"SELECT tenant,"
" COUNT(*) AS requests,"
" SUM(input_tokens) AS input_tokens,"
" SUM(output_tokens) AS output_tokens,"
" ROUND(SUM(cost_usd), 6) AS cost_usd,"
" SUM(CASE WHEN stop_reason = 'step_cap' THEN 1 ELSE 0 END) AS capped"
" FROM calls GROUP BY tenant ORDER BY cost_usd DESC"
).fetchall()
return [dict(r) for r in rows]
Three details worth naming. Every Messages API response carries usage.input_tokens and usage.output_tokens, so you never estimate cost — you read it. stop_reason is tool_use when the model wants a tool and end_turn when it's done; that's the whole loop condition. And every tool_use block must be answered with a matching tool_result in the next user message. Miss one and the next call is a 400.
One thing to change before this touches real customers: tenant arrives in the request body, which means the caller picks whose bill to sign. That's fine on localhost and wrong everywhere else. Derive it from whatever authenticates the request — an API key row, a JWT claim — and treat the body field as untrusted. A meter that can be misattributed by the party being metered is not a meter.
Notice also what the row doesn't store: the question, the answer, or the tool arguments. That's deliberate. The meter needs to be safe to keep for years and cheap to hand to finance, and the moment it contains customer text it inherits every retention and access-control obligation that text carries. Log payloads if you need them, but log them somewhere else, with their own expiry.
SQLite is the right default here and has a known limit: one writer at a time. PRAGMA journal_mode=WAL buys you concurrent readers alongside that writer, which is enough for a single process serving modest traffic. Past that, the insert is one statement against one table with no joins, so moving it to Postgres later is a connection-string change rather than a rewrite. Pick the durable store early; the schema is the part you'd regret.
Build it
- Make a directory and a virtualenv:
mkdir metered-agent && cd metered-agent && python3 -m venv .venv && source .venv/bin/activate. Your prompt now starts with(.venv). - Install two packages:
pip install "fastapi[standard]" anthropic. Last line readsSuccessfully installed anthropic-... fastapi-... uvicorn-.... The[standard]extra is what pulls in uvicorn. - Create a key at
console.anthropic.comunder Settings → API keys, thenexport ANTHROPIC_API_KEY=sk-ant-.... Check it withecho ${ANTHROPIC_API_KEY:0:7}— you should seesk-ant-and nothing else. - Verify the key and the model id in one call:
curl -s https://api.anthropic.com/v1/models -H "x-api-key: $ANTHROPIC_API_KEY" -H "anthropic-version: 2023-06-01". You get JSON with a"data"array of model objects, each with an"id"likeclaude-sonnet-4-5-20250929. Ifclaude-sonnet-4-5is not in that list, put an id that is intoMODEL. - Paste the file above into
app.py. Nothing to edit. - Start it:
uvicorn app:app --reload. You should seeUvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)andApplication startup complete.Ameter.dbfile now exists in the directory. - Send a request that forces the tool:
curl -s localhost:8000/ask -H 'content-type: application/json' -d '{"tenant":"acme","question":"Is dana@example.com on a paid plan, and how many seats?"}'. The response shape is{"answer":"...team plan, 12 seats...","meter":{"steps":2,"stop_reason":"end_turn","input_tokens":2314,"output_tokens":118,"cost_usd":0.008712}}. Your token counts will differ every run — that's the point of measuring instead of guessing.stepsshould be 2: one call to ask for the tool, one to answer with the result. - Read the meter:
curl -s localhost:8000/usage. One object per tenant:[{"tenant":"acme","requests":1,"input_tokens":2314,"output_tokens":118,"cost_usd":0.008712,"capped":0}]. - Prove the cap fires. Set
MAX_STEPS = 1inapp.py(uvicorn--reloadrestarts on save), send the same curl, and look at the meter:stop_reasonisstep_cap,stepsis 1, andansweris empty or a partial thought, because the model was cut off mid-tool-call. Runcurl -s localhost:8000/usageandcappedis now 1. Set it back to 6. - Query the raw rows the way you'd query them at 3am:
sqlite3 meter.db "select tenant, steps, stop_reason, cost_usd from calls order by ts desc limit 5;". Output is pipe-delimited, e.g.acme|2|end_turn|0.008712.
Step 9 is the one people skip. A cap you have never seen fire is a cap you are assuming.
When it doesn't work
Three failures account for most first runs.
The key isn't in the environment. uvicorn dies at import with a KeyError: 'ANTHROPIC_API_KEY' from the os.environ[...] line. If you exported the key in a different shell, or before activating the venv, it isn't there. export it again in the shell that runs uvicorn. If the key is present but wrong or revoked, you get a 401 instead: authentication_error with the message invalid x-api-key.
The model id is stale. Anthropic returns a 404 whose body is {"type":"error","error":{"type":"not_found_error","message":"model: claude-sonnet-4.5"}} — note the dot in that example, which is the usual typo. Model ids use hyphens. Re-run the /v1/models curl from step 4 and copy an id verbatim.
Tool results and tool calls don't line up. If the model emits two tool_use blocks in one turn and you return one tool_result, the next request fails with a 400 invalid_request_error complaining that tool_use ids were found without matching tool_result blocks. The loop above iterates every block in resp.content for exactly this reason. Refactor it to handle resp.content[0] only and you will meet this error.
One more you'll hit if you leave it running: a 429 rate_limit_error, or a 400 saying your credit balance is too low. Both are account state, not code. Neither should take the endpoint down — wrap client.messages.create in a try/except that still writes the meter row with whatever tokens accumulated before the failure. A failed request that cost you $0.004 is still a cost.
The number the meter gives you
Run the cost function on the sample counts from step 7: 2,314 input tokens at $3 per million is $0.006942, and 118 output tokens at $15 per million is $0.00177. Total $0.008712. Now the question that actually decides whether this is a business: at a $49/month seat, $49 ÷ $0.008712 ≈ 5,624 requests before gross margin on that seat is zero.
The cap gives you a ceiling too, not just an average. With MAX_STEPS = 6 and max_tokens=1024, one request can emit at most 6,144 output tokens — about $0.09 at Sonnet's $15 per million. Input is the side that surprises people: the full transcript is resent on every call, so a six-step request pays for its earliest messages six times over. That accumulation, not the output, is what makes a runaway loop expensive, and it's why input_tokens is its own column rather than a footnote.
That's the sentence you cannot write without the table in meter.db.
| Model | Input, $/1M tokens | Output, $/1M tokens |
|---|---|---|
| Claude Opus 4.1 | 15.00 | 75.00 |
| Claude Sonnet 4.5 | 3.00 | 15.00 |
| Claude Haiku 4.5 | 1.00 | 5.00 |
Prices from Anthropic's pricing page; check it before you quote them, because vendors change them and your PRICE_* constants are now load-bearing financial code. The spread between rows is why tenant is in the schema. Route cheap questions to Haiku and hard ones to Sonnet — a decision you can only defend with per-request data. And output tokens cost 5× input across all three rows, so verbosity in your system prompt is not free.
Two more columns to add before you charge anyone: cache hit tokens, and a request_type so you can separate a one-shot answer from a ten-tool research run. I wrote up why the meter comes before the product in Start an AI company by building the meter first.
What I would not hand to the agent yet
Spend authority. This endpoint can call a model and read a dict. It cannot issue a refund, change a price, send outbound email, or push a campaign live. I would not give an agent any of those until the meter has run for weeks and I can see the shape of its bad days, not just its demo. Same argument I made in Agentic go-to-market, and the parts I would not automate.
The other thing I keep on a human is the tool inventory. Adding a tool changes the agent's reachable state space, and the cap is your only guarantee about how far it travels. Six steps with one read-only tool is a bounded system. Six steps with a write tool and a shell is not, regardless of what the prompt says.
When you add that second tool, watch the capped column before you watch the answers.
Sources
- Anthropic API pricing — Per-million-token input and output prices for Claude Sonnet 4.5, Haiku 4.5 and Opus 4.1 used in the price table and the cost function
- Anthropic Messages API reference — usage.input_tokens and usage.output_tokens on every response; stop_reason values including tool_use and end_turn; tool_result block shape
- Anthropic API: List Models — The GET /v1/models call used to verify the key and read exact model ids
- Anthropic API errors — 401 authentication_error, 404 not_found_error, 429 rate_limit_error response shapes quoted in the failure section
- anthropic-sdk-python — Package name, client construction, and the ANTHROPIC_API_KEY environment variable default
- Anthropic Console — Where to create the API key
- FastAPI documentation — fastapi[standard] install and the uvicorn app:app run command
- Python sqlite3 module — Standard-library SQLite, no server required for the meter table
- OWASP Top 10 for LLM Applications — Unbounded consumption is a documented LLM application risk class, which is why the step cap sits outside the model