Agent Cost Model and Token Economics

The price of a token is easy to look up. The price of a finished, correct task takes a model of your own.

BeginnerIntermediateExpert · 12 min read · Last updated:

In short

Model the cost of a whole task, not one call: model tokens for every step, tool and retrieval fees, infrastructure, evaluation and human time. Input tends to grow faster than the number of steps because history is resent. Report spend per successful task and the expected total including failure handling, using ranges drawn from real runs and current prices.

What you will learn: how token pricing works, why steps dominate agent cost, how caching and batch rates change the sum, which costs sit outside the model bill and how to turn it all into a model you can defend.
Prerequisites: How LLMs Power Agents: Transformers, Tokens and Sampling for tokens. Basic arithmetic is enough.

Versions used

The example runs in November 2026 with Python 3.13 and only the standard library. Every price and volume in it is invented. Provider multipliers quoted with a link were read in November 2026; check the current price list before deciding anything.

Beginner Tokens and prices

How model usage is priced

Models read and write tokens, which are pieces of text; images and audio are also counted in token-like units or their own. Hosted providers usually charge separately, per million tokens, for:

KindWhat it isTypical relationship
InputInstructions, tool definitions, history, documentsThe base rate
Cached inputA repeated beginning the provider has storedCheaper to read; may cost more to write
OutputText and tool calls the model producesUsually several times the input rate
ReasoningIntermediate thinking in some modelsCommonly billed as output; check the provider

Some prices also depend on context length, speed tier or region. Read the usage figures returned with each response and treat them as the record. Local estimates of token counts are useful for planning and rarely exact.

Everything in the context is paid for on every call. A long system prompt, forty tool definitions and a large retrieved document are not one-time costs.

One task, many calls

An agent loops: build context, call the model, run a tool, add the result, call again. Each round sends the earlier material once more.

Step 1instructions
Step 2plus one result
Step 3plus two
Step npays for all of it

If instructions take s tokens and each step adds p tokens, the input across n steps is:

total input = n × s  +  p × n × (n − 1) ÷ 2

The second part grows with the square of the step count. This is why a task that wanders is so expensive, and why removing two unnecessary steps from the end of a long run saves more than their share.

The whole bill

CostDriverOften missed?
Model callsSteps, context size, output, model choiceNo
Embeddings and rerankingDocuments indexed and queriesSometimes
Search, data and tool feesCalls to paid servicesOften
Compute, queues and storageRun time, memory, data keptOften
ObservabilityTrace volume and retentionVery often
EvaluationTest runs and model gradersVery often
Human reviewShare reviewed and minutes eachVery often
Failure handlingRework, refunds, supportAlmost always
Building and maintainingEngineering and subject expertsOften

For many business tasks, a few minutes of review costs more than all the model calls. If so, effort spent making outputs easier to check may save more than switching models.

Intermediate Building the model

Two measures that answer different questions

MeasureFormulaAnswers
Spend per successful taskAll agent spend ÷ successful tasksWhat does one good result cost us to produce?
Expected total per taskSpend per attempt + failure rate × cost of handling a failureWhat does a task cost the business, including cleanup?

Keep them separate. Adding failure handling to the first and then dividing by the success rate counts failures twice. State which one a report uses, and use the same definition when comparing versions (Task, Tool and Planning Metrics).

A worked example

The program calculates model cost for different run lengths, then compares a run with and without prompt caching. "Attempt" includes tools, infrastructure and an expected share of human review.

"""Cost per successful task. All prices and volumes are invented."""
PRICE = {"input": 2.00, "cached": 0.20, "output": 10.00}   # per million tokens


def model_cost(steps, system, per_step, output, cached_share=0.0):
    """Each step resends the system text plus everything added so far."""
    sent = cached = made = 0
    for step in range(steps):
        context = system + per_step * step
        hit = int(context * cached_share) if step else 0
        sent += context - hit
        cached += hit
        made += output
    dollars = (sent * PRICE["input"] + cached * PRICE["cached"]
               + made * PRICE["output"]) / 1_000_000
    return dollars, sent + cached


