Gil Allouche
← All writing
TutorialRunning a company with AI

Build a billable AI agent and the ledger that bills for it

A bounded research agent in one Python file: step cap, fetch budget, host allowlist, and a SQLite ledger with the token cost of every run.

November 28, 2026·Gil Allouche·13 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 at the end

One Python file, around 130 lines. It takes a company domain, researches it under a hard ceiling of 8 model turns and 5 HTTP requests, writes a markdown brief into briefs/, and appends one row to a SQLite table holding the token counts and dollar cost of that specific run. Budget an hour if Python is already on the machine. Most of that hour is reading output, not typing.

This is the smallest thing that is actually a business: a service that produces an artifact a customer will pay for, with a cost-per-unit you can measure before you quote a price.

You need Python 3.11 or newer, a terminal, and an OpenAI API key with credit on the account — platform.openai.com/api-keys. Python 3.11 shipped in October 2022, so any currently supported release qualifies; the file uses nothing exotic beyond three third-party packages (openai, requests, beautifulsoup4). Pick one company domain you would genuinely research for a client; a made-up target tells you nothing about whether the brief is any good. The sqlite3 command-line tool makes the ledger easier to read, but it is optional — Python's sqlite3 module has shipped in the standard library since Python 2.5 in 2006, so the ledger needs no server, no migration framework and no extra install.

The three limits that make it runnable unattended

Unbounded Consumption is LLM10:2025 in the OWASP Top 10 for Large Language Model Applications, the category that absorbed the 2023 list's LLM04 Model Denial of Service. The loop below cannot run away, because three limits live in Python rather than in the prompt. A model asked nicely to stop after eight turns is a model that will stop after eight turns most of the time. A while steps < STEP_CAP has no other option.

GuardValue in the fileWhat it preventsWhat you see when it trips
Step capSTEP_CAP = 8A loop that never emits a final answerstop=step_cap billable=0
Fetch budgetFETCH_BUDGET = 5Crawling an entire site on your cardERROR: fetch budget exhausted for this run
Host allowlisttarget domain + subdomainsFollowing an off-site link into anythingERROR: host '...' is outside the allowlist
Page truncationPAGE_CHARS = 12_000One long page filling the context windowThe brief ignores the tail of a page

Those four numbers interact, and the arithmetic is worth doing once. Five fetches at 12,000 characters each is at most 60,000 characters of page text, which at the rough English ratio of four characters per token is around 15,000 tokens — comfortably inside the 128,000-token context window of gpt-4o-mini, whose 16,384-token output limit never comes close to binding for a brief of two or three thousand characters. The headroom is deliberate: the ceiling you hit first should be the step cap you picked, not a context-length error you did not.

One thing the allowlist does not do is read robots.txt. The Robots Exclusion Protocol was standardised as RFC 9309 in September 2022; five requests against a company's own pricing and about pages sits inside ordinary crawling etiquette, but if you widen this beyond a single target per run, fetch and honour /robots.txt before the first page and keep a User-Agent string that identifies you.

One run: a step cap outside the model decides whether the run is billableRequestStep capmax 8 turnsModel turntool_calls?fetch_pageBrief writtenledger billable=1ledger billable=0tool result, loop backno tool callscap hitinvoicednot invoiced

Who picks the next step is the whole distinction between a script and an agent — I wrote about that boundary in autonomous agents, defined by who chooses the next step. Here the model picks which page to fetch. Python decides how many times it gets to pick: eight.

The agent, in one file

Save this as agent.py. It runs as written. The two price variables default to 0, which makes the cost column zero until you fill them in from the OpenAI pricing page — prices change, so they belong in the environment, not in the source.

#!/usr/bin/env python3
"""brief-agent: one bounded worker that produces one billable artifact.

    python agent.py example.com acct_001

Writes briefs/<domain>.md and one row in ledger.db.
"""
import json
import os
import sqlite3
import sys
import time
from urllib.parse import urlparse

import requests
from bs4 import BeautifulSoup
from openai import OpenAI

MODEL = "gpt-4o-mini"
STEP_CAP = 8          # model turns per run, enforced here and not by the prompt
FETCH_BUDGET = 5      # outbound HTTP calls per run
PAGE_CHARS = 12_000   # per-page truncation before text reaches the context window
PRICE_IN = float(os.environ.get("PRICE_IN_PER_MTOK", "0"))
PRICE_OUT = float(os.environ.get("PRICE_OUT_PER_MTOK", "0"))

