Back to insights

ATI Lab insight

How to Track and Cap Token Costs per AI Agent Workflow

To track and cap token costs per AI agent workflow, tag every model call with the workflow that made it, log the four token counts the API returns, and price th...

Analysis for technology leaders and operators planning, buying, and governing AI systems.

How to Track and Cap Token Costs per AI Agent Workflow

To track and cap token costs per AI agent workflow, tag every model call with the workflow that made it, log the four token counts the API returns, and price them in your own code. Then enforce limits at two levels: a provider-side spend limit as the backstop, and a budget check in your application that runs before each call and stops the run before it crosses its budget.

The provider invoice can't do this for you. It shows one total for the month, so a support agent stuck in a retry loop looks the same as a busy week. This guide sets it up on the Claude API. It covers which fields to log, the caching detail that makes most home-made trackers under-count, what each kind of limit does when it is hit, and how we cap spend in our own scheduled routines. ATI Lab builds and runs AI workflows for clients, and cost tracking is part of what we set up, so we have an interest in the topic.

How do you attribute token costs to one workflow?

Attribution starts before the first call. Anthropic's Usage API can filter and group token usage by API key, workspace, model and service tier, so the simplest way to get per-workflow numbers is to give each production workflow its own API key, and each group of workflows that needs its own spending cap its own workspace.

Three details from Anthropic's documentation shape that design.

  • The Usage and Cost API is part of the Admin API, which is unavailable for individual accounts. You need an organization in the Claude Console and an Admin API key.
  • Usage in the default workspace is reported with an empty workspace ID, and you can't set limits on the default workspace. Keep production agents out of it.
  • Playground usage in the Console has no API key attached, so it shows up unattributed.

API keys and workspaces give you per-workflow totals. For the cost of one run or one step, also write a workflow ID and a run ID into your own log line for every call.

Which token counts should you log on every call?

Every Messages API response carries a usage object, and four of its fields set the cost.

FieldWhat it countsPriced at
input_tokensInput after the last cache breakpointBase input price
cache_creation_input_tokensInput written to the cache on this call1.25× base input (5-minute cache) or 2× (1-hour cache)
cache_read_input_tokensInput read from the cache0.1× base input; 0.05× on Opus 5.5 and Sonnet 5.5; 0.025× on Fable 5.1
output_tokensEverything the model generatedOutput price

The first row is where trackers go wrong. Anthropic's prompt caching documentation states that input_tokens covers only the tokens after the last cache breakpoint, and that total input is the sum of all three input fields. A tracker that multiplies input_tokens by the input price and stops there misses every cached token. If you use both cache durations, the response also splits cache_creation_input_tokens into 5-minute and 1-hour counts, which are priced differently.

Server-side tools add their own counters. Web search, for example, is reported as server_tool_use.web_search_requests and billed at $10 per 1,000 searches on top of tokens.

How do you price each call?

With the counts logged, cost per call is arithmetic. This example uses Claude Sonnet 5.5 list prices per million tokens on 15 October 2026.

PRICE = {"in": 2.00, "out": 10.00, "write_5m": 2.50, "write_1h": 4.00, "read": 0.10}

def call_cost(u):  # u = response.usage; prices are per million tokens
    cc = u.cache_creation  # splits cache writes into 5-minute and 1-hour
    w5 = cc.ephemeral_5m_input_tokens if cc else (u.cache_creation_input_tokens or 0)
    w1 = cc.ephemeral_1h_input_tokens if cc else 0
    return (u.input_tokens * PRICE["in"]
            + w5 * PRICE["write_5m"] + w1 * PRICE["write_1h"]
            + (u.cache_read_input_tokens or 0) * PRICE["read"]
            + u.output_tokens * PRICE["out"]) / 1_000_000

Keep the price table in one place, with the date you checked it, because Anthropic changes prices and adds models. The full per-model table, including Batch API rates, is in our Claude API pricing guide for businesses. Two multipliers sit on top: the Batch API halves input and output, and US-only processing through inference_geo adds 10% to every token category on Claude 4.6 and later models.

Your own number is an estimate. Reconcile it against Anthropic's Cost API, which reports in US dollars with daily buckets and can group by workspace or by description (which includes the model). Usage data typically appears within 5 minutes of a request. The cost endpoint leaves out Priority Tier costs, and code execution costs appear only in the cost endpoint.

How do you cap token spend per workflow?

Anthropic gives you two limits. The third, and the only one that works per run, you build yourself.

