Start an AI automation business with one agent you can bill
Build a bounded intake agent that triages inbound submissions, logs tokens per run, and stops itself — then work out what to charge per run.
What you will have running
About 120 lines of Python in one file. It takes an inbound form submission, looks the sender's domain up in your account list, drafts a reply, decides a tier, and appends a run record — token counts included — to runs.jsonl. Budget an evening if you have never called the Messages API, less if you have.
It is not a demo. It writes an auditable record for every run, it stops itself at a fixed number of model calls, and the token counts in that record are the input to your price.
Prerequisites:
- Python 3.10 or newer, and a terminal.
- An Anthropic API key from console.anthropic.com/settings/keys, with a few dollars of credit on the account.
- A file listing accounts you already have — any JSON keyed by email domain will do.
- One job a human currently does badly, that someone has already agreed to pay for.
That last one is the real prerequisite.
Pick the job before you pick the stack
An AI automation business is not a stack. It is one job, with a named buyer, measured in units someone can count. Inbound form triage is the right first job: the unit is obvious — one submission in, one decision out — and when it gets a call wrong, the wrongness shows up in a queue a human is already reading.
I spent years at Metadata.io selling software that ran campaigns on customers' behalf, and the pattern that worked never changed: take a task with a countable unit, do it at a lower cost per unit, show the record. The record is the product as much as the output is.
"Handle our support" is not a job. It is four jobs, a staffing problem, and a complaints queue, and nobody will sign a per-unit price against it. Neither is "do our marketing." Classify this, extract that, reconcile these two lists, draft this reply for a human to send — those are jobs. If you cannot describe the unit in six words, you cannot invoice for it.
More on scoping the first worker in how to build an AI company, starting with one bounded worker, and on why the economics are a per-loop question in the role of AI in entrepreneurship is cost per loop.
Build it
- Make the project and a virtualenv:
mkdir intake-agent && cd intake-agent && python3 -m venv .venv && source .venv/bin/activate. Your prompt now starts with(.venv). - Install the SDK:
pip install anthropic. The last line of output startsSuccessfully installed anthropic-followed by a version, plus its dependencies (httpx,pydantic, and others). - Create a key at console.anthropic.com/settings/keys and export it:
export ANTHROPIC_API_KEY=sk-ant-.... Check the client can see it:python -c "import anthropic; print(bool(anthropic.Anthropic().api_key))"printsTrue. - Write
accounts.json— two entries is enough to test both branches. Use the documentation domains for now:{"example.com": {"account": "Example Corp", "owner": "dana@vendor.example"}, "example.net": {"account": "Example Net", "owner": "sam@vendor.example"}}. Confirm it parses:python -m json.tool accounts.jsonechoes it back indented. - Save the file in the next section as
triage.py. Nothing to see yet;python -c "import ast;ast.parse(open('triage.py').read())"exits silently if the syntax is good. - Run a submission from a known customer:
python triage.py '{"email":"ops@example.com","message":"SSO broke after the Tuesday release. Who do we page?"}'. You get a JSON record with"tier": "existing_customer"and"owner": "dana@vendor.example". - Run one that is not:
python triage.py '{"email":"hello@unknown.example","message":"BUY FOLLOWERS CHEAP"}'. You get"tier": "spam"and"owner": "unassigned". - Check the ledger:
wc -l runs.jsonlprints2 runs.jsonl. Every run from here on appends one line, whether it succeeded or hit the cap.
triage.py, complete
Two tools. One loop. The cap is a Python counter, not an instruction.
#!/usr/bin/env python3
"""triage.py - bounded intake agent. One submission in, one filed decision out."""
import json
import pathlib
import sys
import time
from anthropic import Anthropic
MODEL = "claude-sonnet-4-5"
MAX_STEPS = 6 # model calls per run, enforced here
RUN_LOG = pathlib.Path("runs.jsonl")
ACCOUNTS = pathlib.Path("accounts.json")
client = Anthropic() # reads ANTHROPIC_API_KEY from the environment
TOOLS = [
{
"name": "lookup_account",
"description": "Look up a company by email domain in the customer account "
"list. Returns null if the domain is not a customer.",
"input_schema": {
"type": "object",
"properties": {
"domain": {"type": "string", "description": "e.g. example.com"}
},
"required": ["domain"],
},
},
{
"name": "file_triage",
"description": "File the final decision. Call this exactly once, last.",
"input_schema": {
"type": "object",
"properties": {
"tier": {
"type": "string",
"enum": ["existing_customer", "qualified", "spam"],
},
"owner": {"type": "string"},
"reply": {"type": "string", "description": "Draft reply, under 120 words."},
},
"required": ["tier", "owner", "reply"],
},
},
]
SYSTEM = (
"You triage inbound form submissions for a B2B software company. "
"Look up the sender's email domain with lookup_account exactly once, then call "
"file_triage exactly once. tier=existing_customer if the lookup returned an account; "
"spam if the message contains no business request; otherwise qualified. "
"owner is the owner field from the lookup, or 'unassigned'. "
"Never state a fact about the sender that is not in the submission or the lookup."
)
def lookup_account(domain):
accounts = json.loads(ACCOUNTS.read_text())
return accounts.get(domain)
def run(submission):
messages = [{"role": "user", "content": json.dumps(submission)}]
usage = {"input_tokens": 0, "output_tokens": 0}
filed = None
steps = 0
while steps < MAX_STEPS and filed is None:
steps += 1
resp = client.messages.create(
model=MODEL,
max_tokens=1024,
system=SYSTEM,
tools=TOOLS,
messages=messages,
)
usage["input_tokens"] += resp.usage.input_tokens
usage["output_tokens"] += resp.usage.output_tokens
messages.append({"role": "assistant", "content": resp.content})
if resp.stop_reason != "tool_use":
break
results = []
for block in resp.content:
if block.type != "tool_use":
continue
if block.name == "lookup_account":
out = lookup_account(block.input.get("domain", ""))
elif block.name == "file_triage":
filed = block.input
out = {"ok": True}
else:
out = {"error": "unknown tool: " + block.name}
results.append({
"type": "tool_result",
"tool_use_id": block.id,
"content": json.dumps(out),
})
messages.append({"role": "user", "content": results})
if filed is None:
filed = {
"tier": "needs_human",
"owner": "unassigned",
"reply": "",
"error": "no decision after %d model calls" % steps,
}
record = {
"ts": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
"email": submission.get("email", ""),
"steps": steps,
"usage": usage,
"result": filed,
}
with RUN_LOG.open("a") as f:
f.write(json.dumps(record) + "\n")
return record
if __name__ == "__main__":
print(json.dumps(run(json.loads(sys.argv[1])), indent=2))
A successful run prints a record shaped like this. Your timestamp and token counts will differ — these are the fields, not a measurement:
{
"ts": "2025-01-01T00:00:00Z",
"email": "ops@example.com",
"steps": 2,
"usage": { "input_tokens": 0, "output_tokens": 0 },
"result": {
"tier": "existing_customer",
"owner": "dana@vendor.example",
"reply": "Thanks for flagging this - routing to your account team now."
}
}
steps: 2 is the shape to expect: one call to request the lookup, one to file the decision. The usage fields come straight off the API response, which reports input_tokens and output_tokens on every message.
Where the step cap goes
The model does not decide when to stop. The while steps < MAX_STEPS line does, and it sits in code the model cannot write to.
Putting "stop after six steps" in the system prompt is not a cap. It is a suggestion, and the model drops it the moment a tool result looks wrong to it — it re-calls the tool, reads the same result, calls again. Unbounded tool-calling loops are the most common way these systems fail in production, and the only thing between that loop and your bill is a counter. Anthropic's own engineering guidance on agents points the same direction: keep the loop simple, put the guardrails outside the model.
When the cap trips, the run does not throw. It files tier: needs_human with an error string and still writes a line to runs.jsonl. That matters commercially: a cap hit is a run you can count, grep, and refund. A crash is a run you cannot.
Raise MAX_STEPS to make a stubborn case pass and you have moved the bug, not fixed it. Tighten the tool schema or the system prompt instead.
What one run costs
Every line in runs.jsonl carries the two numbers you need. The rest is arithmetic against the published per-million-token rates — Claude Sonnet 4.5 is listed at $3 per million input tokens and $15 per million output tokens on Anthropic's pricing page. Check the page before you quote anyone. It changes.
Take a two-step run that totals 2,000 input and 400 output tokens. Input: 2,000 ÷ 1,000,000 × $3 = $0.006. Output: 400 ÷ 1,000,000 × $15 = $0.006. $0.012 for the run.
One mechanic catches people out. Input tokens are charged on every call, and each call resends the whole conversation so far, so a four-step run costs far more than four times the first call's input. Prompt caching exists specifically to cut the cost of those re-sent prefixes; read the docs before you assume a longer loop is linear.
Assuming $0.012 a run and a price of $0.50 a run — a price you will have to test, not take from me:
| Monthly runs | API cost | Billed | Difference |
|---|---|---|---|
| 500 | $6.00 | $250 | $244 |
| 2,000 | $24.00 | $1,000 | $976 |
| 10,000 | $120.00 | $5,000 | $4,880 |
The API line is the smallest line in that business. Your real costs are the human reviewing needs_human, the integration work per customer, and the hours lost when a schema changes upstream. Price the contract, not the tokens.
When it doesn't work
No key, or the wrong one. If ANTHROPIC_API_KEY is unset, the SDK raises on client construction, before any network call: TypeError: Could not resolve authentication method. Expected either api_key or auth_token to be set. If the key exists but is wrong, you get it from the API instead — anthropic.AuthenticationError: Error code: 401 with 'message': 'invalid x-api-key'. Fix: re-export the key in the same shell you are running in, and confirm with the one-liner in step 3. A key exported in another tab is the usual cause.
A tool_use block with no matching tool_result. If you break out of the loop after the model asked for a tool but before you append the results, the next request is malformed and you get anthropic.BadRequestError: Error code: 400 with 'message': 'messages.N: Each tool_useblock must have a correspondingtool_result block in the next message'. Every tool_use needs an answer, including ones you do not recognise — that is why the loop above returns {"error": "unknown tool: ..."} rather than skipping.
Model ID not found. Aliases get retired. A stale one produces anthropic.NotFoundError: Error code: 404 with 'type': 'not_found_error' naming the model string you sent. Fix: pull the current IDs from the model overview and pin a dated version like claude-sonnet-4-5-20250929 once you have a paying customer, so a retired alias cannot change your output overnight.
And the one that is not an error: records with "tier": "needs_human". Grep for them daily — grep -c needs_human runs.jsonl — because that count is your quality metric and the first thing a customer will ask about.
What you can actually charge for
Two things make this billable rather than a toy: the run record and the fallback. The record means you can invoice per unit and defend the invoice. The fallback means a bad run produces a routed ticket instead of a silent wrong answer.
Metering per run is a solved problem — Stripe's usage-based billing takes meter events keyed to a customer, so one runs.jsonl line becomes one billable event. Do that before you build a dashboard.
What I would not do yet: give the agent authority to spend money or send mail unsupervised. Drafting a reply and filing a decision is a different risk class from pressing send, and the second one needs a different set of controls — see agentic commerce means the agent pays, not just recommends and self-hosting an agent framework is the easy half.
The defensible part of this business is not the loop. Anyone can copy 120 lines of Python. What they cannot copy is your accounts.json equivalent, the tier definitions you argued out with a customer, and the eighteen months of run records that tell you which submissions the model gets wrong. That is the argument in moat, in AI, and it is why the first customer matters more than the second tool.
Sources
- Anthropic Messages API reference — stop_reason values, usage.input_tokens / usage.output_tokens on every response
- Anthropic tool use overview — tool_use blocks must be answered with matching tool_result blocks in the next message
- Anthropic model overview — current model IDs and aliases, e.g. claude-sonnet-4-5
- Anthropic pricing — per-million-token input and output prices used in the cost arithmetic
- anthropic-sdk-python — pip install, ANTHROPIC_API_KEY resolution, client error types
- Anthropic Console API keys — where the API key comes from
- Building effective agents (Anthropic Engineering) — guidance to keep agent loops simple and composable, with guardrails outside the model
- Prompt caching — re-sent conversation prefixes can be cached to cut input cost on multi-step runs
- Stripe usage-based billing — metering events for per-run billing