Skip to content

Token Efficiency Framework

Updated

This page contains both the operating framework and its companion Part 4 vendor and evidence reference.

Four-part playbook for cutting input, cache, tool, and orchestration token spend across coding harnesses and hosted LLM APIs.

Spend tokens only where they change the outcome: choose the cheapest build primitive, cache stable prefixes, load skills and tools on demand, keep bulk data in code, match intelligence to step difficulty, and gate lossy changes with an eval.

How to use these files. This framework mirrors the Verifiable Output Framework (four parts, three tracks) so you do not load unrelated modes or vendor tables into an agent session.

PartWhat it isWhere it goes
Part 1. Agent rules (Token Efficiency Framework)
Short rules the agent follows
CLAUDE.md or a skill. Load Shared Core + 1 active track only
Part 2. Harness enforcement (Token Efficiency Framework)
Mechanical checks that must always run
Hooks, wrapper scripts, and CI. Never prompt text alone
Part 3. Operator playbook (Token Efficiency Framework)
Matrices, formulas, guardrails, checklists
You (design and audit time). Do not load into runtime agent context
Part 4. Evidence and vendor reference (Token Efficiency Reference)
Pricing tables, worked math, studies, sources
Load specific sections on demand using the Reference Index below
TrackUse when building or auditing
Track A: Coding-harness skills
Claude Code, Codex CLI, OpenCode, or Antigravity skills on quota plans
Track B: Multi-step and multi-worker workflows
Data pipelines, browser automation loops, research harnesses, subagent workflows
Track C: Hosted API systems
Token-billed backend apps, RAG services, and multi-tenant APIs (Anthropic, OpenAI, Google, xAI)

Part 1. Agent rules

Paste Shared Core plus one active track into CLAUDE.md or a skill. Cut any rule that does not match a failure mode in your system.

Shared Core (paste with every track)

Shared Core (paste with every track) (markdown)
# Token efficiency core

- Pick plain code before a model call, a workflow before an agent, and one
  agent before many. Never spend LLM tokens on deterministic parsing,
  filtering, counting, schema checks, or diffing.
- Keep prompt prefixes static-first and byte-stable (Block 1 tools,
  Block 2 system/developer prompt, Block 3 shared docs, Block 4
  session-start facts, Block 5 conversation). Never put timestamps,
  random IDs, or per-turn state in Blocks 1 to 4 (keep session-specific
  facts out of Blocks 1 to 3, fix Block 4 at session start, and keep
  Block 5 append-only between planned edit points).
- Keep tool definitions, model, Anthropic `tool_choice`, and top-level
  thinking/effort fixed inside a cached session (except Anthropic
  per-message effort or OpenAI GPT-6+ `configuration_update` items).
- Ask for the artifact only. Edit files by diff, not whole-file rewrite.
  Use native structured output where parsed; on non-reasoning models doing
  hard synthesis, reason in plain text first, then format in a small call.
- Never truncate tool or script output silently. Cap script stdout/stderr
  (<= 50 lines or <= 4 KB), state what was cut, save the full output and
  tracebacks to a file path, and return only the compact summary.
- Keep recent errors needed to avoid repeats, compact full stack traces to
  the failing line and message, and enforce hard stops in code.

Track A: Coding-harness skills

Track A: Coding-harness skills (markdown)
## Skill token rules
- Keep skill frontmatter concise (50 to 100 tokens) and specific so it does
  not trigger falsely. Keep total workspace skill metadata within budget
  (default <= 2,000 tokens or configured `workspace_skill_budget`) and
  scope rarely used skills per project, not globally.
- Keep `SKILL.md` <= 200 lines (target ~2,000 tokens, hard cap <= 2,500
  tokens). Move tables, schemas, and long examples into `references/` and
  read only the active file.
- Ship deterministic work in bundled `scripts/` (following the Shared Core
  stdout/stderr cap and disk-log rule).
- Disable unused MCP servers and prefer known CLIs (`git`, `gh`, `curl`,
  `python`).
- Drive bulk browser work through bundled Playwright scripts or targeted
  `browser_evaluate` JSON extractors rather than raw MCP DOM snapshots.
  Inspect screenshots in a disposable 1-turn vision call or subagent so
  image blocks never accumulate in or invalidate a cached worker session.

Track B: Multi-step and multi-worker workflows

Track B: Multi-step and multi-worker workflows (markdown)
## Workflow token rules
- Spawn a subagent when: (1) noisy multi-turn exploration exceeds the
  cold-start break-even (>= 5 turns or >= 20K raw tokens on a warm
  same-model parent), (2) the worker runs on a cheaper model tier, (3)
  the Verifiable Output Framework requires clean-context read-only review,
  or (4) stateless parallel workers share a warmed Blocks 1 to 3 prefix
  (place shared Blocks 1 to 3 before worker briefs and send 1 warming
  request first so workers pay cache reads instead of cold writes).
- On fan-outs of 5+ workers, write outputs to disk and return ~100-token
  status rows (path, counts, errors) so flagship orchestrators do not hit
  quadratic re-read blowups. Never poll background workers in an LLM loop.
- Persist progress incrementally in per-worker shard ledgers with atomic
  claim-before-work locks. Cap per-unit retries, dead-letter poison pills,
  and trip a circuit breaker after configured N (default 3) consecutive
  upstream failures.
- Rotate queue workers to a fresh session when marginal history reads
  approach a cold prefix write (typically 10 to 15 heavy items or before
  `0.85 * min(window, cliff)`, or `0.85 * window` when flat-priced:
  <= 85K Haiku 5.5, <= 170K Gemini Pro/Grok, <= 231K OpenAI GPT-5.6/6.x).
  Cap compactions at <= 2 per session; after 2, start fresh from disk
  artifacts and re-inject verbatim IDs mechanically. Ban opaque encrypted
  compaction when verbatim IDs or audit trails matter.
- For browser workflows, extract targeted DOM fields via bundled
  Playwright scripts or `browser_evaluate` JSON instead of raw MCP
  snapshots, and inspect screenshots in a disposable 1-turn vision call so
  images never accumulate in or invalidate a cached worker session.
- For evidence-backed pipelines: run zero-token deterministic ledger checks
  (normalized local snapshots, verbatim spans, claim links, derived math)
  before running LLM checks (or in a separate stage-isolated ledger stage
  before prose generation if staged separately); group LLM claim checks by
  shared source snapshot in Block 3; on verification fix passes (for
  example, Fix Pass 1 after `pass_num = 0` and Fix Pass 2 after
  `pass_num = 1` in the Verifiable Output Framework; never patch at
  read-only `pass_num = 2`), patch only flagged claims and prose sentences
  by ID (re-running code template fill for updated placeholders) instead
  of regenerating full prose.

Track C: Hosted API systems

Track C: Hosted API systems (markdown)
## API token rules
- Use Blocks 1 to 5 static-to-dynamic layout. On OpenAI GPT-6.2+ Responses
  API, place reusable system instructions in a `developer` message (top-
  level `instructions` append after `input` and bill uncached).
- Use split-TTL caching when idle gaps exceed the short TTL, >= 2 reads
  hold, and the provider supports explicit TTLs: long TTL on static
  Blocks 1 to 3, short TTL on session-scoped Blocks 4 to 5. After a
  detected TTL expiry, prune or compact right away.
- Set compaction/eviction caps below context and pricing cliffs (`0.85 *
  min(window, cliff)`, or `0.85 * window` when flat-priced: <= 85K Haiku
  5.5, <= 170K Gemini Pro/Grok, <= 231K OpenAI GPT-5.6/6.x) and reject
  oversized inputs pre-flight. Cap
  compactions at <= 2 per session (then start fresh from persisted state
  and re-inject verbatim IDs mechanically) and ban opaque encrypted
  compaction when verbatim IDs or audit trails matter.
- Scope exact-match and semantic cache keys by `tenant_id`, ACL/role,
  `model`, and `prompt_version`. Cancel backend streams on client disconnect.
- Capture full stream usage (`stream_options.include_usage=true` on OpenAI
  Chat Completions; merge `message_start` + `message_delta` on Anthropic)
  and reserve/debit tokens locally on aborted streams. Set HTTP read
  timeouts above p99 thinking/Flex TTFT and never auto-retry read timeouts
  without confirmed backend cancellation.
- On OpenAI reasoning models, use the Responses API. Route deferrable work
  to Batch, Gemini Flex, or OpenAI Responses API background mode.

Part 2. Harness enforcement

Rules in prompts are requests. Enforce these invariants in hooks, wrapper scripts, and CI so they hold on every run. Every check flags or blocks; none silently rewrites content.