def task_costs(model, tools, infra, success, review_rate, review_cost, failure_cost):
    """Return spend per attempt, per success, and expected total per task."""
    attempt = model + tools + infra + review_rate * review_cost
    per_success = attempt / success                      # all spend / successes
    expected = attempt + (1 - success) * failure_cost    # includes handling failures
    return attempt, per_success, expected


if __name__ == "__main__":
    for steps in (5, 10, 20):
        cost, tokens = model_cost(steps, 3000, 1500, 400)
        print(f"{steps:>2} steps: {tokens:>7,} input tokens, model cost ${cost:.4f}")
    print()
    for name, success, share in (("no cache", 0.90, 0.0), ("with cache", 0.90, 0.8)):
        model, _ = model_cost(10, 3000, 1500, 400, share)
        a, s, e = task_costs(model, 0.02, 0.005, success, 0.10, 1.50, 2.00)
        print(f"{name:<11}model ${model:.3f}  attempt ${a:.3f}  "
              f"per success ${s:.3f}  expected total ${e:.3f}")

Output:

 5 steps:  30,000 input tokens, model cost $0.0800
10 steps:  97,500 input tokens, model cost $0.2350
20 steps: 345,000 input tokens, model cost $0.7700

no cache   model $0.235  attempt $0.410  per success $0.456  expected total $0.610
with cache model $0.099  attempt $0.274  per success $0.304  expected total $0.474

Three observations:

  1. Going from 10 to 20 steps multiplies input tokens by about 3.5 and model cost by more than three.
  2. Caching cuts the model cost by more than half in this setup, but the saving per attempt is smaller in relative terms, because tools and review are unchanged.
  3. Failure handling adds a large amount to every task, even at 90 percent success.
What this sketch leaves out

It ignores any extra charge for writing to a cache, assumes a fixed share of each context is reused, gives every step the same output and treats averages as if every run were typical. Each simplification makes the estimate tidier than reality. Use real usage records once you have them.

Sensitivity: which assumption matters?

Take the cached version, with spend of about 0.274 per attempt and 2.00 to handle a failure:

Success rateSpend per successExpected total per task
85%0.320.57
90%0.300.47
95%0.290.37

Spend per success barely moves, while the expected total changes a great deal. A team that reports only the first measure would undervalue a quality improvement.

Expert Discounts, distributions and decisions

Cache and batch rates

Providers offer lower rates in exchange for conditions. As one example, Anthropic's pricing page in November 2026 describes cache writes at 1.25 times the base input rate for a five-minute lifetime or 2 times for one hour, and cache reads at 0.1 times on most models, with lower read multipliers on some newer ones. It also describes a batch interface at half price for input and output, which can be combined with caching. On that page's own account, a five-minute cache entry pays for itself after one read and a one-hour entry after two.

You can check the logic with multipliers alone. Without caching, sending a prefix twice costs 2.0 units. With a five-minute cache, one write and one read cost 1.25 + 0.1 = 1.35. With one hour, one write and one read cost 2.1, slightly more than 2.0, so a second read is needed: 2.2 against 3.0.

OpenAI also offers a batch interface at half price for work processed asynchronously within 24 hours, and its prompt caching rules and rates vary by model. Do not carry one provider's numbers to another.

The conditions matter as much as the discount. Caching needs an identical beginning and calls close enough together. Batch needs work that can wait. A forecast should include the hit rate you actually measure, not the best case.

Model the spread, not only the average

Agent costs are usually uneven: many short runs and a few very long ones. An average hides them.

  • Record cost per run and look at the median, 95th percentile and maximum.
  • Split by task type, customer and release.
  • Find what the expensive tail has in common: huge inputs, loops, failing tools.
  • Set a per-run ceiling based on the distribution, and decide what happens when it is reached.

A per-run limit converts an unbounded risk into a known worst case. Include unsuccessful and abandoned runs in the totals; they are real spend.

From task cost to monthly forecast

monthly cost = fixed costs
             + tasks per month × expected spend per attempt × attempts per task
             + evaluation and monitoring runs
             + review hours × hourly cost

