PRODUCTION · 5 MIN READ

The real cost of an agent run

Count the loop, the tools, the storage, and the failures.

Download example files Code + setup + checks in a ZIP
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.

Langfuse exampleLiteLLM exampleOpenTelemetry example
SEE HOW THE SYSTEM FITS TOGETHERSELECT A COMPONENT
allocatetool workusageusageunit costremainingTask startsCreate a budgetEach model callInput + output usageEach tool callSearch + compute + dataTotal run costInclude retriesCompleted outcomeVerify successBudget decisionContinue or stop
  1. Set allowed calls, tokens, tool use, and elapsed time for this task.

  2. Record the actual billable categories and applicable contract rates.

  3. Include external APIs, sandbox compute, retrieval, storage, and media processing.

  4. Join the costs of every attempted step, including unsuccessful tasks.

  5. Use completed tasks as the denominator rather than counting fluent responses.

    Result or stopping point
  6. Check estimated remaining spend before another operation and reconcile actual usage afterward.

    Result or stopping point
Each model call

Record the actual billable categories and applicable contract rates.

Follow the arrows, then select a component to inspect its responsibility. On mobile, downward arrows connect the next step; bent arrows identify branches and return paths. Select a destination to jump to that component.

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.
Shell
python3 -m venv .venv
source .venv/bin/activate

Implement the example

Save as budget.py

Python · 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

JSON · 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

Shell
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.

Keep exploring

AI agent evaluation: frameworks, tools and an exampleAn agent that can pause and resume