CheckTrackWhat it verifiesOn failure
Skill size and frontmatter linter
A
Frontmatter <= 100 tokens, SKILL.md <= 200 lines and <= 2,500 tokens (target ~2,000), total workspace skill metadata <= 2,000 tokens (or configured workspace_skill_budget)
Block merge or warn
Script stdout/stderr cap
A, B
Bundled scripts and PostToolUse hooks cap inline output (<= 50 lines or <= 4 KB) and emit a disk path on truncation
Truncate with path notice
Subagent tool allowlist
A, B
Read-only reviewers and scoped workers receive only declared tools:
Block unauthorized tool
Run-level budget and depth guard
B, C
Shared run ledger enforces total tokens/dollars, max_depth = 1, max subagents, per-item cap, and (tool, target) error breaker
Stop run and log reason
Pre-flight input and cliff guard
B, C
Rejects oversized single requests (Track C) and triggers compaction/eviction or worker rotation before 0.85 * min(window, cliff) (0.85 * window when flat-priced; <= 2 compactions, then rotate session)
Block, compact (< 2), or rotate
Consecutive-request prefix diff
C
Automated test diffs Blocks 1 to 4, cache-affecting top-level params (model, Anthropic tool_choice, thinking, output_config.effort, reasoning.effort, GPT-6.2 top-level instructions), and append-only Block 5 prefix across 2 consecutive non-edit turns
Fail CI
Stream usage and abort debit
C
Confirms usage fields logged on normal streams and fallback debited on disconnects/timeouts
Alert and block quota bypass
CI quality, cost, and latency gate
B, C
Eval suite asserts quality floor, p95 cost per successful task, and p95 latency
Fail CI

Part 3. Operator playbook (do not load into runtime agent context)

Scope. Covers hosted token-billed APIs (Anthropic, OpenAI, Google, xAI Grok) and quota-limited coding harnesses (Claude Code, Codex CLI, OpenCode, Antigravity). Self-hosted GPU inference is excluded. Provider facts in the Token Efficiency Reference reflect live vendor documentation; re-check after model launches.

Core principles

  1. 1Optimize cost per successful task, not tokens per call. Retries and rework dominate unit cost.
  2. 2Find the dominant token class first. Agent loops are input-dominated; reasoning models hide spend in thinking tokens billed as output.
  3. 3Choose the simplest architecture before tuning prompts. Plain code beats a model call; a workflow beats an agent; one agent beats many.
  4. 4Cache before you cut. A stable, append-only prefix is the largest zero-quality-risk saving.
  5. 5Treat context as a budget. Beyond a threshold, extra tokens degrade reliability and trigger pricing cliffs.
  6. 6Load on demand. Skills, tools, references, and memory enter by reference only when needed.
  7. 7Keep bulk data out of the model. Filter, join, parse, and validate in code; return the summary and file path.
  8. 8Right-size intelligence per independent unit. Pick model and effort per call or subagent; escalate on verifiable evidence.
  9. 9Pay realtime prices only for realtime work (API / custom loop). Deferrable routes go to Batch, Gemini Flex, or OpenAI background mode.
  10. 10Spend output tokens on purpose. Diffs over rewrites, compact artifacts over prose, calibrated caps on every route.
  11. 11Gate lossy changes with deterministic checks first, then evals. Change one lever at a time against a recorded baseline.
  12. 12Measure continuously. Track spend or quota burn by feature and token class, alert on cache drops, and re-baseline after model upgrades.

Primitive selection matrix

Pick the cheapest primitive that solves the task before tuning prompts.

PrimitiveUse whenAvoid whenToken profile
Plain script / CLI
Deterministic rules: parsing, filtering, counting, schema checks, diffs, polling
Open-ended judgment or messy prose
0 LLM tokens
Skill (SKILL.md + scripts/)
Repeatable harness workflow pairing short guidance with bundled scripts
One-off task, or pure deterministic job
Small frontmatter tax per turn; body loads on trigger
Single call or code workflow
Fixed step sequence (extract, classify, transform, validate)
Dynamic branching needing open exploration
Minimal prefix, no growing chat history, batch-friendly
Single agent loop
Interactive coding or tightly coupled edits sharing state
Parallel independent work or massive noisy exploration
Warm cache across turns; quadratic growth with turns
Subagent (isolated window)
Heavy multi-turn exploration, cheaper-model delegation, or clean-context review
Short same-model lookup below break-even (for example, < 5 turns or < 20K raw tokens on a warm parent)
Pays cold-start write unless sharing a warmed prefix; returns compact summary or file path
Multi-agent fan-out
Broad, parallel, read-heavy research or strictly sharded independent units
Sequential reasoning or concurrent edits to the same files
High multiplier (~15x chat); stateless warmed-prefix workers pay 0.1x reads
MCP server
Unfamiliar remote API with auth/state needing structured schemas
Local tools with known CLIs (git, gh, curl, python)
Heavy schema overhead unless deferred via tool search

Subagent break-even rule. On the same model, spawning a stateful subagent pays a cold-start prefix write (P_s * r_write), brief output (B * r_out), summary output (S * r_out), and an extra synthesis turn. Turn-by-turn simulation shows a 5-turn, ~20K-token search on an 80K warm parent barely breaks even on the same model; heavy 10-turn exploration (~50K raw tokens) saves strongly. Three explicit overrides: spawn a subagent regardless of same-model cache math when (1) the Verifiable Output Framework requires a clean-context read-only reviewer, (2) the subagent runs on a much cheaper worker model (for example, Haiku 5.5 under an Opus 5.5 parent), or (3) stateless parallel workers share a warmed Blocks 1 to 3 prefix (paying 0.1x reads, not 1.25x writes).

Lever ranking

Use Build order on new designs (architecture first) and Audit order on running systems (cut waste and fix caching first). Savings are from individual studies and are not additive.

Build orderAudit orderLeverApplies toReported savingsEffortQuality riskKey caveatReference section
1
2
Simpler architecture / plain code
Both
Multi-agent ~15x chat; single agent ~4x; 65% of nodes pure code
High (rewrite) / Low (new)
Varies
Decide before building; cut dead/code-solvable steps first
Agent architecture
2
1
Prompt caching and stable layout
Both (preserve in harnesses)
90%+ off cached reads
Low
None
Writes cost 1.25x to 2.5x; min prefix 512 to 4,096; breaks even at 1 read (5m/30m) or 2 reads (1h/12h)
Prompt caching and layout
3
3
Exact-match response cache
API / custom loop
100% on hits
Low
None (repeatable calls)
Scope keys by tenant, ACL, model, prompt version; non-time-sensitive calls only
Batch, async, and response caching
4
4
Batch, flex, and async tiers
API / custom loop
50% off (Batch / Gemini Flex); 30% to 40% off (OpenAI background mode)
Low to medium
None, latency only
Unavailable in harnesses; OpenAI Flex beta winding down (none on GPT-6.2+); Gemini 2.5/3.1 Pro Batch and Flex bill cache hits at standard cache rate
Batch, async, and response caching
5
5
Load skills and tools on demand
Both (defer_loading is API/harness-native)
Anthropic reports 85% total context cut (~77K to ~8.7K post-discovery)
Low
Low, often improves selection
Skip below ~10 tools; mutating Block 1 breaks caching
Tools, skills, and MCP
6
6
Shape tool and script outputs in code
Both
~65% per response (206 to 72 tokens); orders of magnitude on logs
Medium
Low
Announce cuts; write full logs/DOM to disk; LLM-written filtering raised net cost on Opus 4.6
Tools, skills, and MCP
7
7
Clear stale tool results in batches
API / custom loop
40% to 84% of unmanaged tokens; ~16% to 18% in modeled 50-turn cached loop (12% to 19% by cadence)
Low to medium
Low
Clearing every turn breaks the cache (1.5x worse); keep IDs/paths in placeholders
Context engineering
8
8
Output control
Both (max_tokens/constrained JSON API only)
Varies; output is the priciest class
Low
Low to medium
Output caps include thinking tokens; avoid forcing strict JSON during complex non-reasoning synthesis
Output control
9
9
Code execution for tool loops
Both
37% to 98% tokens on multi-step data work
High (needs sandbox)
Low to medium
Raises output tokens ~2.2x; costs ~8% more on 1 to 2 simple lookups
Tools, skills, and MCP
10
10
Reasoning effort tuning
Both
No significant drop on 22/56 half-benchmark pairs; 50% to 84% cut (with loss) on 4 of 7 models at lowest effort
Low
Medium
Set per call/subagent, or per-message effort on supported Claude models
Model routing and reasoning effort
11
11
Retrieval precision
Both
~26x fewer tokens than long-context (small models, 1 domain), at lower accuracy
Medium
Medium
Sweep chunk size and top-k on eval; deduplicate chunks in multi-turn chat
Retrieval
12
12
Model routing, advisor, cascade
Both (harness = static subagent routing only)
12% (advisor, higher score); 35% to 85% (routers, ~95% quality)
Medium to high
High without eval
Route whole threads or subtasks, not single turns; escalate on verifiable checks
Model routing and reasoning effort
13
13
Compaction and summarization
Both
Extends long sessions
Medium
Medium to high
Lossy; cap at <= 2 compactions per session, then start fresh from disk
Context engineering
14
14
Semantic response cache
API / custom loop
20% to 45% realistic hit rate
Medium
High
High false-positive risk; FAQ traffic only, tenant-scoped
Batch, async, and response caching
15
15
Prompt compression
Both (script-side or API)
Up to 10x to 20x in studies
Medium
High
Last resort; every tested method raised hallucination
Retrieval / Quality guardrails and known traps

Stopping rules. For token-billed APIs, estimate monthly savings (route spend * expected cut) against engineering and eval time; stop when the next lever on your biggest route takes more than 1 quarter to pay back. For quota-limited coding harnesses, stop when turn-1 fixed overhead fits your ceiling and normal runs finish inside your rolling session and weekly quota without avoidable compactions.

Prompt layout (static first, dynamic last)

Prompt caching is a strict byte-for-byte prefix match. One changed byte invalidates every block below it.

