The AI bill arrives as tokens. The questions leadership asks are about value: what are we getting for this, and should we be running it somewhere else?

Most organisations start by negotiating price. In my view the bigger levers are architectural: how many tokens each task sends, which model answers, whether the work was worth doing, and where it runs. The good news is that one piece of plumbing, a gateway with proper telemetry, answers all four. The same data that tells you a cache is cold also tells you which use cases could move on-prem.

This post works through that in order: where tokens go, how to spend fewer of them, how to measure agents by outcome rather than volume, and how to turn that measurement into a bottom-up hosting strategy without losing sight of data retention and DLP.

Where the tokens go

A model bill has more parts than “input and output”:

Component Where it hides
Input tokens System prompts, tool definitions, retrieved documents and the whole conversation history, resent on every call
Output tokens Answers, tool calls, and reasoning: thinking tokens are billed as output even when you never display them
Cache writes A premium on the first request that stores a prefix
Cache reads A steep discount on every request that reuses one
Waste Retries, abandoned runs, loops that never converge, work nobody used

Output tokens cost several times more than input. On Anthropic’s first-party API at the time of writing, output is five times the input price across the current models. But in agentic systems, input usually dominates the bill anyway, because of how agent loops work.

Why agents are expensive

An agent loop resends its entire context on every step. Take a modest loop: an 8K-token system prompt and tool definitions, then 20 steps that each add 3K tokens of tool output.

  • Without caching, the loop sends 730K input tokens. Step one sends 8K, step twenty sends 65K, and everything in between adds up.
  • With prompt caching, each step reads the previous prefix from cache and writes only the new 3K. Reads cost about a tenth of the base input price and writes 1.25 times, so the same loop costs the equivalent of about 148K input tokens: roughly a fifth of the uncached bill.

Same model, same task, same answer. That difference is purely how the requests are built, which is why the first levers are engineering, not procurement.

Lever 1: Caching

Prompt caching

Prompt caching stores the processed prefix of a request so the next request with an identical prefix skips the work. On Anthropic’s API, at the time of writing:

  • Reads cost about 0.1x the base input price, and less on some models (0.05x on Claude Opus 5.5).
  • Writes cost 1.25x for the default 5-minute lifetime, or 2x for a 1-hour lifetime.
  • Break-even is two requests on the 5-minute cache, and three on the 1-hour cache.
  • The minimum cacheable prefix is model-dependent: 512 tokens on the current Claude models, but higher on some older ones. Below it, nothing caches and nothing errors.

Other providers and self-hosted servers have their own versions (vLLM calls its version automatic prefix caching), with different prices and rules. The design principles are the same everywhere.

It is a prefix match. Any change to a byte invalidates everything after it. The request renders tools, then system prompt, then messages, so put stable content first and volatile content last. The usual silent invalidators are a timestamp in the system prompt, JSON serialised with unstable key order, and a tool list that varies between calls.

Caches are scoped. On Anthropic’s API they are isolated per workspace, and per organisation on Bedrock and Vertex. They are also per model, so the same prompt sent to two models writes two entries. Splitting traffic across workspaces or models splits the cache, and that has consequences for routing, below.

Measure it. Responses report cache reads and writes per request. If reads stay at zero across repeated calls, something in the prefix is changing. A cache hit ratio per use case belongs on the dashboard next to spend.

Response caching

A gateway can also cache whole responses, by exact match or by semantic similarity. That works for repeated, deterministic questions such as classification, FAQ-style lookups and enrichment. It does not suit agents, where the same question asked twice an hour apart should often get different answers.

A response cache is also a data store. It needs a time-to-live, a cache key that includes the tenant and the caller’s permission scope, and a rule that restricted data never enters it. Otherwise one user’s answer becomes another user’s data leak.

Lever 2: Batch anything that can wait

Asynchronous batch APIs trade latency for price. Anthropic’s Message Batches run at half the standard cost, and the major clouds offer their own discounted batch modes. Evals, nightly summarisation, backfills, bulk classification and document processing rarely need an answer in seconds. If a use case can tolerate results within hours, it should not pay interactive prices.

Lever 3: Route to the right model

The price spread between model tiers is large. On Anthropic’s first-party API at the time of writing, Claude Haiku 5.5 costs $0.10 per million input tokens, Claude Sonnet 5.5 $2 and Claude Opus 5.5 $4: a fortyfold spread between the smallest and the largest. Bedrock and Vertex price Claude separately.