SYSTEM = """You write short company briefs for a sales team.
Work only from pages you fetch. Never guess a fact.
Start at https://{domain}/ and follow at most a few links on that same domain
(pricing, about, customers, careers).
When you have enough, reply with markdown only, in these sections:
## What they sell
## Who they sell to
## Signals (hiring, pricing, launches)
## Open questions
Mark anything you could not verify as "not found on site"."""

TOOLS = [{
    "type": "function",
    "function": {
        "name": "fetch_page",
        "description": "Fetch one URL on the target domain and return its visible text.",
        "parameters": {
            "type": "object",
            "properties": {"url": {"type": "string"}},
            "required": ["url"],
            "additionalProperties": False,
        },
    },
}]


class Budget:
    def __init__(self, fetches, host_suffix):
        self.fetches = fetches
        self.host_suffix = host_suffix


def fetch_page(url, budget):
    if budget.fetches <= 0:
        return "ERROR: fetch budget exhausted for this run"
    host = (urlparse(url).hostname or "").lower()
    if not (host == budget.host_suffix or host.endswith("." + budget.host_suffix)):
        return f"ERROR: host {host!r} is outside the allowlist ({budget.host_suffix})"
    budget.fetches -= 1
    try:
        r = requests.get(url, timeout=10, headers={"User-Agent": "brief-agent/0.1"})
    except requests.RequestException as e:
        return f"ERROR: {type(e).__name__}"
    if r.status_code != 200:
        return f"ERROR: HTTP {r.status_code}"
    text = BeautifulSoup(r.text, "html.parser").get_text(" ", strip=True)
    return text[:PAGE_CHARS]


def run(domain, account):
    budget = Budget(FETCH_BUDGET, domain.lower())
    client = OpenAI()  # reads OPENAI_API_KEY from the environment
    messages = [
        {"role": "system", "content": SYSTEM.format(domain=domain)},
        {"role": "user", "content": f"Company domain: {domain}"},
    ]
    in_tok = out_tok = steps = 0
    started = time.monotonic()
    brief, stop = "", "step_cap"

    while steps < STEP_CAP:
        steps += 1
        resp = client.chat.completions.create(
            model=MODEL, messages=messages, tools=TOOLS, temperature=0.2
        )
        in_tok += resp.usage.prompt_tokens
        out_tok += resp.usage.completion_tokens
        msg = resp.choices[0].message

        entry = {"role": "assistant", "content": msg.content}
        if msg.tool_calls:
            entry["tool_calls"] = [
                {"id": c.id, "type": "function",
                 "function": {"name": c.function.name,
                              "arguments": c.function.arguments}}
                for c in msg.tool_calls
            ]
        messages.append(entry)

        if not msg.tool_calls:
            brief, stop = (msg.content or ""), "complete"
            break

        for call in msg.tool_calls:
            args = json.loads(call.function.arguments or "{}")
            messages.append({
                "role": "tool",
                "tool_call_id": call.id,
                "content": fetch_page(args.get("url", ""), budget),
            })

    cost = in_tok / 1e6 * PRICE_IN + out_tok / 1e6 * PRICE_OUT
    return {
        "account": account,
        "domain": domain,
        "steps": steps,
        "input_tokens": in_tok,
        "output_tokens": out_tok,
        "cost_usd": round(cost, 6),
        "seconds": round(time.monotonic() - started, 1),
        "stop_reason": stop,
        "billable": int(stop == "complete" and len(brief) > 400),
        "brief": brief,
    }


DDL = """CREATE TABLE IF NOT EXISTS runs (
  id INTEGER PRIMARY KEY,
  ts TEXT NOT NULL DEFAULT (datetime('now')),
  account TEXT NOT NULL,
  domain TEXT NOT NULL,
  steps INTEGER NOT NULL,
  input_tokens INTEGER NOT NULL,
  output_tokens INTEGER NOT NULL,
  cost_usd REAL NOT NULL,
  seconds REAL NOT NULL,
  stop_reason TEXT NOT NULL,
  billable INTEGER NOT NULL
)"""

COLS = ("account", "domain", "steps", "input_tokens", "output_tokens",
        "cost_usd", "seconds", "stop_reason", "billable")


def record(row):
    db = sqlite3.connect("ledger.db")
    db.execute(DDL)
    db.execute(
        "INSERT INTO runs (account, domain, steps, input_tokens, output_tokens,"
        " cost_usd, seconds, stop_reason, billable) VALUES"
        " (:account, :domain, :steps, :input_tokens, :output_tokens,"
        " :cost_usd, :seconds, :stop_reason, :billable)",
        {k: row[k] for k in COLS},
    )
    db.commit()
    db.close()


