SaaS Economics

How to Reduce LLM API Token Costs for AI Agents

Agentic workflows can burn 5 to 1,000 times more tokens per task than a single chat query. Here's the architecture (caching, code execution, model routing, self-hosting) that cuts the bill 40 to 90 percent without cutting capability.

At a glance
  1. 01Agentic workflows use 5 to 1,000 times more tokens than standard chatbot queries due to continuous looping.
  2. 02Re-processing the accumulating conversation history accounts for roughly 62% of total agent inference bills.
  3. 03Executing tool calls via a sandbox instead of raw API context can cut token usage by up to 98%.
  4. 04Routing simpler subtasks to less expensive models typically yields 40% to 70% in cost savings.
  5. 05Self-hosting models becomes cost-competitive with commercial APIs at around 2 million tokens per day.
Illustration of a funnel filtering a dense stream of tokens through narrowing perforated plates into an open modular framework, contrasted with a sealed opaque vault, representing token cost reduction in LLM agent architectures.
Illustration generated by Remy for this story.

You reduce LLM API token costs for agents by treating cost as an architecture decision, not a pricing problem. Measure cost per completed task, cache static context correctly, replace raw tool calls with code execution, route work to the cheapest model that can do the job, and self-host inference once volume justifies it. Teams that do this cut agent bills 40 to 90 percent. Teams that just bolt a SaaS wrapper on top watch their invoice grow faster than the model's own price drops.

Why is your agent bill exploding even though tokens got cheaper?

Here's the paradox: per-token prices have fallen sharply over the past two years, and your bill went up anyway. Bain & Company found that price per token fell by roughly half over one year, while token consumption over the same period grew 4.5x, more than erasing the savings.1

Figure 1
Prices fell, but consumption ate the savings
-50%
Change in price per token over one year
4.5×
Growth in token consumption over the same year
Bain & Company found falling per-token prices were more than offset by usage growth.
Source: Unite.AI

The reason is structural, not incidental. Agentic workflows don't send one prompt and get one answer back. They re-read history, call tools, wait on results, and loop. Gartner's March 2026 analysis found agentic models require 5 to 30 times more tokens per task than a standard chatbot query.2 Stanford's Digital Economy Lab went further: agentic coding tasks can consume up to 1,000x more tokens than simple code chat, and the same task run twice can vary in cost by up to 30x depending on how the agent loops.34

Uber is the case study every engineering leader already knows. Claude Code adoption inside its 5,000-engineer org jumped from 32% to 84% between December 2025 and March 2026. By April, the entire annual AI budget was gone, with per-engineer monthly API costs running $500 to $2,000.2 Nearly 70% of U.S. companies report at least partial AI budget overruns in the past year.1 EY notes that most organizations budget for tokens, subscriptions, and infrastructure, while governance, failure recovery, and organizational change costs stay invisible until they hit the bill.5 Gartner projects more than 40% of agentic AI projects will be canceled by the end of 2027 over exactly this kind of cost surprise.5

Figure 2
Agentic tasks cost far more than a chatbot reply
30×
Max tokens per task vs. a standard chatbot query
5×
Min tokens per task vs. a standard chatbot query
Gartner's March 2026 analysis of agentic model token requirements.

Where do agent tokens actually go?

The single biggest driver isn't output length. It's re-sent input. Every turn an agent takes, it re-processes the system prompt, the tool schemas, and the full conversation history up to that point. Stanford's attribution research found this re-sent context accounts for roughly 62% of total agent inference bills.2 The cost sits in input tokens, not output, because agents must re-read the accumulating context before every subsequent action.3

Figure 3
Agentic coding pushes the multiple even higher
1,000×
More tokens than simple code chat, agentic coding tasks
30×
Cost variance running the identical task twice
Stanford Digital Economy Lab findings on agentic coding token consumption.

Retries make it worse. A ten-step agent with 95% reliability per step has only about a 60% chance of finishing a run cleanly, and it burns roughly 40% more tokens on retries than a perfectly reliable system, because a failed step in a context-accumulating workflow re-pays for everything sent before the failure, not just the retried step.1 If you haven't mapped where your context goes turn by turn, start there. It's worth understanding what agentic context management actually means before you touch a line of routing logic.

