Jatin Gupta
Jatin Gupta
Senior Architect @ HCL Tech
Jatin Gupta

Blog

Running Agentic AI on a Token Budget: Cutting Agent Cost 10× Without Losing Reasoning Quality

Running Agentic AI on a Token Budget: Cutting Agent Cost 10× Without Losing Reasoning Quality

Agentic AI Token Economics LLM Engineering

Running Agentic AI on a Token Budget: Cutting Agent Cost 10× Without Losing Reasoning Quality

Agent loops replay their entire context on every step. That single property is why most agentic pilots look brilliant in a demo and indefensible in a budget review — and why token architecture, not model choice, decides whether your agent ships.

August 2026
14 min read
Applied AI Engineering
10×
Achievable token reduction per resolved task
90%
Discount on cached prefix reads vs. base input price
60%
Of agent calls routable to a cheaper model tier
The Economics Problem

Agent loops are quadratic, and nobody budgets for that

A single-turn LLM call is easy to reason about: you send a prompt, you pay for it once. An agent is a different animal. On every step of the loop, the model receives the system prompt, the full tool catalog, and the entire accumulated history of everything it has already done — every reasoning turn, every tool call, every observation returned. Step twelve pays for steps one through eleven all over again.

The consumption curve is therefore not linear in steps. It is roughly quadratic. Double the number of steps and you roughly quadruple the token bill. This is why teams are consistently blindsided: the pilot ran three-step workflows and cost almost nothing, then production hit fourteen-step incident investigations and the invoice went up by two orders of magnitude.

Loop lengthTokens added per stepCumulative input billedRatio
3 steps2,800~25,500baseline
7 steps2,800~98,7003.9×
14 steps2,800~334,60013.1×
14 steps, unshaped log dumps12,000~1,171,80046.0×

Assumes a 5,700-token static prefix (tool schemas plus system policy). Note the last row: the only variable that changed was how much text each tool returned. A retrieval tool that dumps raw log lines instead of a shaped summary can, on its own, multiply your bill by 3.5× — without the agent doing anything differently or getting any smarter.

The governing insight: in an agent, every token you add is paid for once per remaining step, not once. A 2,000-token block inserted at step 2 of a 14-step loop costs you 26,000 tokens, not 2,000. Optimization pressure belongs at the point where context enters the loop.

Diagnosis

Where the tokens actually go

Before optimizing anything, instrument the loop and break the consumption down by origin. Across production agent deployments the distribution is remarkably consistent, and it is almost never where teams assume.

SourceTypical shareWhy it growsCompressible?
Tool results / observations55–75%Raw payloads, log lines, JSON blobs returned verbatimVery high
Tool schema definitions10–20%Re-sent in full on every single stepHigh
Accumulated reasoning turns8–15%Never pruned; superseded hypotheses persist foreverHigh
System prompt & policy4–10%Static, but re-sent every stepCacheable
Generated output2–6%Small volume, but billed at 4–5× the input rateModerate

Two conclusions follow immediately. First, the biggest lever is not the model or the prompt — it is what your tools return. Second, the second-biggest lever is how much of the context is byte-stable enough to cache. Teams that spend a month rewriting their system prompt to be more concise are optimizing a 6% line item while a log-search tool quietly burns the other 70%.


Architecture

What a token-optimized agent loop looks like

The optimized architecture separates context into four zones by volatility. Everything immutable sits at the front behind a cache breakpoint. Everything voluminous gets shaped before it ever enters the transcript. Everything stale gets compacted out. And everything that can be decided without a frontier model gets routed away from one.

