Token Intelligence Field Guide
Everything you need to understand, measure, and radically reduce AI token consumption. Search across all 32 topics or navigate by domain area above.
🔬 Token Fundamentals
● Critical
What Is a Token?
How text is split into tokens, why token counts differ from word counts, and why this matters for every AI cost.
→
● Critical
Token Pricing Across Models
Input vs output cost asymmetry, cache pricing, and real cost comparisons across frontier models.
→
● Important
Token Counting & Measurement
Count tokens before you send them. Tools, libraries, and pre-flight checks that prevent bill surprises.
→
● Critical
Token Budgets & Limits
Set hard and soft token budgets per request, per user, and per feature. Enforce graceful degradation before you hit limits.
→
🧬 Context Window Anatomy
● Critical
Full Context Anatomy
Dissect the 6 layers that fill your context window. Understand what's eating 95% of your tokens before the user even speaks.
→
● Critical
System Prompt Tokens
The silent cost multiplier. System prompts repeat on every single request — even 500 extra tokens costs thousands daily at scale.
→
● Critical
Conversation History Management
Every message keeps all prior turns by default. Naive history management is the #1 hidden cost driver in chat applications.
→
● Important
Tool Schema Tokens
Every tool definition you include costs tokens — even when the tool is never called. Lazy-load and compress schemas to cut overhead.
→
✍️ Prompt Optimisation
● Critical
Prompt Compression
Techniques to slash prompt length without losing meaning: instruction distillation, LLMLingua, and format optimisation.
→
● Critical
Output Token Control
Output tokens cost 3–5× more than input. Always set max_tokens, specify output format, and constrain verbosity explicitly.
→
● Important
Few-Shot Efficiency
More examples ≠ better results. Find the minimum effective shot count — most tasks need ≤3 examples when framed correctly.
→
● Important
Structured Output
JSON mode and constrained generation prevent verbose free-text responses and eliminate post-processing extraction tokens.
→
♻️ Caching & Reuse
● Critical
Prompt Caching (KV Cache)
Cache static context at the model layer — system prompts, documents, examples. Up to 90% reduction on cached tokens. Biggest single win available.
→
● Critical
Semantic Response Caching
Cache full responses for semantically similar queries. A vector-similarity lookup can serve 30–60% of requests with zero LLM calls.
→
● Important
Tool Result Memoization
Cache tool call results within and across agent runs. Expensive API lookups shouldn't re-execute on every loop iteration.
→
● Useful
Embedding Caching
Don't re-embed the same chunks. Persist vectors for static documents; only re-embed on actual content changes.
→
📚 RAG & Retrieval
● Critical
Chunk Sizing Strategy
Oversized chunks bloat context. Undersized chunks lose coherence. Find the sweet spot for your domain with hybrid chunking.
→
● Critical
Re-ranking & Precision Retrieval
Retrieve more, send less. A re-ranker filters top-50 candidates to 3–5 truly relevant chunks, slashing RAG context by 80%.
→
● Important
RAG Context Budget Control
Allocate a strict token budget to retrieved context. Enforce it with chunk truncation and relevance-based trimming.
→
● Important
Summary Indexing & RAPTOR
Build multi-level summaries of your corpus. Retrieve compact summaries for high-level queries instead of raw dense chunks.
→
🤖 Agentic Systems
● Critical
Agent Loop Token Explosion
Each iteration carries the full prior context. 10 iterations can cost 10–50× a single call. The most dangerous cost pattern in AI.
→
● Critical
Multi-Agent Overhead
Every agent-to-agent message serialises full context. Orchestrator patterns, shared memory, and message compression are essential.
→
● Critical
Planning & Reasoning Costs
Extended thinking and chain-of-thought reasoning generate thousands of tokens before the real response. Budget reasoning separately.
→
● Important
Tool Call Result Management
Raw API results dumped into context are token-wasteful. Extract only needed fields. A 50KB API response rarely needs more than 500 tokens.
→
🔀 Model Routing & FinOps
● Critical
Intelligent Model Routing
Route simple tasks to small, cheap models. Reserve frontier models for tasks that genuinely need them. 80% cost reduction possible.
→
● Important
Speculative Decoding
A small draft model generates candidates; the large model verifies in parallel. Reduces output latency without sacrificing quality.
→
● Important
Fine-Tuning for Prompt Reduction
Bake repetitive instructions into a fine-tuned model. Eliminate 80% of system prompt tokens for high-volume, predictable tasks.
→
● Important
Batch Processing
Async batch APIs offer 50% cost reduction for non-real-time tasks. Classification, summarisation, and enrichment jobs don't need streaming.
→
● Critical
Token Observability & Tracing
You can't optimise what you don't measure. Structured token telemetry per request, per feature, per user — the foundation of all FinOps.
→
● Important
Rate Limiting & Quotas
Per-user, per-feature, and per-team token quotas prevent runaway costs. Hard limits with graceful fallbacks protect budget.
→
● Important
Cost Attribution & Chargeback
Tag every token to a feature, team, or customer. Showback and chargeback models drive accountability and surface the real cost of each product decision.
→
● Important
Token Anomaly Detection
Detect cost spikes before your bill does. Automated anomaly detection on token velocity, request size, and per-user consumption patterns.
→
What Is a Token?
The atomic unit of all LLM computation and cost. Every character, word, and space resolves into tokens — and every token has a price.
Core Concept
LLMs don't process text directly — they process tokens: subword units generated by Byte-Pair Encoding (BPE). A token is roughly 3–4 characters or 0.75 words in English.
- "Hello world" → 2 tokens
- "Unbelievable" → 3 tokens (Un / believ / able)
- Code symbols, whitespace, numbers each tokenise differently
- Non-English languages use more tokens per word (2–4×)
Why It Matters
- Every API call is billed per input + output token
- Context windows have hard token limits (32K–200K+)
- Token count ≠ word count — estimating by words leads to budget errors
- Whitespace, punctuation, and formatting all count
- Tokens drive both cost and latency
Efficient Patterns
- Dense prose over bullet lists
- Short variable names in code prompts
- Remove redundant whitespace
- Abbreviate known terms
- Use JSON without extra spacing
Wasteful Patterns
- Excessive markdown formatting
- Verbose role descriptions
- Repeated context injections
- Raw XML/HTML in prompts
- Unnecessary examples
Token Ratios by Language
- English: ~4 chars / token
- Spanish/French: ~3.5 chars / token
- Chinese/Japanese: ~1.5 chars / token
- Code (Python): ~3 chars / token
- JSON: ~3.5 chars / token
# Count tokens before sending (Python + tiktoken)
import tiktoken
enc = tiktoken.encoding_for_model("gpt-4o")
tokens = enc.encode("Your text here")
print(f"Token count: {len(tokens)}")
# Anthropic SDK
client.beta.messages.count_tokens(
model="claude-sonnet-4-20250514",
messages=[{"role": "user", "content": "Your text"}]
)
Token Pricing Across Models
Output tokens cost 3–5× more than input tokens. Understanding cost asymmetry is the foundation of any token optimisation strategy.
Key Insight: Most organisations are shocked to find 60–80% of their AI bill comes from output tokens, which they have the most control over. Always set max_tokens and specify response format.
| Model | Input ($/1M) | Output ($/1M) | Cache Read | Best For |
|---|---|---|---|---|
| Claude Haiku 3.5 | $0.80 | $4.00 | $0.08 | High-volume simple tasks |
| Claude Sonnet 4 | $3.00 | $15.00 | $0.30 | Balanced production workloads |
| Claude Opus 4 | $15.00 | $75.00 | $1.50 | Complex reasoning, high-stakes |
| GPT-4o mini | $0.15 | $0.60 | $0.075 | Cost-sensitive applications |
| GPT-4o | $2.50 | $10.00 | $1.25 | Multimodal, broad tasks |
| Gemini 1.5 Flash | $0.075 | $0.30 | — | Ultra-high-volume, simple |
The Output Cost Trap
Output tokens are the largest cost lever most teams ignore. A model asked to "explain in detail" vs "summarise in 3 bullets" can produce 10× more tokens. Always instruct the model on output length and format explicitly.
Cache Pricing Advantage
Cached input tokens cost ~90% less on Anthropic models. A 2,000-token system prompt called 1,000 times/day costs $60/day uncached vs $6/day cached — $18,000/year difference at Claude Sonnet rates.
Token Counting & Measurement
Count tokens before you send them. Pre-flight counting prevents context overflows, enables graceful degradation, and gives you full cost visibility.
Counting Tools
- tiktoken — OpenAI's fast BPE tokeniser (Python)
- Anthropic count_tokens API — exact counts pre-send
- tokenize.js — browser-side counting
- LangChain token splitters — chunking-aware counting
- LlamaIndex token counters — pipeline-integrated
What to Log Per Request
- System prompt tokens (static overhead)
- History tokens (dynamic, grows over time)
- RAG context tokens
- Tool schema tokens
- User message tokens
- Output tokens (actual + budgeted)
- Cache hits vs cache misses
# Pre-flight token guard — abort before sending if over budget
def count_request_tokens(system, messages, tools=[]):
total = count(system) + count(tools)
for m in messages:
total += count(m["content"]) + 4 # 4 overhead per message
return total
def safe_call(system, messages, max_budget=8000):
tokens = count_request_tokens(system, messages)
if tokens > max_budget:
messages = truncate_history(messages, max_budget - count(system))
return client.messages.create(...)
Token Budgets & Limits
Budgets are the governance layer of token optimisation. Define them at every level — request, user, feature, team — and enforce them with graceful degradation.
Soft Budget (Warning)
70–85% of limit. Log a warning, notify the user that context is filling, begin proactive history summarisation. Don't break the experience.
Hard Budget (Enforce)
90% of limit. Truncate oldest history, compress RAG context, remove optional tool schemas. Maintain core functionality at minimum token footprint.
Emergency Limit (Block)
100% of limit. Return a structured error or fallback response. Never send a request that will fail or cost unexpectedly at the API layer.
Budget Dimensions
- Per-request — max context + max output tokens
- Per-session — cumulative tokens in a conversation
- Per-user/day — rate limiting individuals
- Per-feature — chat vs code gen vs summarisation
- Per-team/month — departmental chargeback
Graceful Degradation Ladder
- Step 1: Summarise oldest history turns
- Step 2: Remove optional tool schemas
- Step 3: Reduce RAG top-k from 10 → 3
- Step 4: Strip examples from system prompt
- Step 5: Route to smaller model
- Step 6: Return cached/fallback response
Full Context Window Anatomy
Before the user types a single word, 80–95% of the context window may already be consumed. Understanding each layer is the first step to controlling costs.
The 95% Problem: In production agentic systems with RAG, multi-turn history, and tool schemas, the actual user message is often <5% of total tokens sent. Optimise the 95%, not the 5%.
System Prompt
25%
Conv. History
20%
RAG Context
35%
Tool Schemas
8%
User Message
6%
Output
7%
Layer 1: System Prompt
Static instructions sent on every request. Optimise once, save forever. Target: <500 tokens. Enable KV caching to reduce cost by 90%.
Layer 2: History
Grows with every turn. Implement sliding window, periodic summarisation, or selective retention to cap at a token budget.
Layer 3: RAG Context
The largest variable layer. Re-ranking, smaller chunks, and budget caps are the primary levers. Target: ≤1,500 tokens of retrieved context.
System Prompt Tokens
System prompts are a silent cost multiplier. Every token in your system prompt is paid on every single request — at scale, even 200 extra words can cost thousands of dollars monthly.
Cost at Scale Example
A 2,000-token system prompt at 100,000 requests/day:
Uncached: 200M tokens × $3/1M = $600/day = $18,000/month
Cached (90% hit): 20M × $3 + 180M × $0.30 = $114/day = $3,420/month
Savings from caching alone: $14,580/month
Uncached: 200M tokens × $3/1M = $600/day = $18,000/month
Cached (90% hit): 20M × $3 + 180M × $0.30 = $114/day = $3,420/month
Savings from caching alone: $14,580/month
Compression Checklist
- Remove "you are a helpful assistant" boilerplate
- Replace prose rules with bullet directives
- Eliminate redundant instructions
- Use abbreviations for repeated terms
- Move examples to a cacheable prefix block
- Audit quarterly — rules accumulate over time
Cache Everything Static: Place all static content (persona, rules, examples, documents) at the beginning of the context as a cacheable block. Only dynamic, per-request content should be outside the cache boundary.
Conversation History Management
By default, every new message carries the entire conversation. A 20-turn chat can accumulate 40,000+ tokens — paid again on message 21. This is the #1 hidden cost driver in chat apps.
Strategy 1: Sliding Window
Keep only the last N turns. Simple, predictable, but loses long-term context. Best for task-focused chatbots where recency matters most.
Strategy 2: Summarisation
Periodically compress older turns into a summary paragraph. Preserves key context at ~10% of original token cost. Best for long support conversations.
Strategy 3: Selective Retention
Keep only turns flagged as high-value (user corrections, key decisions, tool results). Score turns by relevance and prune dynamically.
# Summarise history when it exceeds a token budget
def manage_history(messages, budget=4000):
if count_tokens(messages) < budget:
return messages
# Summarise all but last 4 turns
old = messages[:-4]
recent = messages[-4:]
summary = summarise(old) # ~200 tokens
return [{"role":"user","content":f"[Summary of prior context: {summary}]"}] + recent
Tool Schema Tokens
Every tool definition you include in a request costs tokens — even when that tool is never invoked. A 20-tool agent can waste 3,000+ tokens per request on schema definitions alone.
The Schema Overhead Problem
Typical tool schema sizes:
- Simple tool (name + desc): ~80 tokens
- Medium tool (+ params): ~200 tokens
- Complex tool (+ enum + examples): ~400 tokens
- 20 complex tools: ~8,000 tokens/request
Lazy Schema Loading
- Include only tools relevant to the current task
- Use a router to select the right tool subset
- Start with name-only schemas; expand on first use
- Cache schema tokens with KV cache
- Compress descriptions without losing semantics
Prompt Compression
Systematically reduce prompt length without reducing task quality. Well-compressed prompts often perform better — brevity forces clarity.
LLMLingua-2 Compression
Microsoft's token-budget-aware prompt compressor. Removes semantically redundant tokens while preserving task-critical information. Achieves 4–8× compression with <5% performance drop on most tasks.
Manual Compression Techniques
- Replace narrative instructions with imperative directives
- Use structured formats (YAML > verbose JSON > prose)
- Remove pleasantries and meta-commentary
- Deduplicate repeated concepts
- Use domain abbreviations consistently
Before (87 tokens)
"You are a helpful customer service assistant who is always polite and professional. When a customer asks a question, please make sure to answer it thoroughly and provide any relevant information that might help them. Always be friendly and supportive."
After (22 tokens)
"Role: customer support agent. Tone: professional, concise. Answer user questions accurately. Ask for clarification if ambiguous."
Result
75% token reduction. Same (often better) output quality because the model receives cleaner, less ambiguous instructions.
Output Token Control
Output tokens cost 3–5× more than input tokens and are the largest single cost lever most teams haven't pulled. Every token the model generates is money leaving your account.
Always Set max_tokens
Never send a request without max_tokens. The default allows models to generate thousands of tokens for simple tasks. Even setting max_tokens=200 for classification tasks can cut output costs by 90%.
Format-Constrained Output
- Use JSON mode — eliminates preamble tokens
- Specify exact output schema in the prompt
- Request bullet points, not paragraphs
- Specify maximum length explicitly ("max 3 sentences")
- Use "Answer only with: yes/no/unsure" for classification
The Verbosity Default: LLMs are trained to be thorough and helpful, which means they default to longer, more detailed responses. Override this explicitly in every prompt. "Be concise" is not enough — specify the exact format and maximum length.
Few-Shot Efficiency
More examples don't linearly improve performance. Find the minimum effective shot count for each task type — most tasks need 1–3 examples when framed correctly.
Example Budget Guidelines
- Classification tasks: 1–2 examples per class
- Format transformation: 1 input/output pair
- Code generation: 0–1 examples (use type hints instead)
- Complex reasoning: 2–3 chain-of-thought examples
- Highly specialised domain: 3–5 examples maximum
Cached Example Patterns
Place all few-shot examples in the system prompt (cacheable) rather than repeating them per-request. Cache once, save millions of tokens. Use cache breakpoints to separate static examples from dynamic context.
Structured Output
Constrained generation produces exactly what you need — nothing more. It eliminates preamble, explanation padding, and post-processing extraction calls.
JSON Mode Benefits
- Eliminates "Sure, here is the JSON you requested:" preamble
- Removes markdown code fences (```json)
- No need for a second extraction call
- Predictable token count for budgeting
- Directly parseable — zero processing overhead
Token Savings by Format
- Asking for JSON: 30–50% fewer output tokens
- Structured schema: 20–40% fewer tokens
- Bullet list vs prose: 40–60% fewer tokens
- Yes/No classification: 95% fewer tokens
Prompt Caching (KV Cache)
The single highest-ROI optimisation available. Cache static context at the model layer and pay 90% less on every cache hit. Implement on day one.
How KV Cache Works
The model computes key-value attention matrices for your prompt. With caching enabled, these are stored server-side. Subsequent requests with identical prefix pay only for the cache read (~10% of input cost) instead of full recomputation.
Cache Killers — Avoid These
- Timestamps or request IDs in system prompt
- User name/personalisation before static content
- Dynamic content injected before examples
- Random ordering of tool schemas
- Any variation in the static prefix
Architecture Rule: Always place content in order of stability: system instructions → documents → examples → (cache boundary) → conversation history → user message. Cache everything above the boundary.
# Anthropic cache_control implementation
client.messages.create(
model="claude-sonnet-4-20250514",
system=[
{"type": "text", "text": system_prompt,
"cache_control": {"type": "ephemeral"}} # Cache this block
],
messages=[
{"role": "user", "content": [
{"type": "text", "text": document_text,
"cache_control": {"type": "ephemeral"}}, # Cache docs too
{"type": "text", "text": user_message}
]}
]
)
Semantic Response Caching
Cache full AI responses for semantically similar queries. A vector similarity lookup serves 30–60% of requests with zero LLM cost — the most powerful throughput multiplier available.
How It Works
1. Embed the user query → vector
2. Search Redis/Pinecone for similar cached queries
3. If cosine similarity > threshold (0.92+): return cached response
4. If miss: call LLM, store response + embedding in cache
5. TTL-based expiry for time-sensitive content
2. Search Redis/Pinecone for similar cached queries
3. If cosine similarity > threshold (0.92+): return cached response
4. If miss: call LLM, store response + embedding in cache
5. TTL-based expiry for time-sensitive content
When It Excels
- FAQ and support bots (high query repetition)
- Document Q&A on stable content
- Product description generation
- Code explanation for common patterns
- High-traffic consumer applications
SIMILARITY_THRESHOLD = 0.92
async def cached_completion(query: str) -> str:
query_vec = await embed(query)
hit = await redis.vector_search(query_vec, threshold=SIMILARITY_THRESHOLD)
if hit:
metrics.increment("cache_hits")
return hit.response
response = await llm_call(query)
await redis.store(query_vec, response, ttl=3600)
return response
Tool Result Memoization
Agent loops often call the same tools with identical parameters multiple times. Memoising results eliminates redundant API calls and dramatically reduces context pollution from repeated tool outputs.
Within-Session Cache
Hash (tool_name + params) → cache result for the duration of an agent run. A weather lookup, database query, or API call performed in iteration 2 need not re-execute in iteration 5.
Cross-Session Cache
For stable data (product catalogues, configuration, user profiles), persist tool results in Redis with appropriate TTL. Saves both token costs and downstream API costs simultaneously.
Embedding Caching
Embedding costs are often overlooked — but re-embedding unchanged documents at query time is pure waste. Persist vectors; only recompute on actual content changes.
Storage Strategy
- Store document hash → embedding vector
- On update: diff hashes, re-embed only changed chunks
- Use pgvector, Pinecone, or Weaviate for persistent storage
- Cold-start: bulk embed entire corpus once
- Warm path: hash check before any embed call
Cost Savings
A 10,000-document corpus embedded daily costs ~$1/day with text-embedding-3-small. With caching and differential updates (5% daily change rate), cost drops to ~$0.05/day — 95% reduction.
Chunk Sizing Strategy
Chunk size directly controls RAG context quality and cost. Too large: bloated context with low signal. Too small: fragmented context loses coherence. The optimal size is task-dependent.
Too Large (>1000 tokens)
High token cost, low retrieval precision, relevant info buried in noise. Retrieval similarity becomes diluted across multiple topics per chunk.
Sweet Spot (200–400 tokens)
Balanced precision and coherence. Works for most document types. Combine with sentence-aware splitting to avoid mid-sentence breaks.
Too Small (<50 tokens)
High retrieval noise, fragments miss context, requires larger top-k to find relevant content. Often worse retrieval quality than larger chunks.
Hybrid Chunking
- Split on semantic boundaries (paragraphs, sections)
- Add 10–20% overlap to prevent context cliffs
- Store parent chunk → retrieve child chunks
- Proposition chunking: one factual claim per chunk
- Code: split by function/class, not arbitrary length
Metadata Injection
Prepend source, section title, and page number to each chunk (<30 tokens). This improves retrieval precision and allows context attribution without embedding these in the chunk content itself.
Re-ranking & Precision Retrieval
Retrieve broadly with vector search, then filter aggressively with a re-ranker. Send top-3 high-precision chunks instead of top-20 noisy ones. Same quality, 80% fewer context tokens.
Two-Stage Pipeline
Stage 1 — Vector Recall: Retrieve top-50 candidates by embedding similarity (fast, approximate).
Stage 2 — Cross-Encoder Re-rank: Score each candidate against the query with a cross-encoder model (slower, precise). Keep top-3 to top-5.
Result: 10× better precision at 20% of the context cost.
Stage 2 — Cross-Encoder Re-rank: Score each candidate against the query with a cross-encoder model (slower, precise). Keep top-3 to top-5.
Result: 10× better precision at 20% of the context cost.
Re-ranker Options
- Cohere Rerank — hosted, easiest integration
- BGE-Reranker — open source, self-hostable
- cross-encoder/ms-marco — HuggingFace, free
- FlashRank — ultra-fast, minimal dependencies
- LLM-as-reranker — highest quality, higher cost
RAG Context Budget Control
Set a hard token budget for all retrieved context and enforce it before sending. RAG context is the most controllable cost layer — it should never exceed its allocation.
Budget Allocation
For an 8K token request budget:
System prompt: 500 tokens
History: 1,500 tokens
RAG budget: 1,500 tokens
Tool schemas: 500 tokens
User message: 500 tokens
Output reserved: 3,500 tokens
RAG content beyond 1,500 tokens is truncated by relevance score.
System prompt: 500 tokens
History: 1,500 tokens
RAG budget: 1,500 tokens
Tool schemas: 500 tokens
User message: 500 tokens
Output reserved: 3,500 tokens
RAG content beyond 1,500 tokens is truncated by relevance score.
Enforcement Strategies
- Count retrieved chunks before injection
- Sort by relevance score, take until budget exhausted
- Truncate individual chunks at token boundary
- Prefer fewer complete chunks over many truncated ones
- Log budget utilisation per request
Summary Indexing & RAPTOR
Build a hierarchy of summaries from your corpus. Retrieve a compact 300-token summary instead of 3,000 tokens of raw chunks for high-level queries.
RAPTOR Architecture
Level 0: Original chunks (200–400 tokens)
Level 1: Cluster summaries (100–200 tokens, ~10 chunks per cluster)
Level 2: Section summaries (50–100 tokens)
Level 3: Document summaries (30–50 tokens)
Query routing decides which level to retrieve from based on query specificity.
Level 1: Cluster summaries (100–200 tokens, ~10 chunks per cluster)
Level 2: Section summaries (50–100 tokens)
Level 3: Document summaries (30–50 tokens)
Query routing decides which level to retrieve from based on query specificity.
Query Routing Logic
- General question → top-level summary (50 tokens)
- Section-specific → level 1 summary (150 tokens)
- Detail-specific → leaf chunks (300 tokens)
- Mixed → hybrid retrieval across levels
Agent Loop Token Explosion
The most dangerous cost pattern in agentic AI. Each iteration re-sends the entire accumulated context. 10 iterations isn't 10× the cost — it's 10–50× due to compounding history.
Critical Warning: An unconstrained agent loop on Claude Opus 4 can accumulate $5–$20 in token costs per task. Multiply by 1,000 daily tasks and you have a $5,000–$20,000/day bill from a single feature.
| Iteration | New Tokens | Cumulative Context | Relative Cost |
|---|---|---|---|
| 1 | 1,500 | 1,500 | 1× |
| 2 | 800 | 2,300 | 1.5× |
| 3 | 800 | 3,100 | 2.1× |
| 5 | 800 | 4,700 | 3.1× |
| 10 | 800 | 8,700 | 5.8× |
Control Mechanisms
- Hard iteration limit (never exceed 10 iterations)
- Token budget per loop (abort if exceeded)
- Compact tool results before adding to history
- Summarise completed sub-tasks mid-loop
- Use scratchpad pattern: thinking separate from history
Anti-Patterns
- Appending full tool results without extraction
- Re-injecting system instructions each iteration
- No iteration or token limit
- Logging verbose chain-of-thought in context
- Re-retrieving RAG context every iteration
class BudgetedAgent:
def __init__(self, max_iter=8, token_budget=40000):
self.max_iter = max_iter; self.token_budget = token_budget
self.total_tokens = 0; self.iter = 0
def step(self, messages):
if self.iter >= self.max_iter:
raise AgentLimitError("Max iterations reached")
estimated = count_tokens(messages)
if self.total_tokens + estimated > self.token_budget:
messages = self.compress_history(messages)
result = llm_call(messages)
self.total_tokens += result.usage.total_tokens
self.iter += 1
return result
Multi-Agent Overhead
Every agent-to-agent message serialises full context. An orchestrator managing 5 sub-agents can easily generate 5× the token cost of a single-agent approach if not architected carefully.
Where Cost Explodes
- Orchestrator passes full context to each sub-agent
- Sub-agents return full conversation history
- Context duplicated across all parallel branches
- Each agent re-loads tool schemas independently
- No shared memory — same research done repeatedly
Efficient Architecture
- Pass only task-relevant context to sub-agents
- Sub-agents return structured summaries, not full history
- Use a shared read-only memory store
- Centralised tool schema registry (cached)
- Orchestrator compresses sub-agent outputs before aggregation
Planning & Reasoning Costs
Extended thinking, chain-of-thought, and planning steps generate thousands of tokens before the actual response begins. Budget reasoning tokens as a first-class cost category.
Reasoning Token Reality
Claude's extended thinking can generate 5,000–20,000 thinking tokens per request. At Opus 4 output pricing ($75/1M), 20,000 thinking tokens = $1.50 per request — before the actual response.
Budget_tokens Parameter
Anthropic's thinking API accepts a budget_tokens parameter to cap reasoning length. Set this based on task complexity: simple tasks need 1,000 tokens of thinking; complex reasoning rarely benefits beyond 10,000.
When to Use Extended Thinking
- Multi-step mathematical reasoning
- Complex code architecture decisions
- Long-horizon planning tasks
- Tasks requiring self-verification
When NOT to Use It
- Simple extraction or classification
- Formatting or transformation tasks
- Factual retrieval from provided context
- Any task a standard call handles correctly
Tool Call Result Management
Raw API results injected directly into context are the most common source of token waste in agentic systems. A 50KB API response contains ~12,000 tokens — extract the 200 tokens you actually need.
Extraction Pattern
Define a result schema for each tool call. After receiving the result, run a lightweight extraction step that pulls only the fields needed for the current task before appending to agent history. Never append raw API responses.
Compact Serialisation
- Remove null/empty fields from JSON results
- Use short field names in tool result schemas
- Truncate long string fields at character limit
- Aggregate arrays: "47 items, first 3: [...]"
- Return status codes, not full error messages
Intelligent Model Routing
Not every task needs a frontier model. Route 80% of requests to fast, cheap models — reserve Opus-tier only for tasks that genuinely require it. Potential 80% cost reduction on model spend.
Routing Tiers
Tier 1 (Micro): Classification, extraction, simple Q&A → Haiku 3.5 or GPT-4o mini
Tier 2 (Standard): Generation, summarisation, code completion → Sonnet 4 or GPT-4o
Tier 3 (Advanced): Complex reasoning, novel problems, high-stakes → Opus 4 or o1
Tier 2 (Standard): Generation, summarisation, code completion → Sonnet 4 or GPT-4o
Tier 3 (Advanced): Complex reasoning, novel problems, high-stakes → Opus 4 or o1
Routing Signals
- Task type (classify, generate, reason)
- Estimated output length
- Domain complexity score
- User tier / SLA requirement
- Confidence from a cheap classifier model
| Task Type | Recommended Model | Relative Cost | Quality Impact |
|---|---|---|---|
| Binary classification | Haiku 3.5 | 1× | None |
| Entity extraction | Haiku 3.5 | 1× | Minimal |
| Summarisation | Sonnet 4 | 4× | Noticeable on long docs |
| Code generation | Sonnet 4 | 4× | Significant quality gap |
| Complex reasoning | Opus 4 | 19× | Major quality difference |
Speculative Decoding
A small draft model generates token candidates in parallel; the large model verifies and corrects them. Same output quality at 2–4× higher throughput and lower effective latency.
How It Works
1. Small draft model (e.g., Haiku) proposes K tokens
2. Large model evaluates all K tokens in parallel
3. Accepted tokens are kept; first rejection restarts
4. Net effect: 2–4× speed improvement on simple continuations
5. Best for code completion, template filling, factual continuation
2. Large model evaluates all K tokens in parallel
3. Accepted tokens are kept; first rejection restarts
4. Net effect: 2–4× speed improvement on simple continuations
5. Best for code completion, template filling, factual continuation
Cost-Latency Trade-off
Speculative decoding doesn't reduce total tokens — it reduces wall-clock latency. The cost is similar to running both models. Value is in user experience and throughput capacity, not direct token savings.
Fine-Tuning for Prompt Reduction
Bake repetitive instructions, style, and domain knowledge into the model weights. Eliminate 80% of system prompt tokens for high-volume, predictable tasks. Best ROI at 50,000+ requests/month.
What Fine-Tuning Eliminates
- Role and persona descriptions
- Output format instructions
- Domain-specific terminology definitions
- Company-specific rules and constraints
- Few-shot examples baked into weights
Break-Even Analysis
Fine-tuning cost: ~$500–$2,000 one-time.
Savings: 1,500-token system prompt × 100K requests/month × $0.003 = $450/month.
Break-even: <4 months. ROI thereafter: infinite.
Savings: 1,500-token system prompt × 100K requests/month × $0.003 = $450/month.
Break-even: <4 months. ROI thereafter: infinite.
Batch Processing
Async batch APIs offer 50% cost reduction for non-real-time workloads. Most AI tasks don't require synchronous responses — classification, enrichment, and generation jobs can be batched.
Tasks Suited for Batching
- Content classification at scale
- Document summarisation pipelines
- Data enrichment and extraction
- Embedding generation for new content
- Evaluation and testing runs
- Overnight report generation
API Options
Anthropic Batch API: 50% discount, 24h processing
OpenAI Batch API: 50% discount, 24h processing
Queue non-urgent work into nightly batch runs. Split real-time from async paths at the application layer.
OpenAI Batch API: 50% discount, 24h processing
Queue non-urgent work into nightly batch runs. Split real-time from async paths at the application layer.
Token Observability & Tracing
You cannot optimise what you don't measure. Structured token telemetry per request, per feature, and per user is the non-negotiable foundation of all AI FinOps.
Minimum Viable Telemetry
- request_id, timestamp, user_id, feature_id
- model, prompt_tokens, completion_tokens
- cache_hit (bool), cache_tokens_saved
- latency_ms, cost_usd
- agent_iteration (for agentic calls)
- rag_chunks_retrieved, rag_tokens_used
Key Dashboards
- Cost/day by feature and model
- Token size distribution (p50, p95, p99)
- Cache hit rate trend
- Top 10 most expensive request patterns
- Per-user token consumption leaderboard
- Cost per successful task completion
# Instrumentation decorator — wrap every LLM call
def track_tokens(feature: str):
def decorator(fn):
async def wrapper(*args, **kwargs):
result = await fn(*args, **kwargs)
await metrics.record({
"feature": feature,
"input_tokens": result.usage.input_tokens,
"output_tokens": result.usage.output_tokens,
"cache_read": result.usage.cache_read_input_tokens,
"cost_usd": calculate_cost(result.usage)
})
return result
return wrapper
return decorator
Rate Limiting & Quotas
Token quotas are the first line of defence against runaway costs and abuse. Define limits at every level and enforce them before the API call — not after the bill arrives.
Quota Hierarchy
Per-request: Max input + output tokens hard limit
Per-user/hour: Prevent individual abuse
Per-user/day: Fair use enforcement
Per-feature/day: Budget allocation per product area
Per-team/month: Departmental budget cap
Platform total: Global circuit breaker
Per-user/hour: Prevent individual abuse
Per-user/day: Fair use enforcement
Per-feature/day: Budget allocation per product area
Per-team/month: Departmental budget cap
Platform total: Global circuit breaker
Graceful Quota Responses
- Warn at 80% of daily quota
- Throttle to reduced limits at 90%
- Return cached/static responses at 100%
- Show quota status in user-facing UI
- Allow quota increases via self-service portal
Cost Attribution & Chargeback
Attribute every token to a cost centre. Showback drives awareness; chargeback drives accountability. Both are necessary to make AI costs manageable at organisational scale.
Tagging Strategy
Tag every API request with:
Route tags to your observability platform (Datadog, Grafana, AWS Cost Explorer). Generate monthly cost-by-dimension reports automatically.
team, product, feature, environment, user_tier, experiment_idRoute tags to your observability platform (Datadog, Grafana, AWS Cost Explorer). Generate monthly cost-by-dimension reports automatically.
Chargeback Models
- Showback: Report costs to teams, no billing
- Soft chargeback: Internal credits, no real money
- Hard chargeback: Real budget impact on team P&L
- Start with showback — accountability emerges naturally
Token Anomaly Detection
Cost spikes happen fast. An agent loop bug, a prompt injection, or a traffic surge can generate thousands of dollars in unexpected charges in minutes. Automated anomaly detection is non-optional at scale.
Anomaly Signals to Monitor
- Request token count > 3× rolling average
- Single user consuming >10% of daily budget
- Agent iteration count exceeds threshold
- Cost/hour spike >2× standard deviation
- Cache hit rate drops >20% unexpectedly
Response Actions
- Alert: Slack/PagerDuty notification
- Throttle: Reduce quota for offending entity
- Block: Stop requests from suspected abuse
- Investigate: Flag request for human review
- Rollback: Revert recent prompt/model changes
Token Cost Calculators
Model your actual token costs, visualise optimisation savings, and understand the compounding impact of agentic loops. All calculations run locally — no data sent anywhere.
1. Per-Request Cost Breakdown
Model the full token cost of a single AI request — every layer included. Select a model and adjust inputs to see your true per-call cost.
1,000avg 500–2,000
2,000grows with turns
2,000retrieved chunks
500~200 per tool
200actual user query
500model response length
60%% of system+static tokens cached
11 = single request
Total Input Tokens
All layers combined
5,700
Effective Input Cost
After cache discount
$0.0117
Output Cost
Most expensive layer
$0.0075
Total Cost / Request
All tokens, all layers
$0.019
Monthly Cost (10K req/day)
At current settings
$5,790
Cache Savings / Request
vs no caching
$0.006
2. Optimisation Savings Calculator
Start from your baseline monthly AI spend and activate optimisation levers to see potential savings. Adjust sliders to match your deployment scenario.
$10,000current monthly AI bill
30%depends on % static context
20%system + few-shot reduction
25%% requests served from cache
35%% of requests routed to smaller models
15%context reduction from precision retrieval
20%from max_tokens + format constraints
Baseline Monthly Spend
$10,000
Prompt Caching Saves
$3,000
Prompt Compression Saves
$1,400
Semantic Cache Saves
$1,575
Model Routing Saves
$1,531
RAG + Output Saves
$701
Optimised Monthly Spend
$1,793
Total Annual Savings
$98,484
3. Agent Loop Cost Visualiser
See how token costs compound across agent iterations. Adjust base context and per-iteration additions to understand the true cost of agentic systems.
5,000initial system + RAG + history
800tool results + model output per step
10agent loop limit
1,000daily agent task volume
Cost at Iteration 1
$0.023
Cost at Iteration 5
$0.071
Cost at Max Iteration
$0.134
Avg Cost If Aborted at 5 Iter
$0.042
Daily Cost (1K tasks, full loop)
$134
Monthly Cost (full loop)
$4,020
Savings from 5-Iter Limit
$1,380/month
Token Optimisation Checklists
Actionable checklists for every role and timeline. Check off items as you implement them — progress is tracked automatically.
⚡ Quick Wins — Do These in the Next 48 Hours
0 / 10 complete
Audit your system prompt. Count the tokens. Remove every sentence that doesn't change model behaviour. Target: under 500 tokens.
P1
Enable prompt caching. Add cache_control to your system prompt and any static documents. Immediate 60–90% cost reduction on those tokens.
P1
Set max_tokens on every API call. Never rely on model defaults. Set a realistic limit for each use case — classification tasks should be 50–200 tokens, not 4,096.
P1
Add token logging to every LLM call. Log input_tokens, output_tokens, cache_hit, and cost_usd with a feature tag. You cannot optimise what you don't measure.
P1
Remove boilerplate from prompts. Delete "You are a helpful assistant", "Please", "Thank you", and similar non-functional filler. Usually saves 50–150 tokens per request.
P1
Use JSON mode for structured outputs. Eliminates preamble tokens and markdown fences. Reduces output tokens 30–50% for data extraction tasks.
P2
Implement conversation history truncation. Cap history at a token budget (e.g., 2,000 tokens). Sliding window or summarisation — either is better than unlimited growth.
P2
Reduce RAG top-k from the default. Most defaults are top-10 or top-20. Reduce to top-5 with a relevance threshold filter. Cuts RAG context tokens 50–75%.
P2
Identify your top 3 most expensive request patterns. Sort by total_tokens descending in your logs. The top 3 often account for 50%+ of spend.
P2
Add pre-flight token counting. Count tokens before sending — abort or truncate if over budget. Prevents unexpected context overflow costs.
P3
🔧 Engineering Implementation — 1–2 Weeks
0 / 10 complete
Deploy semantic response caching. Redis + embedding similarity lookup. Start with a 0.92 cosine threshold. Target: 30%+ cache hit rate within 2 weeks.
P1
Add a re-ranker to your RAG pipeline. Retrieve top-50, re-rank, send top-5. Cohere Rerank or BGE-Reranker are easy starting points. Reduces RAG context 60–80%.
P1
Implement model routing. Build a simple classifier that routes requests to Haiku (simple), Sonnet (medium), or Opus (complex). Start with rule-based routing before ML-based.
P1
Add per-user token quotas. Implement daily token budgets per user tier. Warn at 80%, throttle at 90%, block at 100% with a graceful message.
P2
Implement tool result memoization. Cache tool call results within agent sessions by (tool_name + params) hash. Especially impactful for search, lookup, and API calls.
P2
Add agent loop limits. Hard cap at 8–10 iterations per task. Implement a token budget that triggers mid-loop compression if exceeded.
P2
Implement lazy tool schema loading. Don't include all tools in every request. Use a lightweight router to select the 3–5 most relevant tools per task type.
P2
Set up cost anomaly alerts. Alert when any request exceeds 3× the rolling average token count, or when hourly cost spikes above 2 standard deviations.
P2
Move eligible workloads to batch API. Identify classification, summarisation, and enrichment pipelines that don't require real-time responses. 50% cost reduction immediately.
P3
Implement conversation summarisation. For long sessions, periodically summarise old turns into a compact paragraph. Compress 2,000 tokens of history to 200 tokens without losing key context.
P3
🏛️ Platform & Governance — Ongoing
0 / 8 complete
Build an AI cost dashboard. Real-time cost by feature, model, team. Include cost/task efficiency metric, not just raw spend. Leadership needs to see ROI, not just bills.
P1
Define token budgets per product feature. Every feature that calls an LLM should have an agreed token budget. Review and reapprove if it needs to grow.
P1
Establish a prompt review process. Any new system prompt or prompt template should be reviewed for token efficiency before production deployment.
P2
Schedule monthly token optimisation reviews. Review top cost drivers, identify new quick wins, and track progress on ongoing optimisations.
P2
Tag all requests with cost centre metadata. team, product, feature, environment, user_tier. Required for chargeback and accurate attribution.
P2
Document token architecture decisions. Record why each layer exists, its token budget, and the last review date. Prevents silent token budget creep over time.
P3
Set up provider pricing change alerts. Model pricing changes can significantly impact your optimisation strategy. Monitor provider pricing pages for updates.
P3
Evaluate fine-tuning ROI quarterly. For high-volume, stable tasks (10,000+ requests/day), fine-tuning often pays back within 1–3 months. Run the break-even calculation.
P3
Token Metrics & KPIs
The metrics that matter for token optimisation. Define baselines, set targets, and track progress weekly. What gets measured gets improved.
Cost Efficiency Metrics
| Metric | Formula | Good Target | Warning Level | Why It Matters |
|---|---|---|---|---|
| Cost per Request | total_cost / request_count | <$0.01 | >$0.05 | Primary cost efficiency indicator |
| Token Efficiency Ratio | output_tokens / input_tokens | 0.1–0.3 | >0.5 | High ratio = bloated input |
| Cache Hit Rate | cache_hits / total_requests | >60% | <30% | Most impactful single metric |
| Output / Input Ratio | output_tokens / total_tokens | 10–20% | >40% | High output % = unconstrained responses |
| Cost per 1K Requests | monthly_cost / (monthly_requests/1000) | <$10 | >$50 | Normalised cost benchmark |
| Cost per Successful Task | total_cost / successful_completions | Trending down | Rising month-over-month | True ROI denominator |
Token Distribution Metrics
| Metric | Target | Action if Exceeded |
|---|---|---|
| p95 Request Size | <8,000 tokens | Investigate outlier patterns; add size limits |
| System Prompt % of Total | <15% | Audit and compress system prompt |
| RAG Context % of Total | <30% | Reduce top-k; add re-ranker; tighten budget |
| History % of Total | <25% | Implement sliding window or summarisation |
| Tool Schema % of Total | <10% | Implement lazy schema loading |
| Output % of Total | <20% | Set max_tokens; add format constraints |
Agentic System Metrics
| Metric | Good Target | Why It Matters |
|---|---|---|
| Avg Iterations per Task | <5 | High iteration count = compounding cost |
| Cost per Task Completion | Task-specific baseline | True efficiency of agentic workflows |
| Loop Abort Rate | <5% | High abort = poorly scoped tasks or bugs |
| Tool Call Dedup Rate | >20% | Memoization effectiveness |
| Context Utilisation at Completion | <70% | Leaving headroom prevents emergency truncation |
Optimisation ROI Tracking
| Initiative | Typical Reduction | Implementation Effort | Time to Value | Complexity |
|---|---|---|---|---|
| Prompt Caching | 30–90% on cached tokens | Low (1–2 days) | Immediate | ⭐ |
| max_tokens enforcement | 20–60% output tokens | Low (<1 day) | Immediate | ⭐ |
| System prompt audit | 10–40% system tokens | Low (1 day) | Immediate | ⭐ |
| Semantic response cache | 30–60% total requests | Medium (1 week) | 1–2 weeks | ⭐⭐⭐ |
| RAG re-ranking | 60–80% RAG tokens | Medium (3–5 days) | 1 week | ⭐⭐⭐ |
| Model routing | 40–80% model cost | Medium (1 week) | 1–2 weeks | ⭐⭐⭐ |
| Agent loop limits | 30–70% agentic cost | Low (1–2 days) | Immediate | ⭐⭐ |
| Fine-tuning | 60–90% system prompt | High (2–4 weeks) | 1–3 months | ⭐⭐⭐⭐⭐ |
Token Fundamentals
The bedrock of all token optimisation. Understand what tokens are, how they're priced, and how to measure them before implementing any strategy.
Filtered view: Click any card to see the full details, implementation guide, and code examples for that topic.
Context Window Anatomy
Every token in your context window has a source and a cost. Master the 6 layers that fill the window before the user sends a single word.
Filtered view: Click any card to see the full details, implementation guide, and code examples for that topic.
Prompt Optimisation
Systematic techniques to reduce prompt length without reducing quality. The most controllable cost lever available to every developer.
Filtered view: Click any card to see the full details, implementation guide, and code examples for that topic.
Caching & Reuse
The highest-ROI optimisation category. Cache at every layer — model KV cache, semantic response cache, tool results, embeddings.
Filtered view: Click any card to see the full details, implementation guide, and code examples for that topic.
RAG & Retrieval
Retrieved context is often the largest variable token cost. Precision retrieval, budget control, and hierarchical indexing can cut RAG tokens by 80%.
Filtered view: Click any card to see the full details, implementation guide, and code examples for that topic.
Agentic Systems
Agent loops compound costs exponentially. Every iteration, every sub-agent, every tool result adds to a context that must be fully re-sent.
Filtered view: Click any card to see the full details, implementation guide, and code examples for that topic.
Model Routing & FinOps
Right-size every request. Route to the cheapest model that meets quality requirements. Observe, attribute, and govern token spend at every level.
Filtered view: Click any card to see the full details, implementation guide, and code examples for that topic.
About This Guide
A practical reference built for every person who pays an AI bill — from individual developers to enterprise AI teams managing millions of dollars in annual token spend.
Why This Guide Exists
Organisations are spending 3–10× their projected AI budgets within 12 months of deploying LLMs. The problem isn't the models — it's that most teams have no mental model for how tokens accumulate. This guide provides that model.
Who This Is For
Developers building AI features, architects designing agentic systems, data scientists running RAG pipelines, product managers owning AI budgets, and executives asking "why is our AI bill this large?"
What's Covered
32 topics across 8 domains: token fundamentals, context anatomy, prompt engineering, caching strategies, RAG optimisation, agentic systems, model routing, and FinOps governance. Plus 3 interactive calculators and 28-item checklists.
Realistic Savings
Teams implementing the strategies in this guide typically achieve 50–80% cost reduction within 30 days. The quick wins alone (caching + max_tokens + prompt audit) can cut costs by 40% in under a week.
Keeping It Current
Model pricing, caching capabilities, and optimisation techniques evolve rapidly. This guide covers principles that remain valid across model generations while noting provider-specific implementations where relevant.
Version
Token Intelligence Field Guide v1.0 — June 2026. Covers Claude 3.5/4, GPT-4o, Gemini 1.5/2, and general principles applicable to any LLM provider.