Token / Cost Tracking

Tokens and dollars, per run, per agent, per node.

Token consumption, model costs, and tool-related expenses are measured per run, agent, or workflow. The metric is only useful if something acts on it: a kill switch (a hard budget ceiling that terminates a runaway run) and caching of intermediate results turn the measurement into a control. Variable execution paths make cost forecasting hard, and a single edge case that triggers a retry chain can cost many times a normal run — so the ceiling is a safeguard, not an optimization.

In practiceAn autonomous research agent emits token and cost telemetry on each LLM call, and a hard per-run budget cap terminates the run before a self-initiated retry storm triples the daily bill.

Level
04 · Production
Subdomain
Observability & Evaluation
Also known as
Usage Tracking, Cost Observability, Budget Monitoring
Trade-off
Better budget control is achieved against additional measurement and aggregation effort.
Native in
OpenAI Usage APIs, LangSmith, Microsoft Agent Framework, Google Cloud Monitoring
The mechanism

How it works.

Every model call reports its tokens, and the run adds them up as money. Before each further call the sum is compared with a ceiling, and a run that has reached the ceiling is stopped.

1 · Measure

  1. Read the usage of each callInput and output tokens
  2. Convert to costWith the price of that model
  3. Attribute itTo the run, the agent, the customer

2 · Act

  1. Check before each callSpent so far against the ceiling
  2. Serve from the cacheA repeated step costs nothing
  3. Stop at the ceilingThe kill switch
  4. ReportCost per run, and the outliers
Budget ceiling
The most a single run may cost. It is set per run, not per month.
Kill switch
The rule that ends a run when the ceiling is reached. It is a safeguard, not an optimisation.
Cache hit
A step whose result was stored earlier and is returned without a model call.
Walk it through

A real run, step by step.

TaskA research run with a budget ceiling of 2.00 USD. A normal run costs about 0.80 USD:
Illustrative costs.
StepUSDTotalBudget check
Plan0.040.04Continue
Search and read six sources0.380.42Continue
Write a draft0.210.63Continue
One source fails to parse and is retried ten times1.422.05Continue, each retry was under the ceiling when it started
Eleventh retry0.002.05Stopped: the ceiling is reached
What this shows: one edge case made this run cost more than twice a normal one, and without the ceiling the retries would have gone on. Measuring alone would have shown that on the next invoice. The ceiling acted during the run. The price is a run that ends without an answer, which needs a clear message to the user, and a price table that has to follow every price change.
In code

The pattern in code.

Plain Pythonpython
# illustrative: input, output in USD
PRICE_PER_MILLION = {"small": (0.25, 1.25), "large": (3.00, 15.00)}

class BudgetExceeded(Exception):
    pass

class Budget:
    def __init__(self, ceiling_usd):
        self.ceiling, self.spent, self.cache = ceiling_usd, 0.0, {}

    def call(self, model_name, prompt):
        if prompt in self.cache:
            return self.cache[prompt]  # a repeated step costs nothing
        if self.spent >= self.ceiling:
            # the kill switch
            raise BudgetExceeded(f"{self.spent:.2f} USD spent")
        reply = model(prompt, model=model_name)
        price_in, price_out = PRICE_PER_MILLION[model_name]
        self.spent += (reply.input_tokens * price_in + reply.output_tokens * price_out) / 1_000_000
        self.cache[prompt] = reply.text
        return reply.text
Fit

Use it, or not.

When to reach for it

  • Costs must be capped or allocated.
  • Agents autonomously execute loops.
  • Optimization of models and patterns is required.

When it backfires

  • Prototypes run without budget relevance.
  • Metrics are not actionable.
  • Costs cannot be captured outside the system.
Pitfalls

Two ways this pattern will hurt you.

Cost discovered only after the bill arrives

Usage is computed at month end from the provider's invoice. A runaway loop has already cost a week's budget by the time anyone notices.

Countermeasure

Emit cost on every span as it happens. Set hard per-run caps at the harness; treat exceeding the cap as a correctness failure, not a billing concern.

Cost you cannot attribute across shared sub-agents

A supervisor fans out to specialists and tools that all bill to one account. The total is visible, but you cannot tell which agent, tenant, or feature drove the spend, so you cannot act on it.

Countermeasure

Tag every model call with run, agent, and tenant identifiers on the span, and aggregate cost along those dimensions — not just a single global counter.

Framework support

Where Token / Cost Tracking is native.

OpenAI Usage APIsServiceper-call usage + costNative
LangSmithServiceper-run token + cost rollupsNative
Microsoft Agent Frameworkusage telemetryNative
Google Cloud MonitoringServicecost + usage dashboardsNative
Sources

Where this pattern comes from.

  1. OpenTelemetry — GenAI semantic conventionsIn the source list

Search

Search patterns, frameworks, and pages.