Cost Optimization Strategies: Token Budgeting and Cache-Aware Prompting
The economics of an agent turn — input, cached, and output tokens — plus per-turn and per-session budgets, cache-aware prompt design, history pruning as cost control, and a measurement loop that produces real savings.
Published on • November 27, 2026
AI Assistant

Agent costs don’t arrive as a bill you can act on; they arrive as thousands of small decisions you never reviewed — a system instruction grown by three paragraphs, a tool returning a raw JSON dump, a conversation history replayed in full on every turn. Each one is a few cents. Together they are the line item that makes finance ask questions.
This article is about the two levers that most reliably move that number: budgets (explicit limits on how many tokens a turn or a session may spend) and cache-aware prompting (designing prompts so the expensive parts are billed at cache rates).
Know the three prices you are paying
Every call bills three distinct things, at very different rates:
| Component | Scales with | Relative price | What inflates it |
|---|---|---|---|
| Uncached input | Everything sent: instruction + tools + history + RAG | Full input rate | Prompt bloat, re-sent history, big tool dumps |
| Cached input | The stable prefix reused within its TTL | Discounted (typically ~25% of input) | Only if your prefix is stable — see below |
| Output | What the model generates, including tool-call arguments | Highest rate | Verbosity, long tool arguments, unbounded answers |
Two structural facts follow:
- Input dominates in agents, because every round trip re-sends accumulated context. A ten-turn conversation costs its history ten times over.
- Output is the most expensive per token, which makes “the model writes a 600-word answer to a yes/no question” a real cost bug — and tool-call arguments part of output.
Measure before optimizing: client.models.count_tokens gives you the input side offline, and usage_metadata on each response gives the true billed counts (prompt, cached, output).
Budgets: making the limit explicit
A budget is a number you choose before the traffic, not after the invoice.
Per-turn input budget. Cap what a single turn may send:
MAX_TURN_TOKENS = 40_000
async def budgeted_turn(session_state, new_message):
projected = estimate_tokens(system_instruction, tool_schema, history, new_message)
if projected > MAX_TURN_TOKENS:
history = compact(history, target=MAX_TURN_TOKENS - projected - 1_000)
...
Per-turn output budget. Set max_output_tokens to something derived from your use case — a triage reply doesn’t need 8k tokens — and add an instruction constraint (“answer in three sentences”).
Per-session budget. For autonomous or long-running agents, track cumulative spend and degrade gracefully:
if session.state['tokens_spent'] > SESSION_BUDGET:
session.state['mode'] = 'terse' # shorter answers, fewer tools
session.state['auto_search'] = False # no grounding round trips
Per-call guardrails. A tool that would return 200 KB of JSON should truncate or summarise inside the tool, with a truncated: true flag the model can act on — rather than letting one bad tool result set the cost floor for the rest of the conversation.
Budgets work best as signals with defaults: warn at 80%, hard-stop at 100%, and log which budget bound first so you know where the pressure actually is.
Cache-aware prompting
Caching discounts the stable prefix — everything that must be identical byte-for-byte across requests within the cache’s lifetime. In an agent that prefix is: system instruction + tool declarations + (optionally) fixed reference material.
Design rules:
- Put volatile content last. History, retrieved chunks, and user input go after the stable prefix. One changed byte at position 100 invalidates everything behind it.
- Freeze the prefix. Version your instruction deliberately. A timestamp, a random trace ID, or “today’s date: …” injected at the top destroys every cache hit for that session.
- Don’t reshuffle tools. The tool declaration block is part of the prefix; adding, removing, or reordering tools mid-session invalidates the cache.
- Make the stable part big where it pays. The instruction, few-shot examples, and reference tables are exactly the content you want billed at cache rates — they’re large and identical every time.
Explicit caching for large fixed payloads (long documents, big example sets):
from google.genai import types
cached = client.caches.create(
model='gemini-3.8-flash',
config=types.CreateCachedContentConfig(
contents=[types.Content(role='user', parts=[
types.Part.from_uri(file_uri=doc_uri, mime_type='application/pdf'),
])],
system_instruction=SYSTEM_INSTRUCTION,
ttl='3600s',
),
)
response = client.models.generate_content(
model='gemini-3.8-flash',
contents='Summarise the key obligations.',
config=types.GenerateContentConfig(cached_content=cached.name),
)
A 400-page PDF read across fifty questions is a caching decision, not a token decision.
Cache-aware doesn’t mean cache-only
If the cache TTL lapses between user sessions, you pay full price for the next turn’s prefix — so match TTL to your real inter-turn gap (minutes for an active chat, longer for an agent that idles) rather than picking the maximum.
Pruning and compaction as cost control
History is where agent cost compounds. Three techniques, in increasing aggressiveness:
- Selective history pruning — drop tool payloads older than the point where they stop mattering; keep the conclusions, discard the raw dumps.
- Sliding window — keep the last N turns verbatim, summarise the rest.
- Compaction — replace a long prefix of the conversation with a generated summary, as covered in context compaction strategies.
Each trades a little recall for a large, compounding input saving. Measure quality on your eval set (an agent that forgets a constraint from turn 2 is a bug, not a saving) and pick the least aggressive option that meets your budget.
The measurement loop
- Attribute cost. Log per-turn tokens (uncached/cached/output), tool name, and agent — you cannot optimize a total.
- Find the outliers. Sort by input tokens; the top 5% of turns usually contain the biggest fixable waste.
- Change one thing, re-measure on the same replay set.
- Set a dashboard: cost per resolved conversation, cache hit rate, tokens per turn, and their trends at constant traffic — growth at flat volume means bloat.
- Gate changes in CI with a token budget for a fixed replay set, so prompt edits can’t silently add 30% to every request.
Targeted changes that reliably pay: collapse duplicated instructions between system prompt and tool docstrings; force structured tool returns instead of raw payloads; add max_output_tokens; make the prefix byte-stable; route easy turns to a cheaper tier.
Takeaways
- You pay three prices: uncached input (full), cached input (discounted), output (highest). Agents are input-dominated because history re-sends every turn.
- Set explicit per-turn, per-session, and per-tool budgets with warn/stop thresholds, and log which one bound first.
- Cache-aware design = stable prefix first, volatile content last, no timestamps or reordered tools in the prefix; match TTL to real turn gaps.
- Prune, window, then compact — each trades recall for compounding savings; verify on your eval set.
- Attribute cost per turn and tool, fix the top 5% of outliers, and gate prompt changes with a token budget in CI.