LimitWhere you set itWhat happens when it is reached
Organization spend limitBilling page in the Claude Console, at or below your tier's monthly capRequests fail with HTTP 400 (invalid_request_error, "You have reached your specified API usage limits") until you raise the limit or access resumes
Workspace spend limitPer workspace in the Console (not the default workspace)Same 400 error, worded as "workspace API usage limits"; other workspaces keep running
Run budget in your applicationYour orchestration codeWhatever you decide: stop the run, switch to a smaller model, or hand the item to a person

Behind both sits the tier cap. Anthropic lists monthly spend caps of $500 for the Start tier, $1,000 for Build and $200,000 for Scale. When an organization reaches its tier cap, API usage pauses until 00:00 UTC on the first of the next month unless you request a higher limit. Requests then return HTTP 429 with error type rate_limit_error and the error code enforced_spend_limit_reached, with no retry-after header.

That last detail matters for agents. The cap error has the same type as an ordinary rate limit, and Anthropic notes that retrying, including the SDK's automatic retries, fails until access resumes. If your agent treats every 429 as "wait and retry", it will keep sending requests that cannot succeed until the next month. Check error.details.error_code and stop the run cleanly when it says the spend limit was reached.

The provider limits protect the company from a runaway month, but they can't tell one workflow's runaway run from another's normal day. The run budget does that, and it has to run before the call.

1Estimate the next callPrompt size is known before sending; use a typical output length for the step 2Would run total + estimate exceed the run budget?Yes: stop, save what the run produced, hand the item to a person 3Make the callA spend-cap error (enforced_spend_limit_reached) ends the run; never retry it 4Log the four token countsWith workflow ID, run ID, step name and model 5Price the call, add it to the run totalOnce a day, reconcile your totals against the provider's Cost API

The check compares the run total plus the estimated cost of the next call against the budget. Checking only the total so far lets the run overshoot by one call, and on a long-context step one call can be most of the budget.

How we cap spend in our own routines

The scheduled routines that run atilab.io's search program call a paid data API (DataForSEO) many times per run. It is a data API rather than a language model, but it has the same problem of many cheap calls in an unattended loop. We use the pattern above, and running it taught us two things.

Our keyword-research script takes a --budget argument. Before every paid call it adds that call's estimated price to the running total, and if the sum would cross the budget it stops with a "BUDGET STOP" message instead of making the call. The per-call estimates are hard-coded from the prices we observed on one day in September. The day's plan also caps all scripts together. On the 11 October 2026 planning run, the log records $0.568 for the research script, $0.178 for the AI Overview check and $0.014 for seven extra search-result checks, $0.76 against a $1.00 cap.

The first lesson came from reading our own stop message. The script stops cleanly, but it does not save partial results, so a budget stop at 95% of the run throws away 95% of the paid work. An agent's budget stop should write out whatever the run has produced before it exits, which is why step 2 in the diagram says "save what the run produced".

The second is that estimates drift. For that same run, the script's own estimate was $0.70, about 24% above the $0.568 in the log. Erring high is the safe direction for a cap, but it also means the cap stops runs earlier than it needs to. Logging the provider's reported cost next to your estimate is how you notice the gap, and token prices need the same check whenever a model is replaced.

When should a token cost alert fire?

Set the first alert well before any limit. A sensible starting point is an alert when a workflow passes 80% of its monthly budget, so someone can decide whether to raise the budget or fix the workflow while it still runs. Add one alert on cost per completed task rising week over week. Total spend can stay flat while a workflow completes fewer tasks, which hides a retry problem behind lower volume.

Two rules keep these alerts useful. Give each alert an owner who acts on it, and confirm a rise on a second reading before paging anyone, because one expensive day is often one large document. Our guide to building an AI agent that monitors a metric and alerts the team covers thresholds, confirm-twice rules and alert channels in detail; a cost metric fits the same build. Our AI agent cost review runs this weekly per workflow and also tracks the two costs a token log misses, runtime and the people who review outputs.

Which tools break down token costs by model?

On the Claude API, the Claude Console's Usage and Cost pages and the Usage and Cost Admin API already break usage down by model. The Usage API groups by model, workspace, API key, service tier, context window and data residency, in 1-minute, 1-hour or 1-day buckets. Anthropic's documentation also lists ready-made integrations for dashboards and alerts, including Datadog, Grafana Cloud, Honeycomb, CloudZero and Vantage.

What none of them knows is your workflow structure. A per-model view shows that Sonnet costs more this week; only your own workflow and run IDs show which agent step caused it. Claude Enterprise organizations get cost data through a separate Analytics API with its own key type, and Claude Code per-user costs come from the Claude Code Analytics API.

How are charges calculated when AI agents call external APIs through an orchestration platform?