BlockContentRuleCached across requests
Block 1
Tool definitions
Fixed for the session; any mutation rewrites Blocks 1 to 5
Yes (long TTL)
Block 2
System / developer prompt
No timestamps, IDs, or user names; deterministic JSON keys. On OpenAI GPT-6.2+ Responses API, use a developer message (top-level instructions append after input and bill uncached)
Yes (long TTL)
Block 3
Shared docs and examples
Stable project context, corpus, and few-shot examples
Yes (long TTL)
Block 4
Session facts
Session-start facts (date, initial mode, worker-specific brief, tenant ACL facts); fixed once session starts
Fixed in session (short TTL)
Block 5
Conversation
Append-only between planned edit points (include mid-session mode switches and reminders)
Grows in session (short TTL)

Lever interaction matrix

Resolve these seven conflicts at design time.

ConflictWhat breaksDesign rule
Caching vs clearing tool results
Clearing every turn rewrites the tail every turn (1.5x worse than caching alone); clearing near session end never repays the write
Clear in batches only when removed_tokens * remaining_turns * r_read > rewritten_tail * (r_write - r_read) (or right after a TTL expiry)
Caching vs deferred tool loading
Mutating Block 1 tool schemas mid-session invalidates Blocks 1 to 5
Use provider-native defer_loading + tool search (expands inline in Block 5) or inject discovered docs as Block 5 tool results
Caching vs effort / model switches
Switching models invalidates all caches; top-level thinking, output_config.effort, or OpenAI reasoning.effort changes can invalidate message (and tool/system) caches
Vary models or top-level effort across separate calls/subagents, or use Anthropic per-message effort (Claude 5/5.1/5.2/5.5 beta) or OpenAI GPT-6+ configuration_update items. Verify Gemini and pre-GPT-6 OpenAI effort switches via usage diffs
Caching vs parallel fan-out
Parallel calls launched together all miss; distinct briefs before shared docs break sharing; > 15 rpm on one pre-5.6 OpenAI key overflows routing
Put shared Blocks 1 to 3 before each worker's custom brief; warm with 1 call first (reliable on Anthropic, best effort on OpenAI/Gemini); pool pre-5.6 OpenAI prompt_cache_key into ceil(rpm / 12) buckets
Caching vs multi-turn retrieval
Appending chunks every turn hits pricing cliffs; evicting every turn breaks caching
Deduplicate retrieved chunk IDs against history; batch-evict stale chunks before pricing cliffs; start fresh on topic shifts
Caching vs slow tools / waits / fan-in
Browser waits, CAPTCHAs, or long (>5-min) subagent fan-ins expire a 5-min TTL (~+42% loop cost from 3 average-depth expiries in the 50-turn model, or > +50% if late in the loop)
Use split-TTL breakpoints (long TTL on Blocks 1 to 3, short TTL on Blocks 4 to 5); prune or compact immediately after any detected TTL expiry
Caching vs images / screenshots
Adding or removing an image invalidates Anthropic's cached conversation; screenshots bloat history quadratically
Inspect screenshots in a disposable 1-turn vision call or subagent so images never enter a cached worker thread

Pre-build token budget worksheet

Size budgets to p95, not the mean (agentic runs vary up to 30x on the same task).

  1. 1Session fixed overhead (P_fixed): System prompt + always-loaded tools + root rules + installed skill frontmatter.
  2. 2Task prefix (P): P_fixed + triggered skill body + static Block 3 shared corpus.
  3. 3Turn growth (G): Average tool result + visible assistant output added to history per turn.
  4. 4Loop cost (T >= 1 turns, exact closed form): r_read * (P*(T-1) + G*(T-1)*(T-2)/2) + r_write * (P + G*(T-1)) + r_out * (out + reasoning) * T, using actual model multipliers (for example, r_read = 0.1 or 0.05, r_write = 1.0 implicit / 1.25 short / 2.0 to 2.5 long TTL, r_out = 5 to 8). Add (r_write - r_read) * avg_context per expected TTL expiry.
  5. 5Subagents (N): N * (brief * parent_r_out + subagent_loop + summary * (parent_r_write + parent_r_read * remaining_parent_turns)) (plus any extra parent synthesis turn), where subagent_loop from Step 4 already includes subagent_prefix * r_write (use r_read instead of r_write for stateless workers sharing a warmed Blocks 1 to 3 prefix).
  6. 6Verification and jury calls: Add n_checks * check_cost (route to Batch/Flex and group by shared source doc in Block 3).
  7. 7Retry adjustment: Use average cost per attempt / measured pass rate (for checkpointed workflows, apply only to the retried stage rather than the full run).
  8. 8Pricing cliffs and modifiers (API only): Check Haiku 5.5 (>100K, 5x, includes cached tokens), Gemini Pro (>200K, 2x/1.5x), xAI Grok (>=200K, 2x all), OpenAI GPT-5.6/6.x (>272K, 2x/1.5x), Gemini 4 (<2,050-token turn re-processing), and non-token search fees in the Token Efficiency Reference.

Quality guardrails

ClassLeversGate
Free (same model, same tokens)
Prompt caching, Batch/Flex/background tiers, exact-match cache on repeatable non-time-sensitive calls, independent parallel tool calls
Verify usage fields; no quality eval needed
Usually positive (less noise)
Batched clearing of stale tool results (preserving IDs/paths in placeholders, tracking re-fetch rate), cache-safe deferred tool loading
Spot-check on eval set
Risky (different model or lossy input)
Model routing, lower effort, reranking to fewer chunks, trimming prompt instructions, compaction/summarization, prompt compression, semantic cache, output caps, lower image resolution
Full eval before and after; shadow-test on live traffic

Tiered eval gate (aligned with the Verifiable Output Framework):

  • •Coding-harness skills and local workflows: Run deterministic unit/contract tests (0 tokens) plus a bounded pilot of 5 to 10 real adversarial cases before any lossy change.
  • •High-volume API routes: Run deterministic checks first, then a 30 to 50 case golden set weighted toward past failures (add every new production failure to it). Run 3 repeats (1 flipped case moves a 30 to 50 item score by 2.0 to 3.3 points) and fail CI on quality, cost, or latency regressions.
  • •LLM judges: Never use an uncalibrated single smaller model from the same family. Per the Verifiable Output Framework, use a different model family (or a calibrated 3-model jury, measuring catch rate and clean-item FPR on the combined decision) calibrated to >= 80% catch rate, <= 10% clean-item FPR only for proof-gated or human-triaged workflows, and <= 10% warning-level false-discovery rate in production (on low-error-rate auto-acting gates, require deterministic proof or human review because even 1% to 2% clean-item FPR yields 29% to 45% FDR at a 3% base error rate), routed to Batch, Gemini Flex, or OpenAI background mode.

Never cut: Load-bearing instructions/examples proven by eval, recent errors needed to avoid repeats, exact identifiers (paths, IDs, error strings, numbers) during compaction, verification steps that prevent retries, or reasoning effort on hard steps.

Checklists

New skill, workflow, or system: design checklist

  • [ ][Core] Define unit of work, pass/fail check, and target cost (or quota budget) per successful task.
  • [ ][Core] Pick the cheapest primitive; move deterministic parsing, filtering, and validation into plain code or bundled scripts/.
  • [ ][Core] Lay out prompts Blocks 1 to 5 static-to-dynamic with zero dynamic values in the prefix (on GPT-6.2+ Responses API, put reusable prompts in a developer message).
  • [ ][Core] Shape tool, script, and error outputs: concise defaults, announced truncation, full logs/DOM written to disk, script stdout/stderr capped (<= 50 lines or <= 4 KB).
  • [ ][Skill] Budget skill frontmatter (50 to 100 tokens) and total workspace skill metadata (<= 2,000 tokens default or configured workspace_skill_budget); keep SKILL.md <= 200 lines (target ~2,000 tokens, hard cap <= 2,500); disable unused MCP servers; isolate screenshots in disposable 1-turn vision calls.
  • [ ][Workflow] Enforce subagent break-even (with clean-context reviewer, cheaper-model, and warmed-prefix overrides); return ~100-token disk-backed status rows on 5+ worker fan-outs; ban LLM polling loops; rotate queue workers; cap compactions at <= 2 and ban opaque compaction when verbatim IDs matter; use bundled Playwright/browser_evaluate extraction and disposable 1-turn screenshot isolation on browser loops; use atomic claim locks + shard ledgers + run-level budget (max_depth = 1, per-item cap, (tool, target) error breaker).
  • [ ][API] Keep top-level model/tools/thinking/effort and Anthropic tool_choice fixed inside a session (or use Anthropic per-message effort / OpenAI GPT-6+ configuration_update); use split-TTL breakpoints; enforce cliff-aware compaction caps (<= 0.85 * min(window, cliff), or <= 0.85 * window when flat-priced: <= 85K Haiku 5.5, <= 170K Gemini Pro/Grok, <= 231K OpenAI GPT-5.6/6.x), <= 2 compactions per session, opaque-compaction ban for verbatim IDs, and pre-flight input rejection; scope response cache keys by tenant_id/ACL/model/prompt_version; parse stream usage + debit aborts + cancel backend streams on disconnect; set timeouts above p99 thinking/Flex TTFT; route deferrable calls to Batch/Flex/background mode.
  • [ ][Core] Before any lossy optimization, build deterministic checks plus the matching eval tier (5 to 10 adversarial pilot cases for skills; 30 to 50 golden cases x 3 repeats for APIs).