Give three cases: low, expected and high. Vary volume, steps per task, cache hit rate, success and review share, and say which one moves the total most. Fixed costs, such as a platform fee or reserved hardware, make cost per task fall as volume grows, until capacity must be added in a step.

Compare with the alternative

A cost figure means something only beside a benefit and an alternative. Estimate what the same outcome costs today in time and money, including its error rate. Then compare the full cost of the agent, including building and operating it. Time saved is a saving only if it is used for something else or avoids spending; say which. Business Case, Build vs Buy and Vendor Evaluation treats the business case.

Hosted or self-run models

Self-running a model replaces a price per token with a price per hour. The comparison depends almost entirely on utilization:

cost per million output tokens
  = hourly cost of capacity ÷ (output tokens per second × 3600 × utilization) × 1,000,000

Measure throughput with your own prompt lengths and latency target, include spare capacity for failures and add engineering time. Quality may differ, so compare cost per successful task rather than per token (Managed vs Custom Platforms and Total Cost).

Keep the model honest

RoutinePurpose
Compare forecast with invoice monthlyFind missing components
Update prices from official pagesRates and discounts change
Remeasure after each releaseSteps and tokens shift
Version the spreadsheet or codeExplain changes in estimates
Record assumptions beside resultsLet others challenge them

Keep prices in one configuration file with the date each was checked, not scattered through code.

Your first estimate in an afternoon

  1. Pick one task type and run twenty realistic examples.
  2. Record steps, input, cached and output tokens, and tool calls for each.
  3. Mark each run successful or not by a written rule.
  4. Apply current prices from the provider's page.
  5. Add review minutes and the cost of handling a failure, even as rough ranges.
  6. Report median, high percentile, spend per success and expected total.

Twenty runs cannot pin down rare, expensive cases, so present the result as a first range and revisit it with production data. Then see Reducing Tokens, Tool Calls and Spend.

An illustrative budget conversation

Suppose an owner asks what an invoice-checking agent will cost next year. A single number would be misleading, so you present three cases. All share the same fixed costs. The low case assumes current volume, short runs and a high cache hit rate. The expected case adds measured long-tail runs and ordinary growth. The high case adds a new document type that doubles steps, with more review during its first months.

Beside each case you state success rate, review share and the cost of handling errors. The discussion then moves to the assumption that matters: if review share dominates, the useful investment may be evidence that lets reviewers approve routine items faster, provided quality supports it. The model has done its job when it changes what people decide to work on.

Presenting the result

A model is useful when others can question it. Put on one page the task definition and success rule, the three cases with their ranges, the share of each cost component, the assumption with the largest effect, the date and source of every price and the measurements still missing. Say plainly which figures come from production records, which from a small trial and which are guesses. Offer the next measurement that would narrow the range most, with the effort it takes. Decision makers can then choose whether more certainty is worth buying before they commit.

Common mistakes

MistakeBetter approach
Pricing one call and multiplying by tasksModel every step with growing context
Ignoring review and reworkInclude them, even as ranges
Assuming every call hits the cacheUse the measured hit rate and write charges
Quoting averages onlyShow percentiles and a per-run ceiling
Mixing the two cost measuresDefine them and report consistently
Copying prices from an old articleRead the official page and note the date

Checklist

  • Cost is modeled per task, with all steps.
  • Input, cached input, output and reasoning tokens are separated.
  • Tools, infrastructure, evaluation and review are included.
  • Success has a written definition.
  • Spend per success and expected total are both reported.
  • Percentiles and a per-run limit exist.
  • Prices carry a checked date and a source.
  • Forecast is compared with actual spend.

Frequently asked questions

Why is our bill higher than our estimate?

Common causes are longer histories, more steps, retries, evaluation traffic, low cache hit rates and components left out of the model.

Is output or input the bigger cost?

Output has a higher unit rate, but resent input often dominates long agent runs, so measure your own.

Should failed runs be counted?

Yes; their spend belongs in the total and their handling cost in the expected cost per task.

How precise should an estimate be?

Precise enough for the decision; give a range and name the assumption that moves it most.

References and further reading

Next steps