Routing means sending each request to the cheapest model that meets its quality bar. In practice, in order of sophistication:

  1. Route by use case. Tag every request with its use case at the gateway, and map use cases to models. Classification goes to the small model; incident investigation goes to the frontier one. This captures most of the value and is easy to reason about.
  2. Cascade. Try the cheaper model first and escalate when validation fails: a schema check, a test, a confidence threshold.
  3. Learned routers. A classifier predicts which model a request needs. These are worth considering only once you have the eval data to train and check them.

Two cautions before you build a cascade.

Measure the simpler option first. The most capable model at lower effort often matches a cheaper model at high effort, and newer models expose effort controls that trade thoroughness against tokens within one model. One model at the right effort per route can beat a cascade, and it keeps one cache.

Count the cache. Because caches are per model, a cascade forfeits cache reuse across its tiers. A cheap first attempt that misses the cache and then escalates can cost more than going straight to the right model.

Judge every routing change on cost per completed task, not cost per request. A cheaper request that needs three retries, or a human to redo the work, is not cheaper.

Lever 4: Agent hygiene

Most agent waste comes from context nobody needed:

  • Trim tool output. Return the five relevant log lines, not five thousand. Filter fields, paginate, summarise at the tool. Tool output is usually the largest part of an agent’s context.
  • Load tools on demand. Fifty tool definitions on every call is a fixed tax. Tool search or a small core tool set with on-demand loading cuts it.
  • Manage long contexts. Compaction, clearing stale tool results and starting subtasks in a fresh context keep a long run from resending its whole history.
  • Budget the loop. Set step limits, wall-clock limits and token budgets per task, and stop conditions that end a run which is not converging.
  • Watch parallel fan-out. Ten parallel workers that each build a slightly different prompt over the same context write ten cache entries and read none of each other’s. Fewer workers over a byte-identical shared prefix turn those writes into reads.
  • Cap output. Structured outputs and sensible output limits stop a model from writing an essay when you needed a label.

Measure tasks, not tokens

Token counts tell you what you spent. They do not tell you what you got. To manage AI spend like any other engineering cost, you need unit economics: the cost of a unit of useful work.

Instrument everything at one choke point

Put every model call through a gateway, LiteLLM or similar, and emit OpenTelemetry spans that follow the GenAI semantic conventions. The attributes that matter for cost:

  • gen_ai.provider.name and gen_ai.request.model: who served it and which model.
  • gen_ai.usage.input_tokens and gen_ai.usage.output_tokens.
  • gen_ai.usage.cache_read.input_tokens and gen_ai.usage.cache_write.input_tokens.

Then add your own attributes: use case, team, agent, task ID, data classification and environment. Without a task ID you can count tokens but never cost a task. Check how your provider counts before you sum: in Anthropic’s spans, gen_ai.usage.input_tokens already includes cache reads and writes, so adding the cache attributes on top double-counts.

The gateway gives you attribution for free. LiteLLM, for example, records tags from each request’s metadata against its spend log, and virtual keys per team give you per-team budgets and showback.

Metrics that matter

Metric What it tells you
Cost per completed task The unit economics. The headline number for each use case
Task success rate Whether the work was done, judged against ground truth
First-pass acceptance The share of outputs a human accepted without edits
Rework and retry rate Hidden cost: tokens spent redoing work
Cache hit ratio Cache reads as a share of input tokens. Low means a broken prefix
Tokens per successful task Efficiency that is independent of model price
Latency p95 Whether a cheaper or self-hosted route still meets the SLO
Cost against the human baseline Whether the use case is worth running at all

Measuring what agents produce

Success needs ground truth, and agents make that harder because their output is actions, not text. Combine four sources:

  • Offline evals: a fixed set of historical tasks with known correct outcomes, run before every change to prompts, tools, routing or model.
  • Online evals: a sample of production outputs graded by an LLM judge that has been calibrated against human labels. An uncalibrated judge measures its own taste.
  • Human signals: approvals, rejections and edits. An approval click in Slack or a merged PR is a label you get for free.
  • Downstream outcomes: the ticket that reopened, the PR that was reverted, the incident that recurred. These are slow but honest.

Join outcomes to spend by task ID, and the cost-per-completed-task query is short:

-- One row per model call (from spans) and one per task outcome.
SELECT
  c.use_case,
  COUNT(DISTINCT c.task_id)                                   AS tasks,
  SUM(c.cost_usd)                                             AS spend_usd,
  SUM(c.cost_usd) / NULLIF(COUNT(DISTINCT o.task_id) FILTER (WHERE o.succeeded), 0)
                                                              AS cost_per_success_usd,
  SUM(c.cache_read_tokens)::float / NULLIF(SUM(c.input_tokens), 0)
                                                              AS cache_hit_ratio
FROM llm_calls c
LEFT JOIN task_outcomes o USING (task_id)
WHERE c.started_at >= now() - interval '30 days'
GROUP BY c.use_case
ORDER BY spend_usd DESC;

The table is ranked by spend, which is exactly the order to work through the levers above.

From telemetry to a hosting strategy

Hosting decisions usually start top-down: “we spend this much on AI, should we buy GPUs?” That question cannot be answered, because “AI” is not one workload. A code assistant, a nightly classifier and an agent that reads customer data have different volumes, quality bars and data constraints, and they belong in different places.

Tagged telemetry lets you answer it bottom-up, one use case at a time.

flowchart TD
    apps[Apps and agents] --> gw[AI gateway <br/> keys, budgets, DLP, routing, caching]
    gw --> pub[Provider API]
    gw --> mc[Managed cloud <br/> Bedrock, Vertex, Foundry]
    gw --> nc[Neo-cloud <br/> open-weight models]
    gw --> op[On-prem <br/> open-weight models]
    gw -- spans and spend --> obs[(Telemetry <br/> tokens, cost, outcomes)]
    apps -- outcomes --> obs
    obs --> inv[Use-case inventory]
    inv -- routing and hosting decisions --> gw

Diagram 1 — One gateway feeds the measurement that decides where each use case runs

Build the use-case inventory

After a month of tagged traffic, build one row per use case:

  • Volume: requests and tokens per month, input, output and cached.
  • Shape: interactive or batch, steady or bursty. The ratio of peak to average load decides whether dedicated capacity would sit idle.
  • Quality bar: the smallest model that passes the use case’s evals.
  • Latency: the SLO it has to meet.
  • Data classification: public, internal, confidential or restricted, and any residency requirement.
  • Retention requirement: whether prompts may be retained by anyone, for how long, and for what purpose.
  • Value: cost per completed task against the human baseline.

An illustrative example:

Use case Tokens/month Shape Quality bar Data class Candidate home
Incident investigation agent 400M Bursty, interactive Frontier Confidential Managed cloud, retention off
Code review assistant 900M Steady, working hours Mid-tier Internal Provider API or managed cloud
Ticket classification 2B Steady, batchable Small Internal Batch API, or self-hosted open weights at high utilisation
Customer chat summaries 300M Steady Mid-tier Restricted (PII) On-prem or sovereign, or managed cloud after masking
Nightly log triage 1.5B Batch Small Confidential Batch API or neo-cloud open weights

The hosting options

Option Strengths Trade-offs
Provider API Newest models and features first, no infrastructure, pay per token The provider’s retention terms apply; some frontier models require retention
Managed cloud (Bedrock, Vertex, Foundry) Runs in your cloud account with its IAM, private networking, regional endpoints, retention controls and existing spend commitments Features can lag the provider’s own API; priced separately
Neo-cloud (GPU-focused providers) GPU capacity or serverless open-weight inference, often cheaper and quicker to get than hyperscaler GPUs You run more of the stack; compliance, regional footprint and the provider’s own logging vary widely
On-prem or sovereign Maximum control over data and location; predictable cost at high utilisation Capital cost, utilisation risk, scarce skills, hardware refresh; generally open-weight models only
Hybrid Each use case runs where it fits You need the gateway, routing policy and telemetry to make it manageable

Do the break-even honestly

Self-hosting is a utilisation bet. The cost per million tokens of a self-hosted model is:

(hourly cost of the serving node ÷ tokens served per hour at real utilisation) × 1,000,000

With illustrative numbers, not quotes: a node costing $30 an hour that can serve 2,500 output tokens a second at full load costs about $3.33 per million output tokens if it is busy the whole time. At 40% utilisation, which is common for business-hours traffic, that becomes about $8.33. A small hosted model at $0.50 per million output tokens is hard to beat on price alone.