Existing system: audit procedure

  1. 1Instrument. APIs: capture full usage fields by token class (matching provider cached/write-token schemas) with feature tags over 1 week. Harnesses: inspect /cost, /context, turn-1 fixed overhead, and session transcripts.
  2. 2Cut waste and attribute. Rank routes by spend; delete idle jobs, duplicate calls, and LLM calls that plain code can replace. For the top 3 routes, split tokens by class and prompt component (system, tools, history, tool results, retrieval, output, reasoning).
  3. 3Fix caching. Check cache hit rate per route. Diff 2 consecutive requests for dynamic values, reordered tools, GPT-6.2 top-level instructions, mid-session setting switches, or TTL expiries. Verify fan-out warming and pre-5.6 OpenAI prompt_cache_key bucketing.
  4. 4Cut fixed overhead. Measure turn-1 tokens before the first user message. Trim root rules, disable unused MCP servers, scope skills per workspace, and defer rarely used tools (>= 10 tools).
  5. 5Shrink tool, error, and browser outputs. Filter logs, DOM, and error traces in code; cap script stdout; isolate screenshots; offload raw dumps to disk.
  6. 6Shorten loops and enforce caps. Inspect turn counts, selector-mutation retries, and error loops. Clear stale tool results when break-even holds, cap compactions at <= 2, and set cliff-aware context caps.
  7. 7Move deferrable work (API only). Route evals, backfills, and claim checks to Batch, Gemini Flex, or OpenAI background mode.
  8. 8Tune output and effort. Replace whole-file rewrites with diffs, calibrate output caps (max_tokens / max_output_tokens), and tune effort per independent step (or per-message effort on supported Claude models) behind an eval.
  9. 9Test routing or model swaps. Shadow-test static subagent tiers, advisors, or cascades behind the eval gate.
  10. 10Lock it in. Add quality, cost, and latency assertions to CI, alert on cache hit rate and p95 cost per task, and re-baseline after every model upgrade.

Reference index (Token Efficiency Reference)

Load only the exact section you need from the Token Efficiency Reference section below:

  • •## Token economics (token classes, cost equation, worked 50/100-turn math, pricing cliffs, billing modifiers, p95 tail)
  • •## Prompt caching and layout (layout rules, Anthropic/OpenAI/Gemini caching table, usage schemas, stream parsing, operational rules)
  • •## Context engineering (context rot, observation masking, compaction, multi-window harnesses, multimodal/browser trimming)
  • •## Tools, skills, and MCP (deferred loading, progressive disclosure, MCP vs CLI, result shaping, code execution)
  • •## Model routing and reasoning effort (cost per task vs token, routing patterns, effort benchmarks and defaults)
  • •## Retrieval (long-context vs RAG vs grep, chunking, reranking, compression, multi-turn eviction)
  • •## Output control (diffs, structured output retry math, reasoning-vs-structure rule, output caps across providers)
  • •## Agent architecture (escalation ladder, multi-agent evidence, subagent break-even, fan-out handoffs, resumability, OWASP denial of wallet)
  • •## Batch, async, and response caching (Anthropic/OpenAI/Gemini Batch, Flex, OpenAI background mode, discount-stacking truth, semantic cache risks)
  • •## Quality guardrails and known traps (compression hallucination, over-compaction, tokenizer upgrades, non-free savings)
  • •## Measurement and instrumentation (metrics table, OTel GenAI attributes, Langfuse, token counting, alerts)
  • •## Where to look first, by stack (skills/workflows, coding harnesses, LangGraph/LangChain, batch pipelines, RAG/SaaS)
  • •## Sources (all verified primary links grouped by category)

Token Efficiency Reference

Part 4 companion reference: vendor pricing and caching tables, worked math, stack checklists, and primary sources.

Part 4 (evidence, vendor pricing and caching tables, worked math, stack checks, and full citations) for the Token Efficiency Framework. Load specific sections on demand rather than placing this entire file into an agent context.

Currency. Provider tables, parameter names, and pricing facts reflect live vendor documentation. Rates, thresholds, and lifecycle flags change often; re-check vendor pricing pages before forecasting.

Section index: Token economics | Prompt caching and layout | Context engineering | Tools, skills, and MCP | Model routing and reasoning effort | Retrieval | Output control | Agent architecture | Batch, async, and response caching | Quality guardrails and known traps | Measurement and instrumentation | Where to look first, by stack | Sources.

Token economics

Hosted model bills split into five token classes plus service tiers, each priced differently. Identify which class dominates before optimizing.

Token classRelative priceWhat creates itMain lever
Uncached input
1x
System prompt, tool schemas, history, and retrieved docs re-sent every turn
Caching, pruning, retrieval
Cache write
Anthropic: 1.25x (5 min) or 2x (1 hour). OpenAI: 1.25x (30 min) or 2.5x (12 hours) on GPT-5.6+, none earlier. Gemini: standard input (implicit has no storage fee; explicit on 2.5/3 adds hourly storage)
First time a prefix is seen
Keep the prefix stable so writes are rare
Cache read
Anthropic: 0.1x, or 0.05x (Opus/Sonnet 5.5) and 0.025x (Fable/Mythos 5.1 and 5.2; Fable 5 is 0.1x). OpenAI: 0.1x or 0.05x on GPT-5.6/6.x, model-dependent earlier. Gemini: 0.05x (95% off) on Gemini 4; 0.1x (90% off) on 2.5/3 (implicit has no storage fee; explicit on 2.5/3 adds hourly storage)
A prefix hit
Cache hit rate
Output
Several times input rate (typically 4x to 8x)
Visible answer, tool-call arguments, generated code
Output control
Reasoning (thinking)
Billed at the output rate, mostly invisible
Effort or thinking setting
Effort control
Batch, flex, or async tier (API only)
50% off (Batch / Gemini Flex / legacy OpenAI Flex); 30% to 40% off (OpenAI Responses API background mode)
Latency tolerance
Route async work off the realtime path

The cost equation. Cost per successful task equals the sum over every call in the task of (uncached_input * input_rate + cache_writes * write_rate + cache_reads * read_rate + (output + reasoning) * output_rate), divided by the task success rate, with batch, flex, or background discounts applied to deferrable routes.

Worked example (strict prefix-match arithmetic, not a benchmark). Take a 50-turn agent with a 10K-token fixed prefix, where turn 1 starts with the 10K prefix and each turn appends 300 assistant output tokens followed by a 2K-token tool result (G = 2.3K) to history. Price input at 1x, output at 5x, cache read at 0.1x, and cache write at 1.25x, with cache invalidation strictly from the edited turn forward:

  • •Uncached: 3.39M input-token equivalents (3.32M input plus 0.075M output equivalents).
  • •Cached (append-only): 0.55M equivalents (547,855), an 84% cut. Cache reads make up 58% of what remains (49% from old history alone, 9% from the 10K fixed prefix).
  • •Batched clearing (keep 5 most recent turns, 50-token placeholder): Clearing every 10 turns while future turns remain (turns 10, 20, 30, 40) drops cached cost from 0.55M to 0.45M (447,650, an 18% cut); clearing on turn 50 as well wastes 12.3K equivalents on an unrecouped rewrite (0.46M, a 16% cut). Across clearing cadences of every 5 to 15 turns, the cut ranges from 16% to 19% when skipping all unrecouped end-of-session clears (14% to 19% when skipping turn 50 only; 12% to 19% if clearing on all multiples through turn 50).
  • •Clearing every turn: Replacing the 6th-most-recent (oldest uncleared) tool result on every turn invalidates the 5 turns after the edit point (11.55K tokens under standard assistant-before-tool ordering), raising cost to 0.82M (822,855, 1.5x caching alone; 0.84M if the entire 6th-most-recent turn rewrites). If a framework rewrites history from turn 1 instead of in place, cost climbs to 1.22M.
  • •Doubling to 100 turns: Cached cost grows to 1.66M (1,661,855), 3.0x the 50-turn cached cost, because per-turn cache-read billing still scales quadratically.

Three structural facts follow:

  1. 1Agents are input-dominated. Manus reports roughly 100 input tokens per output token. Every turn re-sends history, so uncached prompt volume grows quadratically with turn count (OpenAI, Codex agent loop). Prompt caching makes prefill compute linear on cache hits and cuts re-read price by 90% or more, but because cache-read tokens are still billed on every turn, total billed cost remains quadratic in turn count (see the 50- vs 100-turn math above).
  2. 2Reasoning is hidden output. OpenAI and Anthropic both bill thinking tokens as output. A 300-token visible answer can carry thousands of billed tokens.
  3. 3Optimize tokens per completed task, not tokens per request. A cheaper call that triggers a retry, a re-read, or a wrong answer costs more (Factory).