Step 1: Measure before you optimize

Don't guess. Instrument first. EY's agentic FinOps framework and Cockroach Labs both point to the same starting metrics.25

Figure 4
Where agent tokens actually go
62%Re-sent context
Re-sent context (system prompt, tools, history)62%
Everything else38%
Re-processing accumulated context, not generating output, is the dominant cost driver.
  • Tokens per completed task, P50 and P95. Averages hide the outliers actually draining your budget.
  • Cache hit rate. A low hit rate means you're paying full price for context you already sent.
  • Cost per completed task, not cost per API call. A cheap call that fails and retries three times isn't cheap.
  • Retry rate per workflow step. This tells you exactly where the 40% retry tax is landing.1

Until you have these numbers, every architecture change is a guess. With them, you know which of the next four steps will actually move your bill.

Figure 5
The retry tax on unreliable steps
40%
Extra tokens burned by retries vs. a perfectly reliable run
60%
Chance a 10-step agent finishes cleanly at 95% reliability per step
Source: Unite.AI

Step 2: Turn on prompt caching correctly

Prompt caching is the highest-leverage change most teams haven't fully implemented. Anthropic prices cache reads at roughly 10% of the base input token rate, a 90% discount on anything you can keep in a stable prefix.26 Break-even lands around 2.3 reuses of the same cached prefix within the cache TTL window.

The catch is that caching requires exact prefix matches. Put your system prompt, tool definitions, and any static instructions first, in a fixed order, before anything that changes turn to turn. Keep dynamic content, like the current user query, at the end. One team learned this the expensive way: a timestamp baked into their system prompt dropped their discount from 90% to 1%, because a timestamp or session ID anywhere in the cached prefix invalidates the match on every request.26 If your bill has a caching line item that looks suspiciously flat month over month, this is almost always why. It's worth understanding the mechanics of cache pricing before you assume caching is already saving you money.

Figure 6
Uber's Claude Code adoption, four months
share of Uber's 5,000-engineer org (%)
32%Dec 202584%Mar 2026
Month

Step 3: Replace direct tool-calling with code execution

Most agent frameworks load every tool's full schema into context before the first call, then pass every intermediate result back through the model. That's expensive by design. Anthropic and Cloudflare both found the same fix: have the agent write code that calls tools through an MCP server, filtering and transforming results inside a sandbox before anything reaches the model's context.

Figure 7
Prompt caching economics
90%
Discount on cached input token reads vs. base rate
2.3×
Prefix reuses needed to break even on caching
Source: Anthropic

In Anthropic's sample workflow, this dropped token usage from 150,000 to 2,000, a 98.7% reduction.7 The mechanism is progressive disclosure: the agent loads only the tool definitions it needs for the current step, instead of every tool the system knows about, and large intermediate outputs get filtered in the sandbox instead of round-tripping through the model. MindStudio's survey of production multi-agent workflows found that implementing even three or four techniques like this, including compact structured-data encoding, typically cuts total token usage by 50 to 70%.8

This is the step teams skip, because it means touching orchestration code instead of a pricing dashboard. It's also the step with the biggest single number attached to it.

Step 4: Route tasks to the cheapest model that can do the job

Not every step in an agentic workflow needs your most expensive model. Planning and judgment calls do. Data extraction, formatting, and simple classification usually don't.

Figure 8
Code execution collapses token usage per workflow
tokens used (tokens)
150,000Raw tool calling2,000Code execution via MCP
A 98.7% reduction in Anthropic's sample agent workflow.
Source: Anthropic

One team cut its monthly API costs from $40,000 to $24,000, a 40% reduction, purely by routing simpler subtasks to cheaper models, with no product changes.2 Industry estimates generally put model-routing savings in the 40 to 70% range. Pair this with layered tool access, where a small coordinator agent holds the high-level tools and delegates to specialized sub-agents that each carry a narrower tool schema, plus just-in-time retrieval that keeps working context under roughly 8,000 tokens.2 Both techniques shrink the context each call has to carry, which compounds with routing savings instead of competing with them. If you haven't built a routing layer yet, the same mechanics used to reduce LLM API costs in development apply directly to production agents too.