Then add what the formula leaves out: the engineers who run it, evals for every model upgrade, redundancy, and the frontier capability you give up. Self-hosting tends to win on control (restricted data, residency, retention, independence from a provider) and on steady, high-volume work that a small open-weight model handles well. It rarely wins on bursty work, or work that needs the best model.

That is why the honest answer is usually hybrid: frontier work on a provider or managed cloud, high-volume steady work on whichever option your break-even favours, and restricted data where you control it.

Make it policy

The gateway enforces the result. In an illustrative format of my own:

# Illustrative format, not a real product schema.
routes:
  - match: { dataClass: restricted }
    backend: onprem-open-weights
    responseCache: off
    logContent: never
  - match: { useCase: ticket-classification }
    model: small
    batch: preferred
  - match: { useCase: incident-investigation }
    backend: managed-cloud-eu
    model: frontier
    effort: high
    budget: { perTask: 2.00 USD }
  - match: {}
    model: mid-tier
    escalate: { to: frontier, when: validation-failed }

Review the inventory quarterly. Volumes grow, models get cheaper, and open-weight models get better. A use case that belonged on a frontier API a year ago may now be a small-model job, and the inventory is what tells you.

Data retention and DLP

Cost and hosting decisions are constrained by where data is allowed to go and how long it may stay there. Design this in from the start; retrofitting it means rebuilding the gateway.

Map every place a prompt persists

Prompts and responses end up in more places than most teams expect:

  • The model provider, under its retention terms.
  • The cloud platform: Bedrock, for example, has explicit retention modes per region, and its invocation logging writes prompts to your own storage if you turn it on.
  • Your gateway’s logs and spend records.
  • Your observability backend. Full-content trace modes copy system prompts, messages and responses into span attributes. Your tracing system quietly becomes a store of sensitive data.
  • Response caches, eval datasets built from production traffic, vector indexes and agent memory.

Each one needs an owner, a retention period and access control.

Set provider retention explicitly

Do not rely on defaults. On Bedrock, retention is a per-region mode: none for zero retention, default for the model’s standard behaviour, aws_review for models that require review, and inherit to defer to a broader setting. Under every mode, Bedrock does not share prompts or completions with the model provider. An organisation can enforce a mode with a service control policy on the bedrock:DataRetentionMode and bedrock-mantle:DataRetentionMode condition keys.

Know which models require retention. On Bedrock, the Claude Fable 5 family needs aws_review, which retains prompts and completions within AWS for up to 30 days for review. On Anthropic’s own API, Claude Fable 5.1 needs 30-day retention unless Anthropic has expressly authorised otherwise. The most capable model may therefore be off-limits for your most sensitive data, and the routing policy has to know that.

Keep content out of telemetry by default

Record metadata by default: model, token counts, cost, tags, outcome and latency. Capture full content only by exception: sampled, redacted, access-controlled and kept for days, not months. Most cost and quality analysis needs task IDs and outcomes, not the text.

Inspect at the gateway

DLP belongs at the choke point, before a prompt leaves your boundary:

  1. Detect personal data and secrets with tools such as Microsoft Presidio, a secrets scanner, or Bedrock Guardrails’ sensitive information filters.
  2. Decide by classification: allow, mask, block, or reroute to a more restricted backend. Rerouting is the useful option: a restricted prompt does not have to fail, it can go on-prem.
  3. Check output too. Models can reproduce sensitive data they retrieved, and responses go into logs and caches.

Watch the agent paths

Agents add exfiltration routes that chat does not have. An agent that can read Confluence and also fetch URLs can be talked, through prompt injection in a document it reads, into sending data out. Use permission-aware retrieval, scoped credentials per tool, and egress controls on anything that can reach the internet.

Treat eval data as production data

Eval sets built from real traffic are some of the most valuable assets in this whole system, and some of the most sensitive. Redact them, set a retention period, and control who can read them.

Where I would start

  1. This week: put every model call through one gateway, and tag each request with use case, team and task ID.
  2. This month: turn on prompt caching for the three use cases with the highest spend, and check the cache reads in the responses. Move anything that can wait to batch.
  3. Next month: join spend to outcomes, and publish cost per completed task for each use case.
  4. Next quarter: build the use-case inventory with data classifications, and make hosting decisions one use case at a time, starting where the data constraint or the volume is clearest.

The order matters. Caching and batching are almost free, routing needs evals, and hosting decisions need everything before them. Teams that start with the GPU purchase usually end up measuring utilisation instead of value.