Long-context pricing cliffs and stream-cancel traps. Several providers re-price the entire request once input crosses a threshold:

  • •Anthropic Haiku 5.5: Prompts above 100K tokens bill the entire request at 5x the base rate; prompt length counts all input tokens, including cache reads and cache writes, so cache hits still trigger the 5x tier above 100K. Other 1M-context Claude 4.6+ models (Opus 5.5, Sonnet 5.5, Fable 5.2) price flat across 1M tokens (Anthropic pricing).
  • •Google Gemini Pro (2.5 Pro, 3.1 Pro): Prompts above 200K tokens bill the whole request at 2x input and 1.5x output (Gemini pricing; note gemini-2.5-pro is flagged deprecated on Gemini pricing, with scheduled auto-routing). Gemini 4 Carbon and Argon price flat across 1M tokens.
  • •xAI Grok: Prompts from 200K tokens upward (inclusive) bill the whole request at 2x across input, cached input, and output (Digital Applied).
  • •OpenAI GPT-5.6 and GPT-6.x (including GPT-6.2 Astra/Sol): Prompts above 272K input tokens bill the whole request at 2x input/cache and 1.5x output.
  • •Orphaned streams: A client-side disconnect can leave backend generation running and billing. Cancel generation on the backend, not only on the socket (Ably).

Billing modifiers. Check these before forecasting (Anthropic pricing, Gemini tiers):

  • •Anthropic fast mode and residency: Fast mode is 2x on all supported models (Opus 5.5, Fable 5.2, Mythos 5.2, Opus 5, and Opus 4.8, for up to 2.5x faster output), stacks with caching and US-only residency, and cannot combine with Batch. US-only inference (inference_geo="us", Claude 4.6+) adds 1.1x to every token class.
  • •Gemini priority tier: Costs 75% to 100% more than Standard.
  • •Anthropic hidden tool prompt: Supplying tools on Anthropic adds a hidden system prompt of 286 to 804 tokens per request, depending on model and tool_choice.
  • •Web search fees: Anthropic bills $10 per 1,000 searches on top of returned tokens (OpenAI standard/reasoning web search is also $10 per 1,000 plus content tokens, while non-reasoning preview is $25 per 1,000 with free content tokens; Gemini 3/4 Grounding with Google Search is $14 per 1,000 after 5,000 free requests/month).
  • •Server-side conversation state is not a discount: With OpenAI's previous_response_id, earlier input tokens in the chain are still billed (OpenAI conversation state).

Budget on the tail, not the mean. An empirical study of agentic coding runs found they use about 1,000x the tokens of code chat, that input tokens drive spend, that the same task varies up to 30x in total tokens between runs, and that accuracy often peaks at intermediate spend. Models also underestimate their own token use. Set run budgets from measured p95, not the mean and not the agent's estimate.

Prompt caching and layout

Caching is a strict byte-for-byte prefix match: one changed byte invalidates every block after it.

Layout rules

  1. 1Order by volatility. Static first, dynamic last: Block 1 tool definitions, Block 2 system/developer prompt, Block 3 shared docs and examples, Block 4 session facts, Block 5 conversation. Anthropic hashes prefixes in the order tools, system, messages.
  2. 2Keep the prefix byte-stable. Exclude timestamps, request IDs, user names, and random ordering from Blocks 1 to 3. Serialize JSON deterministically with stable key order. A second-precision timestamp at the top destroys cache hits (Manus).
  3. 3Make history append-only between planned edit points. Never rewrite earlier turns in place. Batched tool-result clearing (Context engineering) is the planned exception: clear only when saved future reads exceed the tail rewrite cost, or right after a TTL expiry.
  4. 4Freeze the tool set per session. Adding, removing, or reordering tools rewrites Block 1. Keep the tool list fixed and restrict callability via allowed_tools or tool_choice: none on OpenAI, or deferred loading on Anthropic (Anthropic tool search).
  5. 5Put changing facts in messages, not the system prompt. Session-start facts (date, initial mode, worker-specific briefs, tenant ACL facts) go in Block 4 (fixed for the session); mid-session mode switches and reminders append to Block 5. On OpenAI GPT-6.2+ in the Responses API, top-level instructions append after input and bill uncached; place reusable system prompts in an input_text block inside a developer message instead.
  6. 6Hold models and top-level settings steady within a session. Caches are per model, so switching models mid-thread re-bills history as uncached input (Claude Code team). On Anthropic, changing tool_choice or adding/removing an image invalidates message caches; changing top-level thinking or output_config.effort invalidates message caches and, on some models, tool and system caches too (use beta per-message effort via a role: "system" message inside messages with header mid-conversation-output-config-2026-07-01 on supported Claude 5/5.1/5.2/5.5 models, including Opus 5/5.5, Sonnet 5.5, Haiku 5.5, Fable 5.1/5.2, and Mythos 5.1/5.2, to preserve the cache); toggling web search, citations, or fast mode invalidates system and message caches (Anthropic caching). On OpenAI, changing top-level reasoning.effort can invalidate the hidden system prefix, while supported GPT-6+ models preserve the cache via an appended configuration_update input item (OpenAI prompt caching). Verify mid-session effort changes on Gemini and pre-GPT-6 OpenAI models with consecutive-request usage diffs.
  7. 7Forks and compaction must reuse the parent prefix. A compaction call with a different system prompt pays full input price for the entire history.

Provider caching behavior