An agent that calls external APIs through an orchestration platform can run up three separate meters, and only one of them is tokens.

  1. Model tokens. Each tool call costs tokens twice. The model's request to call the tool is output, and the tool's result goes back to the model as input on the next call. Tool definitions are input on every call, and Anthropic adds a tool-use system prompt whenever tools are present (286 tokens on Sonnet 5.5 and Opus 5.5).
  2. The orchestration platform's own unit. Platforms bill in their own units, such as runs, steps, tasks or credits. A loop that retries a step can cost platform units as well as tokens.
  3. The external API's own price. A data provider, search API or enrichment service bills you directly, per call or per record.

Log all three against the same run ID. A large tool result is usually the hidden cost. An API that returns a 30-page JSON document sends all of it back through the model unless a step trims it first.

How do cached input tokens affect my Anthropic API bill?

Cached input tokens make repeated context cheaper: a cache read costs 10% of the base input price on most models, 5% on Opus 5.5 and Sonnet 5.5, and 2.5% on Fable 5.1. Writing to the cache costs more than normal input, 1.25× for the 5-minute cache and 2× for the 1-hour cache, so caching pays off after one read (5-minute) or two reads (1-hour).

Here is an illustrative call on Sonnet 5.5: a 20,000-token cached instruction prefix, 1,000 new input tokens and 500 output tokens.

CaseCorrect costTracker that reads only input_tokens and output_tokens
No caching$0.047$0.047 (all input is in input_tokens)
Cache write (first call)$0.057$0.007, under by 88%
Cache read (warm)$0.009$0.007, under by 22%

Caching can also fail silently. Prompts shorter than the model's minimum cacheable length (512 tokens on the 5.5-generation models, 4,096 on Haiku 4.5) are processed without caching even when marked for it, and no error is returned. Both cache fields then come back as zero, which your log will show.

What do 10 million tokens cost on Claude?

Ten million tokens cost between $1 and $500 on the Claude API, depending on the model and on how many of them are output. Output costs five times as much as input on every model in the table. At list prices on 15 October 2026, before caching or batching:

Model10M input tokens10M output tokens10M at 80% input, 20% output
Claude Haiku 5.5 (prompts up to 100,000 tokens)$1$5$1.80
Claude Haiku 4.5$10$50$18
Claude Sonnet 5.5$20$100$36
Claude Opus 5.5$40$200$72
Claude Fable 5.1$100$500$180

Haiku 5.5 charges five times more per token on any request whose prompt is over 100,000 tokens. Ten million tokens is also not the same amount of text on every model: Anthropic states that Claude 4.7 and later models use a tokenizer that produces about 30% more tokens for the same text, and Haiku 4.5 uses the earlier one.

What does a bring-your-own Anthropic key cost?

When an agent platform runs on your own Anthropic API key, the tokens are billed to your Anthropic account at the API rates above, and the platform bills its own fee separately. The upside is that every token appears in your Console and Usage API, and your spend limits apply to it. The risk is that a platform with your key can spend up to your organization's limit. Give each platform its own API key in its own workspace with a workspace spend limit, so one tool can't use up the whole organization's budget.

If someone else builds the workflow, put tracking and caps in the scope. Our guide to AI automation agency pricing covers how ongoing support retainers are usually structured, and our AI automation service page explains how we scope a build.

Frequently asked questions

Can I set a spend limit per API key on the Claude API?

Anthropic documents spend limits at the organization level and per workspace. To cap a single key, put it in its own workspace and set that workspace's limit.

How quickly does Anthropic report token usage?

Usage and cost data typically appears within 5 minutes of a request completing, according to Anthropic. The Usage API supports polling once per minute. For a per-run budget, use the usage object in each response, which is immediate.

What happens when an agent hits the spend limit mid-task?

Its next request fails. A limit you set returns HTTP 400; the tier's monthly cap returns HTTP 429 with the code enforced_spend_limit_reached. Either way the agent should save its progress, stop and flag the item for a person, because retries will not succeed.

How often should we review token costs per workflow?

Weekly for workflows in production, with automated alerts in between. A monthly review sees a retry loop only after it has run for weeks.

All Anthropic prices, multipliers, usage fields, spend caps and error responses were checked on Anthropic's pricing, prompt caching, rate limits and Usage and Cost API documentation on 15 October 2026. Recheck them before budgeting. The cost examples are illustrative calculations, labelled as such. The budget-stop example and spend figures come from our own routine's code and run log. This article was drafted with AI assistance and edited and checked by the ATI team.

Next step

Turn the analysis into an implementation decision

Bring us the workflow, business constraint, or architecture question. We will help define the practical next step.