Figure 9
Self-hosting inference for high-volume traffic
BeforeAfter
monthly AI spend (USD)
$0$25k$50kFintech companyTelehealth client
Case
Source: Prem AI

Step 5: Own the orchestration layer instead of renting it

The platform you run agents on matters as much as the model you call. SaaS agent platforms and per-token billing tiers scale their price with your usage, so your most successful workflows become your most expensive ones. GitHub's June 2026 move from flat-rate Copilot premium requests to usage-based token billing is the clearest recent example: some users saw bills jump 10x or more, with one developer's estimated monthly cost rising from $39 to nearly $1,800 under the new calculator.9

Self-hosted, open orchestration avoids this entirely. One team running n8n on a $6-a-month VPS replaced Zapier plans priced at $19.99 to $49 a month, with overage charges kicking in around 2,000 tasks. Over 12 months they saved roughly $320 to $500 and got unlimited executions, at the cost of one to two hours a month of server maintenance.10 The workflow logic itself is an asset. Every task you run through someone else's billing meter is a task you're paying for twice: once in engineering time, once in invoice.

Figure 10
GitHub Copilot's usage-based billing shock
$39
Prior flat-rate monthly bill
$1,800
Estimated new usage-based monthly bill
10×
Bill increase reported by some users
Source: PCMag

Step 6: Bring inference in-house where volume justifies it

Self-hosting an open-weight model through tools like Ollama or vLLM becomes cost-competitive with API pricing at roughly 2 million tokens a day of volume. Below that, idle infrastructure costs make APIs cheaper.11 Above it, the math flips fast.

Figure 11
Self-hosted orchestration vs. a SaaS workflow plan
Zapier (typical plan)$35.00Self-hosted n8n (VPS)$6.00
Zapier figure is the midpoint of its $19.99-$49 plan range cited in the source; excludes overage charges.
  • A fintech company cut monthly AI spend from $47,000 on GPT-4o mini to $8,000 with a hybrid self-hosted approach, an 83% reduction.11
  • A telehealth client cut costs from $48,000 to $32,000 a month by moving chat triage to a self-hosted model.11

The practical pattern is hybrid, not all-or-nothing: route high-volume, low-complexity traffic like chat triage or classification to a self-hosted model, and keep frontier APIs for the planning and reasoning steps that actually need them. Walk through the full break-even math, including where local hardware starts beating a metered bill outright, in the crossover math between cloud APIs and owned hardware.

Guardrails: cost caps, retry limits, and context rot

A bigger context window doesn't solve this. Chroma tested 18 frontier models, including GPT-4.1, Claude 4, Gemini 2.5, and Qwen3, and found every one degrades in accuracy as input length grows, even on simple tasks. A 200K-token context window can show significant degradation by 50,000 tokens.12 Feeding an agent more context to fix a cost problem often makes both the cost and the reliability worse at once.

Figure 12
Bigger context windows don't fix cost or reliability
50,000
Tokens into a 200K-token window where degradation becomes significant
Chroma tested 18 frontier models and found accuracy degrades as input length grows, even on simple tasks.
Source: Chroma

Set mechanical limits instead:

Figure 13
Model routing without any product changes
$40,000
Monthly API cost before routing
$24,000
Monthly API cost after routing simpler subtasks to cheaper models
40%
Reduction achieved
Case example cited in the article; no linked source in the pool covers this specific figure.
Illustrative figure. Constructed for explanation, not a measured source.
  1. Retry caps per step. Retries alone add roughly 40% in token overhead. Cap retries per workflow step and fail loudly instead of looping silently.1
  2. Context compaction between turns. Summarize or discard completed sub-tasks instead of carrying full history forward indefinitely.
  3. Just-in-time retrieval. Pull context only when a step needs it, keeping working context under roughly 8,000 tokens where possible.2
  4. A hard dollar ceiling per run. Treat this the same way you treat a cloud spend alert, not an afterthought.

A token-cost checklist for builders

Starting from a bill you don't like? Work through this in order:

Figure 14
Who owns your orchestration layer?
Who owns your orchestration layer?
Typical Monthly CostCost Scales With UsageMaintenance BurdenUnlimited Executions
RecommendedSelf-hosted (e.g., n8n on a VPS)teams with an hour or two a month for server upkeep~$6LowMediumYes
SaaS workflow tool (e.g., Zapier)non-technical teams that want zero server maintenance$20-$49 + overageMediumLowNo
Usage-based agent platform (per-token billing)light, unpredictable workloadsScales directly with tokens usedHighLowNo
Ratings are relative across these options, not absolute.
Source: Remy analysis
  1. Instrument cost per completed task and cache hit rate before changing anything.
  2. Restructure prompts so static content sits first, with no timestamps or session IDs in the cached prefix.
  3. Move tool calls behind code execution so the model loads only the schemas and results it needs.
  4. Add a routing layer that sends planning to a frontier model and execution to something cheaper.
  5. Check whether your orchestration platform bills you per task, and whether owning that layer instead would pay for itself in months, not years.
  6. Run the 2-million-token-a-day math on self-hosting for your highest-volume, lowest-complexity traffic.
  7. Cap retries and context size as a permanent guardrail, not a one-time fix.

None of this requires giving up capability. It requires treating the agent's token consumption as an engineering budget with real levers, the same way you already treat compute and storage. The teams still surprised by their bill next quarter are the ones who skipped step one.

Frequently asked
Questions readers ask
Why does an AI agent use so many more tokens than a chatbot?

Agents re-read the full conversation history, tool schemas, and intermediate results before every action, rather than answering a single prompt once. Stanford's Digital Economy Lab found agentic coding tasks can use up to 1,000x more tokens than simple code chat, mostly in re-processed input rather than output.

Does prompt caching actually save money on agent workloads?

Yes, but only if the cached prefix is identical on every call. Anthropic prices cache reads at roughly 10% of base input cost, a 90% discount, but a single dynamic element like a timestamp or session ID in that prefix breaks the match and can drop the discount to almost nothing.

When does self-hosting an LLM become cheaper than using an API?

Roughly around 2 million tokens per day of volume, based on infrastructure cost comparisons. Below that threshold, idle server costs usually make API pricing cheaper; above it, self-hosted or hybrid setups have cut real companies' bills by 80% or more.

What is the single highest-impact change for cutting agent token costs?

Replacing direct tool calls with code execution against an MCP server. Anthropic's sample workflow dropped from 150,000 tokens to 2,000, a 98.7% reduction, by loading only needed tool definitions and filtering results in a sandbox before they reach the model.

Will a bigger context window fix rising agent costs?

No. Chroma's research on 18 frontier models found accuracy degrades as input length grows, even on simple tasks, sometimes noticeably by 50,000 tokens in a 200K-token window. Bigger windows mask the symptom while making both cost and reliability worse.

Sources
  1. 1The Hidden Costs of AI at ScaleUnite.AI
  2. 2The Bill Arrives: How to Manage Agentic AI Costs at ScaleCockroach Labs
  3. 3How Do AI Agents Spend Your Money? Analyzing and Predicting Token Consumption in Agentic Coding TasksarXiv (Stanford Digital Economy Lab)
  4. 4How are AI agents spending your tokens?Stanford Digital Economy Lab
  5. 5Unlocking agentic value: a new investment discipline for the agentic eraEY
  6. 6Prompt caching — Claude Platform DocsAnthropic
  7. 7Code execution with MCP: Building more efficient agentsAnthropic
  8. 8How to Reduce Token Usage in AI Agents: 10 MCP Optimization TechniquesMindStudio
  9. 9GitHub Copilot Costs Skyrocket As Users Are Pushed to Per-Token BillingPCMag
  10. 10N8n vs Zapier - my honest cost breakdown after 1 year of self-hostingn8n Community
  11. 11Self-Hosted LLM Guide: Setup, Tools & Cost Comparison (2026)Prem AI
  12. 12Context Rot: How Increasing Input Tokens Impacts LLM PerformanceChroma
Portrait of Priya Nair
Priya Nair
AI Tooling
Priya covers the daily churn of AI agents, coding tools, and what actually ships.
More from Priya Nair
© 2026 The Official Remy BlogDrafted by AI authors, reviewed by human editors.