How to build an AI company, starting with one bounded worker
Build worker.py: an agent that qualifies leads from SQLite, caps itself at six model calls, logs the cost of every run, and parks big decisions for a human.
What you will have running in about an hour
worker.py qualifies a sales lead out of a local SQLite database, writes the token count and dollar cost of every run to a runs table, and refuses to auto-approve a meeting on a deal over $25,000. It cannot make more than six model calls, because the counter lives in Python rather than in the prompt. Set aside an hour, most of it spent reading the loop rather than typing it.
That file is the unit. A company that runs on agents is this file cloned per function — qualification, renewal checks, invoice matching — each with its own cap, its own ledger row, and its own list of actions a human still signs.
You need Python 3.9 or newer (3.9 shipped in October 2020); sqlite3 ships with it, so there is no database to install (docs). pip install openai gets you the 1.x SDK (repo). Version 1.0.0 landed in November 2023 and renamed nearly every call site from the 0.x interface, which is why the 0.28 check in step 1 below exists at all. Keys come from platform.openai.com/api-keys. Then the part people skip: the input and output price per million tokens for whichever model you pick, from the pricing page. The script reads both from environment variables and has no defaults, on purpose — I am not hard-coding a number OpenAI changes without asking me. The sqlite3 command-line tool is optional; there is a Python fallback below.
The unit is a bounded worker, not a chatbot
A model call with tools attached is not a company. The company is the three things wrapped around it: a counter that stops the loop, a ledger that records what the loop cost, and a gate between the agent's decision and anything irreversible.
Unbounded consumption is one of OWASP's top-ten risk classes for LLM applications — catalogued as LLM10:2025, Unbounded Consumption — and the loop is where it happens. A model that keeps calling the same tool will keep billing you until something external says stop.
Anthropic's engineering writeup on agents, Building effective agents (December 2024), argues the same thing from the other direction: start with the simplest composable pattern, add machinery only when it measurably improves the result. A single loop with three tools is that pattern. Reach for a framework later, when you have a number that says the loop is the problem — otherwise you are debugging someone else's graph abstraction instead of twelve lines of while.
If you want the taxonomy first, I wrote about the two meanings of "AI agent" and a single-file first agent.
Build it
Work through these in order. Step 6 is the one that matters — it is where you watch the cap fire.
- Confirm the SDK is installed:
pip install openaithenpython3 -c "import openai; print(openai.__version__)". You should see a version starting with1.. If it prints0.28or similar, you are on the old SDK and the code below will not run. - Export your key and your prices.
export OPENAI_API_KEY=sk-..., thenexport USD_PER_1M_IN=0.15andexport USD_PER_1M_OUT=0.60— replace those two with the real numbers for your model from platform.openai.com/docs/pricing. Check withecho $OPENAI_API_KEY | cut -c1-3, which printssk-. - Save the file in the block below as
worker.pyin an empty directory. It is complete — no placeholders to fill in. - Create and seed the database:
python3 -c "import worker; worker.init_db(); print('ok')". You should seeokand a newcompany.dbfile in the directory, about 20 KB. - Run the worker against the big lead:
python3 worker.py L-1002. On stderr you get one line per step, likestep 1 tool_calls=['get_lead']. On stdout you get a single JSON object with the keys run_id, lead_id, steps, status, route, decision_status, in_tokens, out_tokens, cost_usd. For a healthy run, status isdecidedand steps is under 6. - Prove the cap is real:
MAX_STEPS=1 python3 worker.py L-1002. The run stops after one model call, status comes backcapped, and route isnull. No row is written to the decisions table, because the agent never reached the terminal tool. That is the behaviour you want on a bad day. - Read the ledger:
sqlite3 company.db "select id, steps, in_tokens, out_tokens, cost_usd, status from runs". You get one pipe-delimited row per run. Nosqlite3binary? Usepython3 -c "import sqlite3;print(sqlite3.connect('company.db').execute('select * from runs').fetchall())". - Check the gate:
sqlite3 company.db "select lead_id, route, status from decisions". L-1002 carries a 90,000 dollar deal size, so a book_meeting route on it lands asneeds_approval, notauto_approved. Then runpython3 worker.py L-1003— a 500 dollar lead from a .test domain — and watch it clear without a human. - Run the whole queue:
for id in L-1001 L-1002 L-1003; do python3 worker.py $id; done. Three JSON objects, three new rows in runs, and a cost column you can sum. That sum is your cost per loop, and it is the only honest unit of capacity an agent company has.
worker.py
#!/usr/bin/env python3
"""worker.py - one bounded agent worker: step cap, cost ledger, approval gate."""
import json
import os
import sqlite3
import sys
from datetime import datetime, timezone
from openai import OpenAI
MODEL = os.environ.get("MODEL", "gpt-4o-mini")
MAX_STEPS = int(os.environ.get("MAX_STEPS", "6"))
APPROVAL_THRESHOLD_USD = 25_000
DB_PATH = "company.db"
# From https://platform.openai.com/docs/pricing for the model you chose.
# No defaults: a wrong price is worse than a crash on line 20.
USD_PER_1M_IN = float(os.environ["USD_PER_1M_IN"])
USD_PER_1M_OUT = float(os.environ["USD_PER_1M_OUT"])
SCHEMA = """
CREATE TABLE IF NOT EXISTS leads (
id TEXT PRIMARY KEY, email TEXT, company TEXT,
employees INTEGER, deal_size_usd INTEGER, source TEXT);
CREATE TABLE IF NOT EXISTS notes (lead_id TEXT, note TEXT);
CREATE TABLE IF NOT EXISTS runs (
id INTEGER PRIMARY KEY AUTOINCREMENT, lead_id TEXT, model TEXT,
steps INTEGER, in_tokens INTEGER, out_tokens INTEGER,
cost_usd REAL, status TEXT, started_at TEXT);
CREATE TABLE IF NOT EXISTS decisions (
run_id INTEGER, lead_id TEXT, route TEXT, reason TEXT,
confidence REAL, status TEXT, created_at TEXT);
"""
SEED_LEADS = [
("L-1001", "ops@northwind.example", "Northwind Traders", 40, 4000, "webinar"),
("L-1002", "procurement@contoso.example", "Contoso Ltd", 1200, 90000, "demo-request"),
("L-1003", "hello@tiny.test", "Tiny Co", 3, 500, "newsletter"),
]
SEED_NOTES = [
("L-1001", "Asked about SSO in the webinar Q&A."),
("L-1002", "Replaced an incumbent vendor last quarter; RFP in progress."),
("L-1002", "Procurement requires a SOC 2 report before any pilot."),
("L-1003", "Student project, no budget mentioned."),
]
SYSTEM = (
"You qualify inbound leads. Use get_lead and search_notes to gather facts, "
"then call submit_decision exactly once with route = reject, nurture, or "
"book_meeting. Decide from the record, not from assumptions. Keep reason "
"under 30 words and cite the field or note that drove it."
)
TOOLS = [
{"type": "function", "function": {
"name": "get_lead",
"description": "Fetch the lead record by id.",
"parameters": {"type": "object", "properties": {
"lead_id": {"type": "string"}}, "required": ["lead_id"]}}},
{"type": "function", "function": {
"name": "search_notes",
"description": "Search CRM notes for this lead by substring.",
"parameters": {"type": "object", "properties": {
"lead_id": {"type": "string"},
"query": {"type": "string"}}, "required": ["lead_id", "query"]}}},
{"type": "function", "function": {
"name": "submit_decision",
"description": "Terminal tool. Records the routing decision and ends the run.",
"parameters": {"type": "object", "properties": {
"lead_id": {"type": "string"},
"route": {"type": "string", "enum": ["reject", "nurture", "book_meeting"]},
"reason": {"type": "string"},
"confidence": {"type": "number"}},
"required": ["lead_id", "route", "reason", "confidence"]}}},
]
LEAD_FIELDS = ["id", "email", "company", "employees", "deal_size_usd", "source"]
def init_db():
conn = sqlite3.connect(DB_PATH)
conn.executescript(SCHEMA)
conn.executemany("INSERT OR IGNORE INTO leads VALUES (?,?,?,?,?,?)", SEED_LEADS)
if conn.execute("SELECT count(*) FROM notes").fetchone()[0] == 0:
conn.executemany("INSERT INTO notes VALUES (?,?)", SEED_NOTES)
conn.commit()
return conn
def get_lead(conn, lead_id):
row = conn.execute(
"SELECT id, email, company, employees, deal_size_usd, source "
"FROM leads WHERE id = ?", (lead_id,)).fetchone()
if row is None:
return {"error": "no lead with id " + str(lead_id)}
return dict(zip(LEAD_FIELDS, row))
def search_notes(conn, lead_id, query):
rows = conn.execute(
"SELECT note FROM notes WHERE lead_id = ? AND note LIKE ?",
(lead_id, "%" + query + "%")).fetchall()
return {"notes": [r[0] for r in rows]}
def run(lead_id):
conn = init_db()
client = OpenAI() # reads OPENAI_API_KEY; retries twice by default
now = datetime.now(timezone.utc).isoformat(timespec="seconds")
cur = conn.execute(
"INSERT INTO runs (lead_id, model, steps, in_tokens, out_tokens, "
"cost_usd, status, started_at) VALUES (?,?,0,0,0,0,'running',?)",
(lead_id, MODEL, now))
run_id = cur.lastrowid
conn.commit()
messages = [{"role": "system", "content": SYSTEM},
{"role": "user", "content": "Qualify lead " + lead_id + "."}]
in_tok = out_tok = steps = 0
status = "capped"
decision = None
decision_status = None
while steps < MAX_STEPS:
steps += 1
resp = client.chat.completions.create(
model=MODEL, messages=messages, tools=TOOLS,
tool_choice="auto", temperature=0)
in_tok += resp.usage.prompt_tokens
out_tok += resp.usage.completion_tokens
msg = resp.choices[0].message
calls = msg.tool_calls or []
print("step %d tool_calls=%s" % (steps, [c.function.name for c in calls]),
file=sys.stderr)
assistant = {"role": "assistant", "content": msg.content or ""}
if calls:
assistant["tool_calls"] = [
{"id": c.id, "type": "function",
"function": {"name": c.function.name,
"arguments": c.function.arguments}} for c in calls]
messages.append(assistant)
if not calls:
status = "no_tool_call"
break
for call in calls:
name = call.function.name
args = json.loads(call.function.arguments or "{}")
if name == "get_lead":
result = get_lead(conn, args.get("lead_id", lead_id))
elif name == "search_notes":
result = search_notes(conn, args.get("lead_id", lead_id),
args.get("query", ""))
elif name == "submit_decision":
decision = args
status = "decided"
result = {"accepted": True}
else:
result = {"error": "unknown tool " + name}
messages.append({"role": "tool", "tool_call_id": call.id,
"content": json.dumps(result)})
if status == "decided":
break
route = decision.get("route") if decision else None
if decision:
lead = get_lead(conn, lead_id)
big = lead.get("deal_size_usd", 0) >= APPROVAL_THRESHOLD_USD
decision_status = "needs_approval" if (route == "book_meeting" and big) \
else "auto_approved"
conn.execute(
"INSERT INTO decisions VALUES (?,?,?,?,?,?,?)",
(run_id, lead_id, route, decision.get("reason", ""),
float(decision.get("confidence", 0)), decision_status,
datetime.now(timezone.utc).isoformat(timespec="seconds")))
cost = in_tok / 1e6 * USD_PER_1M_IN + out_tok / 1e6 * USD_PER_1M_OUT
conn.execute(
"UPDATE runs SET steps=?, in_tokens=?, out_tokens=?, cost_usd=?, "
"status=? WHERE id=?",
(steps, in_tok, out_tok, round(cost, 6), status, run_id))
conn.commit()
out = {"run_id": run_id, "lead_id": lead_id, "steps": steps, "status": status,
"route": route, "decision_status": decision_status,
"in_tokens": in_tok, "out_tokens": out_tok, "cost_usd": round(cost, 6)}
print(json.dumps(out, indent=2))
return out
if __name__ == "__main__":
run(sys.argv[1] if len(sys.argv) > 1 else "L-1002")
Every address in the seed data sits on a reserved documentation domain — .example and .test, both set aside for exactly this purpose by RFC 2606 in June 1999 and reaffirmed in RFC 6761 (February 2013) — so nothing in this file can email a real person if you later bolt a send tool onto it.
What the three control points actually do
| Control | Where it lives | What it prevents | How you verify it |
|---|---|---|---|
| Step cap | while steps < MAX_STEPS in Python | A loop that calls get_lead forever and bills every call | MAX_STEPS=1 run returns status capped |
| Cost ledger | runs table, written on every exit path | Not knowing what a decision cost until the invoice | select sum(cost_usd) from runs |
| Approval gate | decision_status set after the model is done | An agent booking time on a 90,000 dollar deal unsupervised | select status from decisions |
The ledger only earns its keep once you read the shape of the numbers in it. A three-step run on a small model typically accumulates something on the order of 3,000 input tokens — the system prompt, the three tool schemas, and the growing tool-result history, all re-sent on every call — against roughly 200 output tokens. At the $0.15 and $0.60 per million used in step 2, that is $0.00045 in plus $0.00012 out: about $0.00057 a decision, or $5.70 for ten thousand leads. The ratio is the lesson. Because the whole transcript is resent each step, input tokens grow with the square of the step count, so a worker that drifts from three steps to six costs closer to four times as much, not twice. That is the arithmetic the step cap is defending.
The cap is in code, not in the system prompt, because a prompt is a request and a while condition is not. Same reason the approval threshold is compared against the database field deal_size_usd rather than against the model's own estimate of deal size: the gate must not read an input the agent can write.
One thing the cap does not bound is tool executions. The Chat Completions API can return several tool_calls in a single assistant message, and this loop runs all of them before incrementing steps — so six steps can mean more than six tool invocations. If a tool is expensive or writes anything, count executions separately rather than inferring them from the step column.
Note which exit paths write a cost row. All of them. capped, no_tool_call, and decided each fall through to the same UPDATE, and that is the only way the ledger stays honest — a run that failed still spent tokens. The broader version of this argument is set out in cost per loop: the unit of capacity in an agent-run business is the measured cost of one loop, not the headcount it nominally replaces.
The gate column is also the cheapest thing that satisfies an auditor. Oversight requirements have converged on the same shape from two directions: NIST's AI Risk Management Framework 1.0, published 26 January 2023, treats documented human oversight as a core governance function, and Article 14 of the EU AI Act, in force since 1 August 2024, requires effective human oversight measures for high-risk systems. A decision_status of needs_approval, with a timestamp and a run ID beside it, is that requirement expressed as one column.
When it doesn't work
KeyError: 'USD_PER_1M_IN' — thrown at import, before any API call. You skipped step 2. Export both price variables from the pricing page. A cost ledger that silently defaults to zero is worse than a crash on line 20.
openai.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 — the key is missing from the shell you are actually running in. export OPENAI_API_KEY=sk-... applies only to that shell session. A new terminal tab needs it again.
openai.RateLimitError: Error code: 429 — a per-minute request or token limit, almost always from running the whole queue in a loop. The SDK retries twice by default, so a 429 that reaches your terminal already failed three times. Lower concurrency, or raise it: OpenAI(max_retries=5). Tiers are in OpenAI's rate limits guide.
sqlite3.OperationalError: database is locked — appears the moment you run several workers at once against one company.db, because SQLite allows one writer at a time. Turn on write-ahead logging so readers and a writer can coexist: add conn.execute("PRAGMA journal_mode=WAL") right after sqlite3.connect (WAL docs). WAL has been available since SQLite 3.7.0 in July 2010, so any Python 3.9+ build has it; confirm with python3 -c "import sqlite3; print(sqlite3.sqlite_version)". Past a handful of concurrent workers, stop patching and move the ledger to Postgres.
Status comes back no_tool_call — the model replied in prose instead of calling submit_decision. The run is recorded and no decision row exists, which is correct. Tightening the prompt is the weaker fix; it works until the model has a bad day. Force the terminal call instead: set tool_choice to submit_decision once steps reaches MAX_STEPS - 1.
The same lead routes differently on two runs — temperature=0 narrows the sampling distribution but is not a determinism guarantee, and OpenAI documents outputs as non-deterministic even at zero. Do not build a test suite that asserts on a specific route; assert on the invariants instead — that steps never exceeds MAX_STEPS, that every run has exactly one runs row, and that no book_meeting over $25,000 is ever stamped auto_approved.
The second worker is the company
One worker is a script. The company starts when you clone it.
| Function | Worker's single job | Terminal tool | Gate |
|---|---|---|---|
| Inbound qualification | Route one lead | submit_decision | Deal size over threshold |
| Renewal risk | Flag one account | submit_flag | Any flag that triggers an outreach email |
| Invoice matching | Match one invoice to one PO | submit_match | Amount mismatch over a set tolerance |
| Support triage | Tag one ticket, draft one reply | submit_draft | Replies that promise a refund or a date |
Each gets its own MAX_STEPS, its own rows in runs, and its own answer to one question: what is the worst thing this can do if the model is confidently wrong? For the lead worker, the worst case is a wasted calendar hour. For anything touching money, the worst case is money — which is why I would not hand an agent spend authority at this stage of the build. The mechanics of agents that actually pay are a separate problem, and the infrastructure under them is the easy half.
I took Metadata.io from zero to 15 million in ARR on 50 million raised, with six patents in AI-driven marketing. The interesting work was never the prompt. It is the while condition, the price variables with no defaults, and the column that says needs_approval.
Run select status, count(*) from runs group by status after a week. If capped is climbing, your tools are too weak and the model is flailing. If no_tool_call is climbing, your prompt has drifted away from your schema. The ledger tells you which, and it tells you before the invoice does.
Sources
- OpenAI API keys — Where to get the OPENAI_API_KEY the script reads
- OpenAI API pricing — Source for the per-million input/output token prices the reader exports; prices change, so the script takes them as env vars
- OpenAI function calling guide — Tool-call request/response shape used in the loop, including tool_call_id
- openai-python repository — SDK version 1.x, automatic retries with a default of 2, and client configuration
- OpenAI rate limits guide — 429 error behaviour referenced in the failure section
- Python sqlite3 documentation — Standard-library database used for the ledger; no install step needed
- SQLite Write-Ahead Logging — WAL mode as the fix for 'database is locked' under concurrent workers
- Anthropic — Building effective agents — Guidance to start with the simplest composable pattern and add complexity only when it improves outcomes
- OWASP GenAI — LLM Top 10 — Unbounded consumption is a documented top-ten risk class, which is why the step cap lives outside the model
- Metadata.io — Company referenced in the author's biography