if __name__ == "__main__":
    if len(sys.argv) != 3:
        sys.exit("usage: python agent.py <domain> <account_id>")
    row = run(sys.argv[1], sys.argv[2])
    record(row)
    os.makedirs("briefs", exist_ok=True)
    path = os.path.join("briefs", f"{row['domain']}.md")
    with open(path, "w", encoding="utf-8") as f:
        f.write(row["brief"])
    print(
        f"{row['domain']} steps={row['steps']} in={row['input_tokens']} "
        f"out={row['output_tokens']} cost=${row['cost_usd']:.4f} "
        f"{row['seconds']}s stop={row['stop_reason']} billable={row['billable']}"
    )
    print(f"wrote {path} ({len(row['brief'])} chars)")

Three things in there are not stylistic. The assistant message is rebuilt field by field instead of dumping the SDK's model object back into the history — explicit fields are the ones the API documents, and you avoid shipping whatever new optional field the SDK added last release. The second: every tool_call gets exactly one tool reply appended, failures included. The error string goes back to the model as the tool result. It reads ERROR: host '...' is outside the allowlist and picks a different page.

The third is the explicit timeout=10 on the outbound fetch. requests sets no default timeout and will wait indefinitely for a server that accepts a connection and then says nothing, which is exactly the failure mode an unattended run cannot survive. The OpenAI SDK is the opposite case: it ships with a 10-minute request timeout and retries connection errors and 429s twice by default, so a transient API failure costs wall-clock seconds rather than the whole run. That default also means steps in the ledger counts model turns, not HTTP requests to the API — the two diverge whenever a retry fires.

Running it

  1. Create the environment and install three packages: python3 -m venv .venv && source .venv/bin/activate, then pip install openai requests beautifulsoup4. You should see a final line beginning Successfully installed that names openai, requests and beautifulsoup4 with version numbers.
  2. Create a key at platform.openai.com/api-keys and export it: export OPENAI_API_KEY=sk-.... Confirm the shell actually has it with python -c "import os; print(bool(os.environ.get('OPENAI_API_KEY')))" — it should print True, not False.
  3. Save the file above as agent.py in the same directory. Check it parses before you spend a token: python -c "import agent" should print nothing at all.
  4. Smoke test against example.com, reserved for documentation by RFC 2606 since 1999 and listed as special-use in RFC 6761: python agent.py example.com acct_demo. That domain serves one short real page, so expect a thin brief where most sections say "not found on site" and a summary line ending stop=complete billable=0 — the brief is under 400 characters. The agent reporting absence instead of inventing a customer list is the behaviour you are testing for.
  5. Prove the cap works. Edit STEP_CAP = 1, re-run the same command, and the summary line ends stop=step_cap billable=0. One model turn, no final answer, no row you would invoice. Set it back to 8.
  6. Put the current per-million-token prices from the OpenAI pricing page into the environment: export PRICE_IN_PER_MTOK=0.00 PRICE_OUT_PER_MTOK=0.00 with the real figures substituted. Re-run and the cost=$ field in the summary line becomes non-zero.
  7. Run it against a domain you would actually bill for: python agent.py yourprospect.test acct_001 with a real target substituted — .test is also reserved by RFC 2606 and will never resolve. You want stop=complete billable=1 and a file in briefs/ with all four sections filled in.
  8. Read the ledger: sqlite3 ledger.db "select account, count(*), round(sum(cost_usd),4) from runs where billable=1 group by account". One row per account, with your cost of goods for the month so far.

The summary line has this shape. Your token counts, seconds and cost will be different — the fields are the point, not the values:

acme.example steps=4 in=38412 out=1890 cost=$0.0071 19.3s stop=complete billable=1
wrote briefs/acme.example.md (2104 chars)

The ledger is the business

Run that twenty times and you know something most people selling "AI services" do not know about their own offering: what one unit costs to produce, and how often it fails to produce anything.

SELECT stop_reason,
       COUNT(*)                     AS runs,
       ROUND(AVG(cost_usd), 4)      AS avg_cost,
       ROUND(SUM(cost_usd), 4)      AS total_cost,
       ROUND(AVG(steps), 1)         AS avg_steps
FROM runs
WHERE ts >= date('now', 'start of month')
GROUP BY stop_reason;