font-family="Inter, 'Helvetica Neue', Arial, sans-serif"> TOKEN-OPTIMIZED AGENTIC AI LOOP CONTEXT ARCHITECTURE FOR AGENTS THAT STAY AFFORDABLE AT SCALE CONTEXT ASSEMBLY TOOL SCHEMAS SYSTEM + POLICY RUNBOOK INDEX ▲ CACHE BREAKPOINT VOLATILE TASK INPUT IMMUTABLE PREFIX (Byte-stable · written once · read at 0.1×) PERCEPTION & ROUTING SIGNAL IN PRE-FILTER dedupe · suppress · recurrence check SMALL TIER classify · extract LARGE TIER plan · reason ~60% OF CALLS ROUTE SMALL TIER SELECTION (Cheapest model that holds quality) PLANNING & STEP BUDGET 9 STEPS ALLOWED PLAN STEPS THRASH GUARD BOUNDED REASONING (Steps are quadratic — cap them) MEMORY & COMPACTION 28k tokens COMPACT STATE 1.2k SCRATCHPAD EVIDENCE ON DISK (Pointer in context, not payload) VERIFICATION & OUTPUT SCHEMA-VALID JSON max_tokens CAP CAPPED OUTPUT (Billed at 4–5× input rate) TOOL EXECUTION RAW DUMP ✕ SHAPE TOP-N ✓ aggregates + drill-down pointer SHAPED RESULTS VIA MCP (55–75% of all tokens start here) CONTEXT BUDGET ENGINE STEPS ARE THE COST DRIVER AGENT LOOPS ARE QUADRATIC Every step replays the entire prior transcript TOOL OUTPUT IS 55–75% OF SPEND Shape it at the source 10× FEWER TOKENS PER RESOLVED TASK PROMPT CACHING reads at 0.1× base input TOOL BUDGETING defer · scope · trim schemas MODEL TIERING small by default, escalate BATCH API 50% off async workloads CACHE WHAT NEVER CHANGES · SHAPE WHAT ENTERS · COMPACT WHAT IS STALE · ROUTE WHAT IS EASY · CAP WHAT IS GENERATED
The token-optimized agentic AI loop: assemble a byte-stable prefix, route by difficulty, bound reasoning steps, compact memory, and cap output.

Mindset Shift

Context is a budget, not a bucket

🪣

The bucket model

"We have a million-token window, so let's give the agent everything and let it figure out what matters." Every document, every log line, every tool. Quality is assumed to scale with information volume. Cost scales quadratically, latency degrades, and — worse — accuracy often drops as relevant evidence gets diluted by noise.

Stuff the window All tools always loaded Raw payloads
📐

The budget model

Every step gets an explicit token allowance, allocated by value. Instructions and guardrails are non-negotiable. Output is reserved first. Evidence competes for what remains, ranked by relevance. The window is treated as a working desk with finite surface area, not a warehouse — because that is exactly what attention makes it.

Reserved output budget Ranked evidence Shaped observations

The budget model is not merely cheaper. Long-context evaluations consistently show retrieval and reasoning degrading as irrelevant context grows — the model spreads attention across noise. Token discipline and answer quality point the same direction far more often than teams expect, which is what makes this optimization unusually easy to justify: you are not trading accuracy for cost.


Implementation

Seven levers, ordered by leverage

Apply these in order. The first three typically deliver 80% of the total saving, and none of them require touching your model or your prompt wording.

Lever 01

Make the prefix byte-stable, then cache it

Prompt caching is the single highest-return change available, and it is mostly a discipline problem rather than an engineering one. On the Claude API, cached prefix reads bill at 10% of the base input rate; a five-minute cache write costs 1.25× and a one-hour write costs 2×, so the cache pays for itself after one or two reads. Caching covers tools, then system, then messages — in that order — up to your breakpoint.

The catch is that the cache is keyed on exact bytes. One timestamp, one incident ID, one interpolated username above the breakpoint and you pay full price for the entire prefix, every step, forever. This is the most common silent failure in agent deployments: teams enable caching, never check cache_read_input_tokens, and assume it is working.

# WRONG — dynamic values poison the cacheable prefix system = f"You are an incident agent. Time: {now}. Incident: {inc_id}." # RIGHT — static above the breakpoint, dynamic below it tools = TOOL_SCHEMAS # stable system = [ {"type": "text", "text": STATIC_POLICY, "cache_control": {"type": "ephemeral"}} # ← breakpoint ] messages = [ {"role": "user", "content": f"Time: {now}\nIncident: {inc_id}\n{task}"} # volatile ]

Then verify it. Log cache_read_input_tokens and cache_creation_input_tokens on every call and alert when the creation-to-read ratio spikes — that is your signal that someone shipped a prompt change or introduced a dynamic value into the prefix.

