PRODUCTION · 5 MIN READ
The real cost of an agent run
Count the loop, the tools, the storage, and the failures.
Jump to a section 10 sections
EXAMPLE USE CASE
Calculate the cost of one completed support task
A cheap-looking request may include retries and unsuccessful tasks that still consume model and tool usage.
- Input
- Usage for all attempts, model input/output rates, tool charges and task outcomes.
- Expected output
- Total spend, cost per completed task, remaining budget and over-budget tasks.
- Success check: The worked ledger includes the failed run in total cost and divides by completed tasks only.
- Try a failure: Set the completion count to zero; cost per completion must become undefined, not zero.
Example scope: A configurable accounting example with illustrative rates. It does not quote provider prices or call a billing API.
Set allowed calls, tokens, tool use, and elapsed time for this task.
allocateTo 02 · Each model callRecord the actual billable categories and applicable contract rates.
tool workTo 03 · Each tool callInclude external APIs, sandbox compute, retrieval, storage, and media processing.
Join the costs of every attempted step, including unsuccessful tasks.
unit costTo 05 · Completed outcomeremainingTo 06 · Budget decisionUse completed tasks as the denominator rather than counting fluent responses.
Result or stopping pointCheck estimated remaining spend before another operation and reconcile actual usage afterward.
Result or stopping point
Record the actual billable categories and applicable contract rates.
Account for every step
- A run may contain several model calls, tool calls, searches, and memory operations.
- Record usage and duration at each boundary.
- Include retries and unsuccessful runs when estimating the cost of a completed task.
Use a useful denominator
- Cost per successful task is usually more informative than cost per request.
- Separate fixed infrastructure costs from variable model and service costs.
- Keep prices configurable rather than hardcoding a comparison that will become stale.
Set a budget in application code
- Use limits for turns, wall-clock duration, tool invocations, and estimated spend.
- A stopping rule should return a useful partial result and a clear reason.
- Test a tool that repeatedly fails so the loop cannot spend indefinitely.
Set up the lab
- Use a new working directory for this example.
python3 -m venv .venv
source .venv/bin/activateImplement the example
Save as budget.py
import argparse
import json
from decimal import Decimal
from pathlib import Path
parser = argparse.ArgumentParser()
parser.add_argument("--budget", type=Decimal, default=Decimal("0.020"))
args = parser.parse_args()
# Illustrative currency units per million tokens; replace with your rates.
rates = {"input": Decimal("1.00"), "output": Decimal("4.00")}
runs = json.loads(Path(__file__).with_name("runs.json").read_text())
ledger = []
for run in runs:
model = sum((Decimal(c["input"]) * rates["input"] +
Decimal(c["output"]) * rates["output"]) / 1_000_000
for c in run["calls"])
cost = model + Decimal(run["tool_cost"])
ledger.append({"run": run["id"], "outcome": run["outcome"], "cost": cost})
spent = sum(row["cost"] for row in ledger)
completed = sum(row["outcome"] == "completed" for row in ledger)
report = {"ledger": ledger, "total_cost": spent, "completed_tasks": completed,
"cost_per_completed_task": spent / completed if completed else None,
"remaining_budget": args.budget - spent,
"over_budget": spent > args.budget}
print(json.dumps(report, indent=2, default=str))
raise SystemExit(1 if report["over_budget"] else 0)Save as runs.json
[
{
"id": "completed-104",
"outcome": "completed",
"calls": [
{
"input": 1400,
"output": 180
},
{
"input": 1900,
"output": 220
}
],
"tool_cost": "0.002"
},
{
"id": "failed-999",
"outcome": "failed",
"calls": [
{
"input": 600,
"output": 0
}
],
"tool_cost": "0.002"
}
]Run and verify
python budget.py
# Total: 0.0095; one completed task; cost/completed task: 0.0095.
python budget.py --budget 0.005
# Reconciliation flags over_budget and exits 1.- The completed task costs 0.0069; the failed task still costs 0.0026. Total spend is 0.0095.
- Cost per completed task is 0.0095, including the unsuccessful attempt. With zero completions the report returns null.
- The smaller budget is flagged after reconciliation. It does not retroactively prevent expenditure.
Troubleshooting and failure tests
- Counting only the final successful model call omits retries, failed tasks and external tools.
- These example rates are invented for arithmetic. Load actual rates, billable categories and provider usage in your own application.
Before production
- Enforce an admission budget before each call using conservative estimates and maximum output/tool limits; reconcile actual usage afterward.
- Report fixed infrastructure costs separately, then allocate them explicitly when comparing total task economics.