Two numbers come out of that. Average cost on complete runs is your floor price per brief. Total cost across all rows, divided by the count of billable=1 rows, is your real cost per delivered brief — failed runs cost money and produce nothing, so they belong in the denominator of the thing you sell, not in a separate column you ignore. Worked through with the sample line above: 20 runs at an average of $0.0071 is $0.142 of spend, and if 17 of them came back billable=1, the true cost per delivered brief is $0.0084 — roughly 18% above the headline average. At a 50% failure rate it doubles.

Two caveats on the SQL. SQLite's datetime('now') writes UTC, so date('now', 'start of month') cuts the month at UTC midnight, which matters only if you later reconcile against an invoice stated in local time. And the ledger is an estimate assembled from the usage block of each response; treat it as your internal unit economics and check it against the billing dashboard once a month rather than trusting it to the cent.

Then price it. Not cost-plus-a-margin — price against what the buyer pays today for the same artifact, which for a hand-written prospect brief is a chunk of an SDR's hour. The gap between that and your avg_cost is the entire margin of the business, and it is the thing you have to defend. Meter it per run, not per seat; the mechanics are in selling AI agents as SaaS is a metering and margin problem.

Keep billable as a column the code sets, not a judgement you make later. A capped run with no artifact is not a thing you charge for, and the first time a client audits your invoice against their inbox, that column is the reason the conversation is short.

When it doesn't work

openai.AuthenticationError: Error code: 401 — the key is missing, revoked, or belongs to a different project than the one you think. Almost always it is a new terminal tab without the export. Run the python -c check from step 2; if it prints False, export the key again in this shell.

openai.RateLimitError: Error code: 429 with insufficient_quota in the body — this one is not a rate limit despite the class name. The account has no usable credit. Add credit in billing. The key itself is fine, and retrying will not help — note that the SDK has already retried it twice by the time you see the exception.

openai.BadRequestError mentioning tool_call_id or an assistant message with tool_calls — you broke the pairing rule. The API requires one tool-role message for every entry in tool_calls, appended before the next request. This happens the moment you add a second tool and return early from the loop on an exception. Append the error string as the tool result instead of returning.

Every step comes back ERROR: host '...' is outside the allowlist, then stop=step_cap — the model wants a source off the target domain, usually a directory or a press release. That is the allowlist doing its job. Take the thinner brief, or widen the list to specific hosts you have decided to trust. Do not remove the check.

sqlite3.OperationalError: table runs has no column named ... — you edited DDL after ledger.db already existed, and CREATE TABLE IF NOT EXISTS silently did nothing. During development, delete ledger.db and re-run. Once you have rows you care about, use ALTER TABLE runs ADD COLUMN.

What I would not hand to this agent yet

Spend authority. The agent above reads pages and writes a file; the worst outcome is a wasted API call and a brief that says "not found on site". Give the same loop a payment method or a send button and the worst outcome changes category entirely — a bounded worker that can only produce a draft is a different risk object from one that can transact, which is why agentic commerce is a separate build with separate controls.

Also: anything where being wrong is invisible. The brief is reviewable in ninety seconds by the person who requested it, which is what makes it safe to ship in week one. Start with the work where a human reads the output anyway, bill for that, and widen scope only where the ledger shows the failure rate is low enough to stand behind. The next worker you add should be chosen the same way — one bounded job, one artifact, one row per run, as in how to build an AI company, starting with one bounded worker.

Sources

  1. OpenAI — API keys — Where the reader gets the OPENAI_API_KEY the code requires
  2. OpenAI — Function calling guide — Tool schema shape, tool_calls, and the required tool-role reply per call
  3. OpenAI — Chat completion object — usage.prompt_tokens and usage.completion_tokens are returned on every response
  4. OpenAI — API pricing — Per-million-token prices the reader puts into PRICE_IN_PER_MTOK / PRICE_OUT_PER_MTOK
  5. OpenAI — Rate limits — 429 responses, including insufficient_quota when there is no credit on the account
  6. Requests — advanced usage, timeouts — requests.get has no default timeout; the timeout argument is required to bound a fetch
  7. Python — sqlite3 module — SQLite ships with Python, so the ledger needs no extra service
  8. IANA — Reserved domains — example.com is reserved for documentation and serves a real page, which makes it a safe smoke test
  9. OWASP — Top 10 for LLM Applications — Unbounded consumption is a documented risk class for LLM applications, not a hypothetical
  10. openai/openai-python — The SDK installed in step 1 and the exception classes named in the troubleshooting section

Related