Lever 02

Shape tool results at the source

This is where the majority of the saving lives, and it is entirely within your control because you write the tools. The rule: a tool returns a decision-grade summary, never a data dump. If a human wouldn't read all 4,000 lines, the model shouldn't receive them either.

// ✗ 14,000 tokens of noise search_logs(query, window) → [ ...4,200 raw log lines... ] // ✓ ~380 tokens, strictly more useful search_logs(query, window) → { matched: 4200, by_level: { ERROR: 3891, WARN: 309 }, distinct_signatures: 3, top_signatures: [ { pattern: "conn pool exhausted", count: 3854, first_seen: "01:52:11Z", sample_id: "log_88f21" }, ... ], histogram_60s: [12, 14, 890, 1204, 1180, ...], drill_down: "logs.fetch_by_signature(sig_id, limit)" }

Note the drill_down pointer. The agent retains the ability to fetch detail when it genuinely needs it — but it now makes that an explicit, deliberate, once-per-investigation decision rather than paying for full fidelity on every speculative query. Pair this with hard response caps enforced server-side: no tool may return more than N tokens, ever, regardless of what the underlying query matched.

If you change nothing else in this article, change this. In most deployments, capping and summarizing tool responses alone cuts total token consumption by 50–65% — and it typically improves diagnostic accuracy, because the model stops drowning in near-duplicate log lines.
Lever 03

Budget the tool catalog

Tool definitions are re-sent on every single step. Forty tools at an average 200 tokens each is 8,000 tokens per step — 112,000 tokens across a fourteen-step loop, spent entirely on describing capabilities the agent will never invoke on this particular task.

Three fixes, in increasing sophistication: trim the descriptions (they are prose, and most are twice as long as they need to be); scope the catalog by task phase, so the triage phase loads observability tools only and the remediation phase loads execution tools only; and defer — expose a search-and-load mechanism where the agent discovers tools by keyword and only the matching definitions are injected. Deferred loading is the strongest option once you pass roughly twenty-five tools.

Catalog strategyPrefix cost / step14-step loopTrade-off
All 40 tools, verbose8,000112,000None — pure waste
All 40, trimmed descriptions4,80067,200Slightly higher mis-selection risk
Phase-scoped (12 tools)1,70023,800Needs phase detection logic
Deferred / search-loaded~600~11,000One extra discovery round-trip
Lever 04

Compact aggressively, and offload the rest to disk

Halfway through an investigation, most of the transcript is dead weight: hypotheses that were ruled out, tool calls that returned nothing, intermediate reasoning that has been superseded. Compaction replaces that history with a compressed state object — decisions and confirmed facts retained, raw evidence discarded.

COMPACTION POLICY trigger : step_count % 6 == 0 OR context_tokens > 60% of budget preserve : original task, confirmed facts, ruled-out hypotheses, actions already taken, open questions discard : raw tool payloads, superseded reasoning, failed queries offload : full evidence → scratchpad file, keep pointer only result : ~1,200-token state block replaces ~28,000 tokens of history

The offload half matters as much as the compression. Give the agent a working file it can write findings into and read back selectively. Evidence lives on disk; the context window holds a pointer. This is the difference between an agent that can sustain a forty-step investigation and one that hits its ceiling at twelve — and it makes the investigation auditable as a side effect, because the scratchpad becomes the evidence trail.

Lever 05

Isolate expensive sub-tasks in sub-agents

When a sub-task requires burning through large volumes of context — scanning six months of change records, reading forty runbook definitions to find the right one — do not do it in the main loop. Spawn a sub-agent with a clean context, let it consume what it needs, and have it return only its conclusion.

The parent loop receives 300 tokens of answer instead of inheriting 40,000 tokens of search transcript that it will then carry, and pay for, on every subsequent step. Context isolation is the architectural version of the quadratic insight: keep the expensive stuff out of the loop that repeats.

Lever 06

Route by difficulty, not by habit

Most agent steps are not reasoning steps. They are classification ("is this alert real?"), extraction ("pull the service name from this payload"), and formatting — tasks a small fast model handles at parity. Published Claude API rates put Haiku 4.5 at $1/$5 per million tokens against Sonnet 5 at $2/$10 and Opus 5 at $5/$25, so the tier gap is real money at volume.