ProviderTriggerRetentionWrite costBreak-even and key constraints
Automatic (top-level field) or up to 4 explicit breakpoints
5 min sliding, or 1 hour (split TTLs supported per breakpoint)
1.25x (5 min) or 2x (1 hour)
Breaks even after 1 read (5 min) or 2 reads (1 hour). Minimum prefix is 512 to 4,096 tokens by model; shorter prefixes skip caching silently. Each explicit breakpoint looks back at most 20 blocks, so long histories need extra sliding breakpoints (advance every <= 15 blocks) when not using automatic caching. Changing any tool definition invalidates the full cache.
Automatic (1,024+ visible tokens on GPT-5.6+; varies by settings earlier); optional explicit breakpoints on GPT-5.6+
GPT-5.6+: 30 min (default) or 12 hours. Earlier: in-memory (minutes) or up to 24 hours
GPT-5.6+: 1.25x (30 min) or 2.5x (12 hours). Earlier: none
GPT-5.6+ breaks even after 1 read (30 min) or 2 reads (12 hours). Hits are best effort. prompt_cache_key routes shared prefixes on pre-5.6 models (~15 rpm per key; pool into ceil(rpm/12) buckets) and separates accounting on 5.6+. On GPT-6.2+ Responses API, top-level instructions append after input and bill uncached; use a developer message.
Implicit (on by default, best effort) on 2.5+. Explicit cache objects on generateContent for 2.5 and 3 only (unsupported on Gemini 4 and Interactions API)
Implicit: automatic, ephemeral, best effort (Gemini 4's only mode). Explicit: configurable TTL, default 1 hour
Standard input (implicit has no storage fee; explicit adds hourly storage)
Gemini 4 requires 4,096+ token minimum prefix (2,048 on some legacy models). In Gemini 4 multi-turn loops, the full previous request caches only if the next request adds at least 2,050 new tokens (output, thoughts, and function results combined); for smaller additions, Gemini re-processes the last 2,050 tokens of the previous request at standard input rates.

Operational rules

  • •Track hit rate as cache_read_tokens / total_input_tokens per route. Manus treats KV-cache hit rate as the single most important agent metric; the Claude Code team alerts on drops as incidents.
  • •Compute hit rate and cost from each provider's exact schema:
  • •Anthropic: input_tokens excludes cached tokens. Total input = input_tokens + cache_creation_input_tokens + cache_read_input_tokens. On streams, input/cache counts arrive in message_start and output counts in message_delta.
  • •OpenAI: Chat Completions reports prompt_tokens_details.cached_tokens as a subset of prompt_tokens (pass stream_options.include_usage=true on streams; usage arrives only in the final chunk). Responses API reports input_tokens_details.cached_tokens and, on GPT-5.6+, input_tokens_details.cache_write_tokens (billed at 1.25x or 2.5x instead of 1x) as subsets of input_tokens.
  • •Gemini: Reports usageMetadata.cachedContentTokenCount (or usage.total_cached_tokens) as a subset of prompt/input tokens.
  • •On aborted, timed-out, or mid-stream-errored calls, terminal usage chunks never arrive while providers still bill input plus generated tokens. Reserve input tokens pre-flight and debit local fallback output counts on abort so gateway caps never log $0.
  • •Pick split TTLs from traffic shape: long TTL (1h / 12h) on static Blocks 1 to 3 when idle gaps exceed the short TTL (5 min on Anthropic, 30 min on OpenAI GPT-5.6+) and break-even reads hold, short TTL on session-scoped Blocks 4 to 5. When a slow tool or wait expires the cache, prune or compact immediately at zero extra cache penalty.
  • •Diff two consecutive requests whenever hit rate drops. The cause is nearly always a dynamic value, a reordered tool list, GPT-6.2 top-level instructions, a mid-session setting change, or history rewriting.
  • •Caching buys throughput: on most Claude models, cache-read tokens do not count toward input-tokens-per-minute limits (Anthropic rate limits).
  • •Pre-warm before a fan-out or traffic spike. A cache entry exists only after the first request starts, so parallel requests launched together all miss. Send 1 request first (or use Anthropic's max_tokens: 0 pre-warm, which skips generation and is unsupported with streaming, extended thinking, structured outputs, forced tool choice, or batches), then fan out. Pre-warming is reliable on Anthropic and best effort on OpenAI and Gemini.
  • •Know cache scope: Anthropic isolates caches per organization and per workspace on its direct API.
  • •On OpenAI reasoning models, use the Responses API so reasoning items persist across tool calls. An archived OpenAI test on o3/o4-mini raised cache utilization from 40% to 80% vs Chat Completions (OpenAI reasoning items).
  • •Further reading: OpenAI Prompt Caching 201, AWS Agentic AI Lens.

Context engineering

Context engineering aims for the smallest set of high-signal tokens that completes the task (Anthropic).

Why less is better. Chroma tested 18 models and found reliability falls as input grows, even on simple tasks, and falls faster with distractors. Liu et al. showed accuracy drops when needed facts sit mid-context. A long window is a ceiling, not a target.

The four moves (LangChain): write context outside the window, select what enters, compress what stays, isolate noisy work in separate windows.

Tactics, cheapest and safest first

TacticWhat to doEvidence
Clear stale tool results
Replace old tool outputs with a short placeholder (preserving paths, IDs, error strings) once acted on; keep the call record
JetBrains: observation masking halved cost vs an unmanaged agent and matched LLM summarization on solve rate. Anthropic: context editing cut tokens 84% in a 100-turn web search eval and lifted an agentic search eval by 29%.
Offload to files
Write plans, findings, and large outputs to disk; keep a path or URL in context
Manus treats the file system as unlimited external memory.
Load just in time
Hold references (paths, IDs, queries) and fetch content only when needed
Claude Code loads CLAUDE.md up front and finds files with glob and grep on demand.
Compact with structure
Near the limit (and before pricing cliffs), merge into fixed sections (intent, files changed, decisions, next steps) rather than regenerating
Factory: anchored structured summaries scored 3.70 vs 3.44 and 3.35 for two provider defaults over 36,000+ messages.
Isolate
Give noisy subtasks their own window and return a compact summary or disk path
See Agent architecture and the subagent break-even rule in the Token Efficiency Framework.

Evidence and operational rules

  • •Compact at task boundaries before the window fills or crosses a pricing cliff (<= 0.85 * min(window, cliff), or <= 0.85 * window when flat-priced). Compaction reads the entire history it summarizes; when the next task is unrelated, start fresh instead.
  • •Hard-cap compactions at <= 2 per session so repeated summarization does not erode negative constraints or trigger re-fetch loops; after 2 compactions, start a fresh session hydrated from disk artifacts and re-inject a machine-generated verbatim ID block.
  • •Batch context edits only when saved future reads exceed the tail rewrite cost (removed_tokens * remaining_turns * r_read > rewritten_tail * (r_write - r_read)).
  • •Keep recent errors and failed attempts that remain relevant so the agent does not repeat them (Manus).
  • •Budget fixed overhead separately from task overhead: measure session fixed overhead before turn 1 (system prompt, core tools, root rules, skill frontmatter) and cap it.
  • •Trajectory pruning works on coding agents: AgentDiet removed useless, redundant, and expired steps and cut input tokens 39.9% to 59.7% (40% to 60%) and total cost 21.1% to 35.9% (21% to 36%) at equal performance.
  • •Use a memory layer for long-lived assistants, not short chats. Mem0 reported over 90% token savings and 91% lower p95 latency vs full history replay on LOCOMO, but memory retrieval can miss facts present in full history, so eval on your own data.
  • •Start with native server-side compaction (Anthropic compaction, OpenAI compaction) before writing your own. Anthropic lets you customize the summary prompt. OpenAI's compaction item is encrypted and opaque, so you cannot inspect what survived; avoid opaque compaction when exact verbatim IDs or audit trails are required.
  • •For work spanning multiple context windows, do not stretch one session. Start fresh and rebuild state from durable artifacts: a progress file, a pass/fail task list, and git history (Anthropic long-running harnesses).
  • •Trim multimodal and browser payloads. Crop and downscale images, send only relevant PDF pages, extract text when layout does not matter, and transcribe audio/video locally before calling an LLM. On Gemini 3 and 4, media_resolution low costs 280 tokens per image vs 1,120 at default (Gemini media resolution); gate lower resolution with an eval for dense text or charts. On Anthropic, isolate screenshots in a disposable 1-turn vision call so images never accumulate in or invalidate a cached worker thread.

Tools, skills, and MCP

Tools spend tokens in three ways: up-front definitions, oversized results in history, and extra round trips that re-read context.

1. Definitions: load on demand

  • •Measure first. Anthropic reports ~72K tokens for 50+ MCP tools and has seen 134K before optimization (Anthropic advanced tool use).
  • •Keep the 3 to 5 most-used tools always loaded and defer the rest behind cache-safe tool search. In Anthropic's example, total context consumption (starting from ~500 tokens for the Tool Search Tool up front plus ~3K of 3 to 5 tools discovered on demand) fell from ~77K to ~8.7K tokens (Anthropic reports 85%; arithmetic gives 88.7%), and Opus 4.5 accuracy on large tool sets rose from 79.5% to 88.1%. Skip deferral below ~10 tools or when every tool runs every session.
  • •Never let tool search mutate Block 1 tool definitions mid-session if you rely on prompt caching; use provider-native defer_loading (which keeps static stubs in Block 1 and expands discovered schemas inline in Block 5) or inject discovered docs as Block 5 tool results.
  • •Use progressive disclosure for skills (SwirlAI). Load only name and description up front (~80 median tokens per Anthropic official skill), then SKILL.md on trigger, then references/ files on demand.
  • •Prefer a CLI the model already knows (git, gh, curl) plus a short usage note over a large MCP schema. Scalekit measured MCP at 4x to 32x the tokens of a CLI on identical GitHub tasks when all 43 MCP schemas loaded on every call; deferred loading or a filtering gateway narrows that gap.

2. Results: filter in code and mark every cut

  • •Add a response_format switch (concise vs detailed). Anthropic's example dropped from 206 tokens to 72 (a 65% cut, ~1/3 of the tokens) (Anthropic writing tools).
  • •Add pagination, range selection, filtering, and sensible truncation defaults. Claude Code caps MCP tool outputs at 25,000 tokens by default via MAX_MCP_OUTPUT_TOKENS (unless a tool declares anthropic/maxResultSizeChars, with a 10,000-token warning and automatic file offload above 50,000 characters for non-image results) (Claude Code MCP).
  • •Put highest-signal content first. A telemetry study across five coding agents reportedly observed zero agent-initiated pagination on over-budget tool responses, so the first chunk is all they act on (Codex CLI analysis).
  • •Never truncate silently. State what was cut and write the full output to a file path returned in the preview. Apply the same truncation cap to error payloads.
  • •Return semantic names instead of UUIDs and raw internal codes. Make error messages state how to fix the call so retries are not wasted.
  • •Preprocess noisy outputs in code before the model sees them. Claude Code's docs show a hook that greps a 10,000-line log for ERROR (cutting tens of thousands of tokens to hundreds) and a PreToolUse hook that trims test output to the last 100 lines (Claude Code costs). Apply the same wrapper pattern to return only failing tests or targeted browser DOM fields instead of raw HTML/accessibility dumps.
  • •Filter web pages before they enter context. Anthropic's dynamic filtering has the model write code to prune search results first: 24% fewer input tokens and ~11% higher accuracy across two benchmarks. Price-weighted cost fell on Sonnet 4.6 but rose on Opus 4.6 because filtering code bills as output (Anthropic dynamic filtering).
  • •Serialize compactly. Minify JSON first. Use CSV or TSV for flat uniform tables. For nested data, one benchmark measured Markdown at 34% to 38% fewer tokens than JSON, with YAML scoring highest on accuracy for two of three small models (Improving Agents). TOON used ~33% fewer tokens than formatted JSON on its mixed-structure benchmark, matched minified JSON, and lost to CSV on flat tables. Accuracy gaps between formats were mostly within noise, so measure on your own payloads.

3. Round trips: move loops out of the model

  • •Let the model write sandboxed code that calls tools, filters intermediate data, and returns only the answer. Anthropic's example fell from 150,000 tokens to 2,000 (Anthropic code execution with MCP). Cloudflare collapsed 2,500 endpoints from 1.17M definition tokens to ~1,000 (Cloudflare Code Mode). An independent test measured 78.5% fewer input tokens, 2.2x output tokens, and a 77% net token reduction (price-weighted cost reduction is smaller when output bills at 5x input, ~73% on those exact averages) (AIMultiple).
  • •Know when code execution does not pay. Anthropic measured 37% fewer tokens on complex research tasks (Anthropic advanced tool use), while on tau-squared-bench (1 to 2 sequential calls per turn) it left scores unchanged and cost ~8% more (agentpatterns.ai). Use it for 3+ dependent calls, large intermediate data, or fan-out.
  • •Issue independent tool calls in parallel so each batch avoids extra full-context reads.

Model routing and reasoning effort

Judge every model or effort choice by cost per completed task, not price per token. Artificial Analysis estimated Claude Sonnet 5 at ~$2.29 per Intelligence Index task vs $1.99 for Opus 4.8 using Anthropic's originally planned $3/$15 rates (excluding launch pricing); at max effort, Sonnet 5 used ~40% more output tokens and ~3x the agentic turns of its own predecessor Sonnet 4.6 (Wavect). After Anthropic cancelled the planned increase and made $2/$10 permanent, the same usage scaled to ~$1.53, showing why you must recalculate whenever prices move. Expected cost per solved task equals average cost per attempt divided by success rate (DoiT).

Routing patterns, simplest first

PatternHow it worksEvidenceWatch for
Rules or embedding router
Regex, keywords, or embeddings route known intents before any LLM call
Zero LLM routing tokens. One write-up put embedding routing ~65x cheaper than LLM classification, with a hybrid within 2% accuracy (thin methodology)
Needs a fallback for unmatched inputs
Static map by task type
Extraction, classification, and summaries go to small models; planning and hard reasoning go to large models
Most reliable production pattern
Re-check after model launches
Tiered agents
Large model plans and verifies; small model executes volume work in subagents
Common in coding harnesses
Orchestrator and handoff tokens dominate: 93% of cost in one illustrative modeled run (Beam). Keep briefs and returns short
Advisor
Small executor runs the loop and consults a large model only when stuck
Anthropic: Sonnet + Opus advisor scored +2.7 points on SWE-bench Multilingual at 11.9% lower cost per task; Haiku + Opus advisor hit 41.2% on BrowseComp vs 19.7% solo, at 85% lower cost than Sonnet solo (lower score)
Cap advisor calls with max_uses
Cascade
Try cheap first; escalate on failed validation
FrugalGPT matched the best single model at up to 98% lower cost on its test sets
Escalate on verifiable checks, not self-reported confidence
Learned router
Classifier picks a model per query
RouteLLM (paper): 85%+ cut on MT Bench, 45% on MMLU, 35% on GSM8K, each at 95% of GPT-4 quality (a 5% quality trade)
Benchmark-trained routers misroute live traffic; shadow-test first

Routing and effort rules

  • •Route whole threads or independent subtasks, not individual turns inside a cached session.
  • •Escalate on deterministic evidence (failed tests, schema errors, calibrated judge checks), never on stated confidence.
  • •Track tier-hit distribution and quality per tier so aggregate scores do not mask segment regressions.
  • •For narrow, high-volume tasks, a fine-tuned or distilled small model can replace both a large model and a long prompt, gated by a ground-truth eval.
  • •Tune reasoning effort behind an eval. Vals AI tested half-benchmark subsets (mostly single runs, so directional only): a cheaper setting showed no significant drop on 22 of 56 model-benchmark pairs, 33 scored significantly lower, and no model matched its full-index score at its lowest setting. At lowest effort, four of seven models kept 80% to 89% of score for 16% to 50% of cost (a 50% to 84% cut), with steepest drops on legal research, code migration, terminal, and tax tasks.
  • •Higher effort is not monotonic. A multi-benchmark study across four benchmarks found higher effort sometimes failed tasks lower effort solved; starting low and escalating on a verified external failure matched or beat fixed top effort across all four, cutting median API cost by 15.5% to 41.5% on AIME, GPQA, and corrected SWE-Bench Pro (and reducing cost on 4 of 8 models on Terminal-Bench).
  • •Reasoning models overthink easy prompts (arXiv 2412.21187). Drop "think step by step" on reasoning models: Wharton measured ~3% or smaller gains for 20% to 80% more time.
  • •Assign top-level effort per independent workflow step or subagent; mid-session top-level effort changes invalidate Anthropic caches (use beta per-message effort with header mid-conversation-output-config-2026-07-01 on supported Claude 5/5.1/5.2/5.5 models, or OpenAI GPT-6+ configuration_update items, if changing effort mid-thread). On Claude, effort affects text, tool calls, and thinking; low effort is the documented setting for simple subagent work, and defaults are high on most models and medium on Opus 5.5 and Haiku 5.5 (Anthropic effort). OpenAI uses reasoning.effort; Gemini uses thinking levels.

Retrieval

Precision of retrieved context matters more than window capacity.

SituationApproachEvidence and trade-offs
Small reused corpus
Put in cached prefix, skip retrieval
Simplest; Anthropic's rule of thumb is under ~200K tokens (~500 pages) (Anthropic contextual retrieval)
Large corpus, sparse queries
Retrieval (RAG)
A case study (manufacturing safety training, small models) measured long-context prompting at ~26x the per-query tokens of RAG, with higher correctness (73.1% vs 65.4%)
Code repositories
Agentic search (grep, glob, reads)
Claude Code dropped its vector index for agentic search, per its creator's public remarks. Needs no index and never goes stale, though it spends more turns per lookup than vector queries. Beyond code, a conversational-memory QA study found grep generally beat vector search inside agent harnesses, with high harness sensitivity
Heterogeneous prose, fuzzy queries
Hybrid embeddings + BM25
Embeddings capture meaning; BM25 catches exact identifiers

Tuning rules

  • •Retrieve wide, rerank, then pass the fewest chunks that hold recall. In one systems study, retrieval metrics rose with broader k while exact match and F1 moved non-monotonically; Anthropic's own test found 20 chunks beat 5 and 10. Sweep k on your eval.
  • •Improve recall before adding chunks: Anthropic's contextual embeddings plus BM25 plus reranking cut top-20 retrieval failures from 5.7% to 1.9%.
  • •Match chunk size to query type: a multi-dataset study found 64 to 128 tokens best for short factual questions and 512 to 1,024 tokens for broader context questions.
  • •Place strongest chunks first or last, not in the middle.
  • •Compress retrieved text only behind an eval. RECOMP's trained compressors compressed prompts down to 6% of original length (~16x) with minimal loss on its QA and language-modeling tasks; LLMLingua reported up to 20x. Prefer extractive over abstractive compression so original sentences are preserved, though dropping context can still mislead the model (see Quality guardrails and known traps).
  • •Place volatile retrieved chunks in Block 5 after the cached prefix. In multi-turn RAG sessions, deduplicate retrieved chunk IDs against history, batch-evict stale chunks before pricing cliffs, and start fresh when the topic shifts.

Output control

Output tokens cost several times input tokens and cannot be cached.

  • •Ask for the artifact only. Cut preambles, question restatements, and closing recaps. Return labels, IDs, or enums for classification and extraction.
  • •Edit by diff, not whole-file rewrite. Search-and-replace or diff edits use far fewer output tokens than re-emitting files (Aider edit formats). Measure failed-apply retry rates per model before standardizing a diff format.
  • •Use native structured output carefully. Constrained decoding pushes schema failures well under 1% on in-distribution inputs; failures cluster on deep nesting and huge enum unions. Keep schemas shallow, keys short, and optional fields few. On non-reasoning models performing hard synthesis, reason in plain text first and convert to JSON in a cheap follow-up call (per the Verifiable Output Framework, strict format constraints degrade reasoning); reasoning models already think unconstrained before emitting structured output. Retries multiply cost: at equal prompt size, a 2% independent failure rate with up to three retries adds ~2.04% extra calls (up to 6% if every failed input exhausts all three retries); one unmeasured write-up estimates 12% to 18% when failed calls average three total attempts with larger retry prompts and longer outputs (Tian Pan).
  • •Calibrate output caps from real logs. Use max_tokens on Anthropic, max_output_tokens on OpenAI Responses API and Gemini, and max_completion_tokens on OpenAI Chat Completions. Set caps just above the measured p95 tail. On reasoning models, output caps include thinking tokens, so an overly tight cap returns empty visible output while billing input and thinking (OpenAI reasoning).
  • •Use verbosity parameters where supported. OpenAI exposes text.verbosity (low, medium, high) independently of reasoning effort (OpenAI GPT-5 params). Elsewhere, set explicit length targets.
  • •Reference instead of quoting. Point to file paths, line ranges, and IDs rather than repeating text.
  • •Cap and cache few-shot examples. Sweep 0, 1, 2, 4, and 8 examples on your eval (2 to 5 usually capture the gain) and store them in Block 3 of the cached prefix.
  • •Prune dead prompt instructions behind an eval. Remove workarounds newer models follow natively; re-test after every model upgrade.

Agent architecture

Architecture sets the token floor before any prompt tuning begins.

Escalation ladder

  1. 1Plain code. One analysis of 14 production agent workflows found 65% of nodes ran best as pure code (Tomasz Tunguz).
  2. 2One model call with retrieval and cached examples.
  3. 3Code workflow. Predefined chains, routers, and parallel fan-outs (Anthropic building effective agents).
  4. 4Plan then execute. One planning call, tool execution without history replay, one solve call. ReWOO reported ~5x token efficiency over ReAct on HotpotQA with slightly higher accuracy, at the cost of mid-run adaptability.
  5. 5Single agent loop with managed context.
  6. 6Subagents and multi-agent. Parallel, high-value, read-heavy, or strictly sharded work only.

Multi-agent evidence

SourceFinding
~15x tokens of a chat (4x for a single agent). Beat a single agent by 90.2% on Anthropic's internal research eval; token spend explained 80% of variance on BrowseComp. Anthropic notes most coding tasks are a poor fit.
Google Research (180 configs)
Up to 81% better on parallelizable tasks, 39% to 70% worse on sequential reasoning. Independent agents amplified errors 17.2x vs 4.4x with a central orchestrator.
Parallel writers make conflicting implicit decisions. Multi-agent works when writes stay single-threaded (clean-context reviewer, strong consultant, or manager delegating isolated subtasks).
MAST (1,600+ traces)
Identified 14 recurring multi-agent failure modes in 3 categories; benchmark gains over single agents are often minimal.

Architecture rules

  • •Use subagents for context isolation, model arbitrage, or clean-context review, not role-play. Anthropic's research subagents commonly explore tens of thousands of tokens and return 1,000 to 2,000 tokens. On the same model, check the subagent break-even rule in the Token Efficiency Framework (accounting for cold-start prefix write, brief output, summary output, and synthesis turn vs saved parent-history re-reads across multi-turn subtasks). On fan-outs of 5+ workers, write outputs to disk and return ~100-token status rows so flagship orchestrators do not hit quadratic handoff bloat.
  • •Parallel fan-out caching: Place shared Blocks 1 to 3 before each worker's custom brief and send 1 warming request before launching the batch; stateless parallel workers then pay 0.1x cache reads on the shared prefix rather than 1.25x cold writes.
  • •Scope each agent narrowly (12-Factor Agents) and never poll background workers in an LLM loop.
  • •Compact error traces before re-entry: Pass the failing line and message, not a full stack dump.
  • •Enforce hard stops at two layers: Put max turns, shared run-level token/dollar caps (max_depth = 1, max subagents, per-item cap), timeouts, and (tool_name, target_entity) error circuit breakers in code. Add gateway-level per-key/tenant caps on API deployments.
  • •Keep always-loaded instruction files short. Anthropic's Claude Code docs target under 200 lines per CLAUDE.md (Claude Code memory); HumanLayer keeps its root file under 60 (HumanLayer).
  • •Prevent rework first: Write specific specs, plan large changes, and give agents deterministic self-verification (Claude Code costs).
  • •Make runs resumable: Use file-based write-as-you-go shard ledgers with atomic claim-before-work locks in CLI workflows and checkpointers in graph frameworks (LangGraph checkpointers).
  • •Treat spend as an attack surface (OWASP LLM Top 10: unbounded consumption / denial of wallet). Cap input size pre-flight, output size, and calls per user, not only per run (Forcepoint overview).

Batch, async, and response caching

OptionDiscountTrade-offUse for
50% on input, output, and cached tokens
Async; most finish under 1 hour, 24-hour SLA
Evals, backfills, enrichment, nightly reports
OpenAI Batch API
50% (stacks with caching on GPT-5+)
Async, up to 24 hours; no batch caching on pre-GPT-5
Same
OpenAI flex processing (winding down)
50% on legacy supported models; Responses API background mode offers 30% off (2h) or 40% off (8h) on supported GPT-6+ models (GPT-6 Luna, GPT-6.1 Terra, GPT-6.2 Astra/Sol)
Flex beta is winding down and unavailable on GPT-6.2 Astra/Sol and future models; slower, timeouts, uncharged 429s
Legacy single-request pipelines; use Responses API background mode or Batch API on GPT-6.2+
50% each
Batch: up to 24 hours. Flex: synchronous, 1 to 15 min target, preemptible
Deferrable bulk jobs; flex suits sequential steps that tolerate wait times
Exact-match response cache
100% on hits
Repeatable, non-time-sensitive inputs only
Low-temperature classification/extraction, eval reruns, repeated sub-tasks
Semantic response cache
100% on hits
False hits return wrong answers
FAQ-style traffic only
  • •Discount stacking by provider: Batch and flex discounts halve cached-token rates on Anthropic, OpenAI (GPT-5+ for Batch; legacy supported models for Flex), and Gemini 4. On Gemini 3.1 Pro and 2.5 Pro, Batch and Flex halve uncached input and output only, while cache hits bill at standard context-caching rates (Gemini pricing). In Anthropic batches, cache hits are best effort (30% to 98% reported), so use identical breakpoints across batch items and 1-hour TTL for shared prefixes.
  • •Classify routes interactive vs deferrable at design time. Evals, claim verification, backlogs, labeling, and bulk generation are deferrable.
  • •Treat semantic caching as a correctness risk first. One vendor-published review of public data puts realistic hit rates at 20% to 45% (noting 95% marketing figures usually refer to match accuracy, not hit rate) (Preto). An InfoQ bank FAQ study measured up to 99% false positives at a default 0.7 threshold on two embedding models, dropping to 3.8% only after threshold tuning, preloaded FAQs, and cache quality controls.
  • •For both exact-match and semantic caches, scope keys by tenant_id, ACL/role, model, and prompt_version; for semantic caches, start with a strict threshold, never cache personalized or time-sensitive data, and grade sampled hits continuously.
  • •Memoize tool lookups within a run and reuse plan templates keyed by task type (AWS Agentic AI Lens).

Quality guardrails and known traps

See Anthropic demystifying evals for AI agents and the CI regression pattern (promptfoo pattern) for setting up quality, cost, and latency gates. Always separate zero-token deterministic checks (schemas, unit tests, exit codes) from calibrated LLM judges (different model family or calibrated 3-model jury measuring catch rate and clean-item FPR on the combined decision: >= 80% catch rate, <= 10% clean-item FPR only for proof-gated or human-triaged workflows, <= 10% warning-level FDR in production, and deterministic proof or human review on low-error-rate auto-acting gates per the Verifiable Output Framework).

  • •Compression increases hallucination. An empirical study of six methods across 13 datasets found every method raised hallucination through information loss. A second study found extractive compression held up to ~10x with minimal accuracy loss while token pruning lagged.
  • •Over-compaction causes rework. If an agent re-reads files or repeats dead ends after compaction, the summary dropped load-bearing state. Track re-fetch rate (Factory).
  • •Silent truncation makes agents confidently wrong. Always announce cuts and provide the path to full data.
  • •Tokenizer upgrades shift spend. On Claude Opus 4.7, Anthropic disclosed up to 35% more tokens for identical text at unchanged per-token rates, and OpenRouter measured 32% to 45% depending on prompt size. Re-count tokens and re-baseline after every model change.
  • •Headline savings are often quality trades. Lowest-effort runs kept 80% to 89% of score, RouteLLM held 95% of strong-model quality, and RAG trailed long-context accuracy in the cited study. Ship those levers only where your eval accepts the trade.

Measurement and instrumentation

MetricDefinitionWhy it matters
Cost per successful task
Total spend / passing tasks (median and p95)
North-star unit metric
Tokens per task by class
Uncached input, cache write, cache read, output, reasoning
Shows which lever to pull
Cache hit rate
Cache-read tokens / total input tokens, per route
Drops expose prefix breaks
Session fixed overhead
Tokens before turn 1 (system, core tools, rules, skill frontmatter)
Tax paid on every session and subagent
Turns and tool calls per task
Loop length
Drives quadratic history reads
Tool-result share
Tool output tokens / total context tokens
Flags oversized tool payloads
Retry and failure rate
Schema failures, tool errors, re-runs
Denominator multiplier
Tier-hit distribution
Share of traffic per model and effort level
Confirms routing behavior
Output-length distribution
Per-route histogram
Calibrates output caps
Eval score
Pass rate on deterministic checks + golden set
Hard constraint on every change

Instrumentation notes

  • •Store every field of the provider usage object, including cached, cache-write, and reasoning counts. Capture stream usage cleanly and debit fallback counts on aborted or timed-out streams.
  • •Standardize trace fields on OpenTelemetry GenAI attributes (pin a spec version, as the registry page marks legacy names deprecated in favor of the GenAI conventions repo). Note that OTel defines input tokens to include cached tokens, whereas Anthropic's raw input_tokens field excludes them.
  • •Tag traces with feature, tenant or user, model, prompt version, and run ID so observability tools (Langfuse) break cost down accurately.
  • •Estimate large variable inputs before sending using free token-counting endpoints (Anthropic token counting is free, returns an estimate, and accepts tools, images, and PDFs).
  • •Reconcile logged estimates against provider invoices monthly.
  • •Alert on cache hit rate drops, week-over-week p95 cost-per-task spikes, single-run budget breaches, and fixed-overhead growth after deploys.
  • •Maturity target: move from total spend tracking to unit cost tied to measured outcomes (FinOps Foundation).

Where to look first, by stack

StackFirst checks
Agent skills and file-based workflows
Trim skill frontmatter descriptions and total workspace skill count; move parsing, filtering, and validation into bundled scripts/ with stdout caps; split reference tables into references/; use shard ledgers and worker rotation; filter browser DOM via scripts and isolate screenshots in disposable 1-turn vision calls
Coding harnesses (Claude Code, Codex CLI, OpenCode, Antigravity)
Measure turn-1 fixed overhead via /cost or /context; keep root instruction files concise; disable unused MCP servers (Claude Code now defers tool definitions by default) and prefer CLIs; clear sessions between unrelated tasks; send heavy exploration to subagents; compact at task boundaries (<= 2 per session); set effort per independent task (Claude Code costs)
LangGraph and LangChain agents
Stop passing full message state to every node; adopt built-in middleware (SummarizationMiddleware, ContextEditingMiddleware, ModelCallLimitMiddleware, ToolCallLimitMiddleware) and AnthropicPromptCachingMiddleware (5-min default, 1-hour optional). Measure LLMToolSelectorMiddleware carefully because mutating the tool list per call breaks prefix caching. Enable checkpointers for resume, route extraction/classification nodes to small models, and parallelize independent branches (audit notes)
Batch and data pipelines (API)
Batch, Gemini Flex, or OpenAI background mode; cached shared prefix; native structured output (plain-text reasoning first on non-reasoning synthesis); deterministic pre-filters before any model call; small model with verifiable escalation
RAG and multi-tenant SaaS bots
Rerank to fewer chunks behind eval, deduplicate chunk IDs in history, cliff-aware eviction, tenant/ACL-scoped exact-match cache, pre-5.6 OpenAI prompt_cache_key bucketing, stream usage + abort debiting, and an embedding or rules router before the LLM (intent routing)

Sources

Provider documentation

Engineering write-ups

Research papers

Benchmarks and analyses