Applied AI: Cost Control

Cost Control

Information in this post reflects publicly available sources as of October 17, 2026.

During the pilot, your support agent cost about $40 a month, and nobody looked at the invoice. Three months after launch, the invoice says $58,000, and finance wants to know why. Nobody can say. The usage dashboard shows a total but not which feature, which customer, or which part of the prompt is spending the money.

When the team finally digs in, the answer is mundane. Every step of every conversation resends a 30,000-token system prompt and tool list at full price. Tools return pages of output that sit in the history forever. And every request goes to the largest model, including the six in ten that are simple questions about opening hours and password resets.

None of these are exotic problems, and none require a new architecture to fix. With the changes in this post, the same agent costs about 90% less per conversation. This post is about where the money in an AI feature actually goes and which levers move it.


Why AI costs behave differently

Most infrastructure costs are fixed or scale slowly: a server costs the same whether it handles one request or a thousand. Model APIs charge per token, so every design decision shows up on the invoice. A longer system prompt, an extra tool, a verbose answer, or one more agent step costs money on every single call, forever.

That also means costs grow in ways traffic alone does not explain. The agents post showed that an agent's cost grows faster than its step count, because each step resends the whole history. A feature can double its cost without a single new user, simply because someone added a tool or allowed one more step.

The good news is that the same property makes costs very controllable. Because spending follows tokens, cutting tokens cuts spending directly, and most of the tokens in a typical application turn out to be waste.


How it works

Anatomy of a bill

Every model call is billed on a few quantities, and they are not priced equally.

Input tokens include everything you send: the system prompt, tool definitions, conversation history, retrieved documents, and the user's message. Output tokens are what the model writes, and they typically cost four to eight times as much as input tokens. Models that think before answering bill their reasoning tokens as output too, even when you never see them. Cached input, the part of a prompt the provider has seen recently, is billed at a steep discount.

Put together, the cost of one call is roughly:

cost = uncached_input × input_price
     + cached_input   × cached_price
     + output         × output_price      (output includes reasoning tokens)

That formula points to every lever in this post. Send fewer input tokens, make more of them cached, generate fewer output tokens, or pay a lower price per token by using a cheaper model or a discounted tier.

Measure before you cut

The first lever is visibility. Provider dashboards show totals by API key, which says nothing about which feature or which part of the prompt is responsible. Every API response includes a usage object with token counts, so record cost per call yourself, tagged with the feature that made it:

PRICES = {  # dollars per million tokens, copied from your provider's pricing page
    "large": {"input": 3.00, "cached": 0.30, "output": 15.00},
    "small": {"input": 0.30, "cached": 0.03, "output": 1.50},
}

def record_cost(feature: str, tier: str, usage) -> float:
    p = PRICES[tier]
    uncached = usage.input_tokens - usage.cached_input_tokens
    cost = (uncached * p["input"]
            + usage.cached_input_tokens * p["cached"]
            + usage.output_tokens * p["output"]) / 1_000_000
    metrics.increment("llm.cost_usd", cost, tags={"feature": feature, "tier": tier})
    return cost

The usage field names differ between providers, and the prices here are illustrative, but the idea carries over directly. With cost tagged by feature, a dashboard can show that the ticket summarizer costs $300 a month and the agent costs $50,000, which tells you exactly where to look. Log the size of each part of the prompt as well, so you can see whether the money goes to tool definitions, history, or retrieved documents.

The levers, applied

Here is the support agent from the opening, at an illustrative $3 per million input tokens and $15 per million output tokens. A typical conversation takes ten agent steps. The system prompt and tool definitions come to 30,000 tokens, the history grows by about 1,500 tokens per step, and each step generates about 400 output tokens.

COST PER CONVERSATION, LEVERS APPLIED IN TURN $1.16 $0.46 −61% $0.34 −71% $0.25 −79% $0.11 −90% Baseline Cache the prefix Drop unused tools Trim tool output Route easy traffic At 50,000 conversations a month, the bill drops from about $58,000 to about $5,600. Illustrative prices: $3 per million input tokens, $15 per million output tokens, cached reads at 10%.

Cache the prefix. The 30,000-token prefix is identical on every step, so it is the ideal candidate for prompt caching. With Anthropic-style pricing, the first step writes the cache at 1.25 times the input price and the other nine read it at a tenth. That alone cuts the conversation from $1.16 to about $0.46.

As the context engineering post explained, it only works if the prefix is byte-for-byte stable: no timestamps or request IDs near the top.

Drop unused tools. Most of that prefix was tool definitions for tools this agent rarely uses. Cutting the prefix from 30,000 to 12,000 tokens, by removing unused tools and MCP servers and shortening verbose descriptions, brings the cost to about $0.34. Some hosts go further and load tool definitions only when the model searches for them.

Trim tool output. Tools that return whole API responses fill the history with tokens the model reads again on every later step. Capping tool output and masking old results, so the history grows by 800 tokens per step instead of 1,500, brings the cost to about $0.25.

Route easy traffic. Six in ten conversations turn out to be simple questions that a small model handles well. Sending those to a model at a tenth of the price brings the average to about $0.11, roughly 90% below where it started.

The example leaves output alone, but output deserves a look too, since each output token costs five times an input token here. Asking for concise answers, dropping boilerplate such as restating the question, and using structured outputs for anything code consumes all shrink the most expensive part of the bill.

Routing and cascades

The last lever deserves a closer look, because it is the most powerful and the easiest to get wrong. Model prices differ by ten times or more between tiers, and most real traffic does not need the most capable model.

Request Router cheap classifier Small model about 1/10 the price Large model full price Check valid, confident? Respond easy hard pass fail: escalate Route up front when difficulty is predictable. Cascade when you can check the cheap answer.