Alert triage
Small tier
Field extraction
Small tier
Log summarization
Small tier
Schema formatting
Small tier
Cross-system RCA
Large tier
Multi-step planning
Large tier
Runbook selection
Large tier
Risk assessment
Large tier

In a mature incident agent, roughly 60% of calls land in the small tier. Route on a cheap signal — incident class, step type, confidence threshold — and escalate on failure rather than starting expensive. One caveat worth respecting: never route planning down a tier to save money. A weak plan generates more steps, and more steps cost far more than the model-tier difference you saved.

Lever 07

Cap the output, and pre-filter with plain code

Output tokens bill at four to five times the input rate, and extended-thinking tokens bill as output. Set an explicit max_tokens per step type — a routing decision needs 150 tokens, not 4,000 — and demand structured fields rather than prose. Let the ticket template render the narrative; the model should emit data.

Then look upstream. A meaningful share of what agents get asked to evaluate can be decided by a rule, a regex, or a lookup for effectively zero cost. Deduplicate the alert storm, suppress known-benign patterns, and check the recurrence table before invoking the model. The cheapest token is the one you never send.

Finally, for work that genuinely tolerates latency — nightly evals, prompt regression suites, bulk enrichment, backfill classification — the Batch API applies a flat 50% discount that stacks with caching. It is not usable for interactive agent loops, which need multi-turn synchronous tool use, but the offline half of your pipeline is often larger than teams realize.


Worked Example

One incident investigation, before and after

A fourteen-step cross-cloud latency investigation: correlate an alert, check recent changes, walk the dependency graph, query logs across two tools, form a hypothesis, select a runbook, and hand off. Same task, same quality bar, two architectures.

ComponentNaive loopOptimized loopChange
Tool schemas (re-sent per step)44,8008,400−81%
System prompt & policy35,0002,500−93%
Tool observations254,80019,100−93%
Reasoning turns retained18,4004,200−77%
Generated output4,9002,900−41%
Steps to resolution149−36%
Total tokens billed357,90037,1009.6× lower
Naive — 40,000 events / month
$28.6k / mo
At published Sonnet-tier rates. Latency 90–140s per investigation. Context ceiling reached on complex incidents, forcing premature escalation.
Optimized — same volume
$2.4k / mo
Caching, shaping, compaction, and routing combined. Latency 25–40s. Headroom for 40-step investigations without hitting the window.

Two things worth noticing. First, the step count itself dropped — better-shaped tool results meant fewer clarifying round-trips, so the saving compounds rather than adds. Second, the cost reduction outruns the token reduction once cache reads are priced in, because the prefix is now paid at a tenth of base rate for the majority of steps. Figures are illustrative and rate-dependent; verify current pricing before building a business case on them.


Measurement

Measure per resolved task, never per call

Cost-per-API-call is a misleading metric for agents — it rewards splitting work into more, smaller calls, which is exactly the wrong incentive. The unit that matters is the completed task.

  • Tokens per resolved task — the headline number. Track the median and the p95; the tail is where budgets die.
  • Cache hit rate — cache reads as a share of total input. Below 60% on a stable workload means something is poisoning your prefix.
  • Tool-output token share — if this exceeds 50%, your next optimization is a tool, not a prompt.
  • Steps per resolution — rising step counts usually mean the agent is thrashing on ambiguous tool results.
  • Small-tier routing share — with quality held constant. A rising share at flat accuracy is pure margin.
  • Compaction loss rate — how often a compacted agent re-queries something it already knew. This is your over-compression alarm.

Wire a token budget into CI. Run a fixed scenario suite on every prompt or tool change and fail the build when median tokens-per-task regresses beyond a threshold. Token consumption drifts upward silently otherwise — one verbose tool description at a time.


Guardrails

Where over-optimization starts costing more than it saves