There are two ways to do it. A router classifies each request up front and sends it to the right model. The classifier can be a small model, a set of rules, or a trained model; LMSYS's open-source RouteLLM project reported keeping 95% of GPT-4's quality on one benchmark while cutting cost by more than 85%.

A cascade tries the cheap model first, checks the result, and escalates only when the check fails. Cascades work best when a check is cheap and reliable, such as schema validation, a test suite, or a confidence signal.

Routing also works inside a single request. An agent can plan with a large model and hand mechanical steps, such as summarizing a long tool result or extracting fields, to a small one. The multi-agent post's subagents are a natural place to use cheaper models.

Discounted tiers

The other way to lower the price per token is to give up speed. All three major providers offer batch APIs that process requests asynchronously, typically within 24 hours, at about half the normal price. Nightly report generation, bulk classification, eval runs, and backfills rarely need an answer in seconds. OpenAI also offers a flex tier at similar discounts for traffic that can tolerate slower, less predictable responses.

Reasoning models add one more control. Many expose an effort or thinking budget setting that limits how many reasoning tokens a request may use. Hard planning steps may need a high budget, while routine steps rarely benefit from one, and reasoning tokens are billed at the output price.


Where to start

Different levers cost different amounts of effort, and the cheap ones are worth doing on day one.

More engineering effort Bigger savings DO FIRST PLAN FOR Prompt caching Batch API for async work Stable prompt prefix Cap output and reasoning Trim context Route to smaller models Fine-tune a small model Semantic response cache Typical positions; your traffic decides the exact numbers. Measure before and after every change.

The top-left corner is nearly free: turn on caching and keep the prefix stable, move offline jobs to batch, and set sensible limits on output length and reasoning effort. Trimming tools and context takes some engineering but pays off in quality as well as cost, since smaller contexts tend to produce better answers. Routing and fine-tuning are real projects that need evals to prove they do not hurt quality.

A semantic response cache stores answers and returns a saved one when a new question is similar enough to an old one. It sounds attractive, but it pays off only when users ask the same things in the same context, and returning a cached answer to a question that only looks similar is a correctness bug. Most applications get more from caching prompts than from caching responses.

Do not optimize too early, either. Before a feature has users, the bill is small and the prompt changes daily. The day-one habits are cheap; the larger projects belong after you know which features matter and have an eval suite to protect quality while you cut.


What goes wrong

The cache never hits. A timestamp, user name, or request ID near the top of the prompt makes every prefix unique. Tools listed in a different order each time do the same. Check the cached token count in the usage data; if it is near zero, something at the top of the prompt is changing.

Routing quietly lowers quality. The router sends a hard question to the small model, which answers confidently and wrongly. Nothing errors, so nobody notices. Run evals on routed traffic separately, and track escalation and complaint rates per model tier.

Output limits cut answers off. A tight token limit saves money until it truncates a JSON object or an explanation halfway through, and the retry costs more than the original call would have. Limit length through instructions and schema design first, and keep the hard limit as a safety net with room to spare.

Retries multiply spend. An agent that hits a rate limit or a validation failure and retries the whole conversation can turn one expensive call into five. Retry the failed step, not the conversation, and put a budget on retries per request.

Retrieval costs creep up. A RAG pipeline that re-embeds the entire corpus every night pays for millions of unchanged documents, and a retriever that returns twenty chunks instead of five quadruples the context it adds to every question. Embed only what changed, and tune the number of retrieved chunks with evals rather than generosity.

Nobody owns the number. Without per-feature cost tracking, spending drifts upward one reasonable change at a time. Set budgets per feature, alert on unusual spending, and review the top consumers regularly, just as you would cloud infrastructure.


Trade-offs

Not every lever is free. Prompt caching is the rare exception: it lowers cost and latency together, because cached prefixes skip most of the processing. Trimming context usually improves quality as well.

The rest trade something away. Batch APIs trade latency for price, which is fine for nightly jobs and unacceptable for chat. Routing trades some quality risk for price, and a cascade adds latency on every escalated request, since the user waits for both the cheap attempt and the expensive one. Fine-tuning a small model can match a large one on a narrow task, but it adds training data, evaluation, and model versioning work.

The constant across all of them is measurement. Every cost change is also a potential quality change, so pair each one with the same eval run you would use for any other change to the system.


The current landscape

All three major providers support prompt caching, with different mechanics. Anthropic uses explicit cache markers with five-minute and one-hour lifetimes, with reads billed at a tenth of the input price. OpenAI caches automatically, and Google's Gemini models support both implicit caching, introduced with a 75% discount for Gemini 2.5, and explicit caches. Discounts and minimum prompt sizes vary by model, so check current pricing pages rather than assuming one number.

Batch processing at about half price is available as OpenAI's Batch API, Anthropic's Message Batches, and Gemini's Batch Mode. For routing, gateways such as OpenRouter, LiteLLM, and Portkey provide one API across many models and providers, and RouteLLM offers open-source trained routers. Observability tools such as Langfuse and Helicone, along with the eval platforms from the evals post, track cost per trace and per feature.

Per-token prices keep falling as models improve, but total spending often rises anyway, because agents use far more tokens than chat. Cheaper tokens make waste cheaper too; they do not make it disappear.


Summary

An AI feature's cost is not a property of the model. It is a property of your design: what you send on every call, what you keep in the history, how much you let the model write, and which model you ask. The same agent can cost $1.16 or $0.11 per conversation depending on choices that users never see.

So treat tokens like any other resource you pay for. Measure them per feature, cache what repeats, trim what nobody reads, and send each request to the cheapest model that can do it well, with evals proving that "well" still holds. Most of the savings come from removing waste, not from giving anything up.


Part of the Applied AI series: AI from the builder's side.



×