Every lever here has a failure mode on the far side of it. Token optimization that degrades reasoning quality is not a saving — it converts cheap automated resolutions into expensive human escalations, which is a strictly worse trade.
  • Summarizing away the evidence. If a tool summary drops the one anomalous field that explained the incident, you have optimized your way into a wrong answer. Preserve outliers and distinct signatures explicitly, not just top-N by frequency.
  • Compacting the decision trail. Compaction must retain what was ruled out and why. Drop that and the agent re-investigates the same dead end, spending more tokens than compaction saved.
  • Routing planning to a small model. Cheap per call, expensive per task. Plan quality determines step count, and step count dominates the bill.
  • Cache-driven prompt rigidity. Teams stop improving prompts because changes invalidate the cache. Version the prefix deliberately and accept a warm-up window; a better prompt that cuts two steps beats a stale cached one.
  • Trimming tool descriptions into ambiguity. Tool descriptions are the model's selection interface. Over-trim and mis-selection rises, which costs more in retries than the description ever cost in tokens.

Rollout

A three-phase sequence

Phase 01
Instrument & cache
Log token attribution by source on every call. Restructure the prefix for byte-stability and set the cache breakpoint. Verify cache reads are actually landing. Typically 30–45% saving in under two weeks, with zero change to agent behaviour.
Phase 02
Shape & scope
Rewrite the three highest-volume tools to return summaries with drill-down pointers. Enforce server-side response caps. Trim and phase-scope the tool catalog. This is the largest single block of saving — expect the token curve to bend hard here.
Phase 03
Compact & route
Add compaction triggers, scratchpad offload, and sub-agent isolation for context-heavy sub-tasks. Introduce tier routing with escalation on failure. Lock in the gains with a token-budget regression suite in CI.


Quick Reference

Agentic AI Token Budget, Explained

The whole token-optimization playbook on one page: prompt caching, tool shaping, compaction, and model routing — and where each lever saves its share.

Agentic AI Token Budget Explained ( Prompt Cache + Tool Shaping + Compaction + Model Routing ) * agent-request/ tools/ Tool schemas — re-sent EVERY step observability.json itsm.json runbook.json system/ Policy + guardrails — keep byte-stable cache_control << CACHE BREAKPOINT (reads at 0.1x) messages/ The ONLY part that should change task.md Volatile: IDs, timestamps live HERE history/ Compacted every 6 steps state-block.md 28k tokens -> 1.2k summary scratchpad.md Evidence on disk, pointer in context observations/ Shaped tool results top-n.json Aggregates + counts, NOT raw dumps drill-down.ref Fetch detail only when truly needed routing/ Model tier selection small-tier.yaml classify . extract . format (~60%) large-tier.yaml plan . reason . select runbook output/ Billed at 4-5x the input rate schema.json Structured fields, no prose padding max_tokens Hard cap per step type How it Works (per step) Signal in (alert / ticket) Pre-filter (dedupe, suppress) Cached prefix (read at 0.1x) Route tier (small vs large) Shaped tools (top-N + refs) Capped output (schema + cap) Where the Tokens Actually Go observations/ 55-75% BIGGEST lever - shape results at the source tools/ 10-20% defer, scope & trim schemas (re-sent each step) history/ 8-15% compact - keep decisions, drop raw evidence system/ 4-10% cache it, never interpolate dynamic values output/ 2-6% small volume, but 4-5x the price - cap it Result -> ~10x fewer tokens per resolved task, same answer quality
Agentic AI token budget explained — the handwritten cheat-sheet: what to cache, shape, compact, route, and cap.
The Takeaway

Token architecture is agent architecture

The instinct when an agent costs too much is to reach for a cheaper model. That is almost always the wrong first move — it trades reasoning quality for a linear saving while leaving the quadratic problem completely intact. A weaker model on an unoptimized loop takes more steps, and more steps is precisely what you could not afford.

The durable fix is structural. Cache what never changes. Shape what enters the loop. Compact what has gone stale. Isolate what is expensive. Route what is easy. Cap what is generated. Each of these is a design decision about context flow, not a model decision — and taken together they routinely deliver an order of magnitude while leaving answer quality flat or better.

Which is the part that makes this worth doing properly: for once, the cheap architecture and the good architecture are the same architecture.

AIOps Insights · Agentic AI, observability, and enterprise automation. Pricing figures reflect published rates as of August 2026 and should be verified against current provider documentation.

Add Comment

Related Posts