Applied AI Systems · Monograph

The Token Budget

Every method for cutting token consumption in LLM and agentic pipelines, the arithmetic that tells you which one to reach for first, the ways each of them fails, and what changes when the pipeline becomes a fleet of agents.

Context window occupancy, one agent turn70% used, 2% is the task
System prompt Tool schemas History Retrieved docs The actual task

Part I

Foundations

What a token actually is, why cutting tokens is an accuracy argument before it is a cost argument, and how to decide which of the twenty methods below apply to your workload.

The two reasons to care

Token optimization gets framed as a cost exercise, and cost is real: in a long-running agent, the same system prompt and tool catalog are re-sent on every single model call, so a 40,000 token preamble in a 30 step loop is 1.2 million billed input tokens for one task. But cost is the smaller half of the argument.

The larger half is accuracy. Liu and colleagues showed that model performance follows a U-shaped curve against the position of the relevant passage: it is highest when the needed information sits at the very start or the very end of the input, and it degrades markedly when the model has to reach into the middle of a long context. Performance also falls as the context simply gets longer, even for models explicitly built for long inputs. Anthropic's context engineering guidance frames the same finding as a design rule: treat context as a finite resource with diminishing marginal returns, and hunt for the smallest set of high-signal tokens that still gets the outcome you want.

So the tokens you cut are not only cheaper, they are often better. That reframing changes what counts as a successful optimization. A method that halves your token count and costs you two points of task accuracy is a bad trade. A method that halves your token count and raises accuracy, because it removed distractors, is the one you want, and several of the methods below do exactly that.

What a token is, concretely

Before any of the arithmetic, it helps to see the unit. A token is not a word and not a character. It is a subword unit produced by a byte-pair encoding trained mostly on English web text, which has three consequences that surprise people: common English words are usually one token while rare ones fragment, many non-Latin scripts cost several times more tokens per unit of meaning, and code pays a penalty for indentation, long identifiers and punctuation runs.

Figure 1Live token estimator
Characters
0
Words
0
Tokens, estimated
0
Tokens per word
0

This is a heuristic estimator, not a real BPE vocabulary: it segments on the usual word, number, punctuation and whitespace boundaries, treats frequent English words as single tokens, splits long or unusual words into subwords, groups digits, and charges non-Latin scripts at roughly one token per character or worse. Expect it to be within about ten percent on English prose and rougher elsewhere. Use it to feel the ratios, not to bill anyone. The pattern to internalize: English prose lands near 0.75 tokens per word, code runs higher because of indentation and identifiers, and the same sentence in a non-Latin script can cost two to three times what its English translation costs, which is a real fairness and budget issue in multilingual products.

A map of the territory

There are only four things you can do. Every method in this monograph is an instance of one of them.

FamilyWhat it changesMethods covered here
Shrink the inputTokens sent per callPrompt caching, semantic caching, compaction, extractive compression, learned compression, retrieval, progressive tool loading, serialization format
Shrink the outputTokens generated per callLength and schema constraints, diffs instead of rewrites, reasoning budget caps
Change the architectureNumber, size and shape of callsModel cascades, batch prompting, distillation and fine-tuning, subagent isolation, programmatic tool calling, serving-layer levers
MeasureWhere you spend effortPer-stage accounting, cache hit rate, retry and error budgets, tokens per solved task
Rates used on this page

All dollar figures use an illustrative $3.00 per million input tokens and $15.00 per million output tokens, with cache writes at 1.25× base input and cache reads at 0.10× base input. Those multipliers match the published Claude prompt caching structure. Substitute your own rates; the shapes of the curves do not move.

Which methods apply to you

The ranked table at the end of this monograph is the general answer. This is the version filtered to your workload. Answer four questions and it reorders.

Figure 2Workload triage

    This is the same thirteen-method table from Part V, re-scored against your answers. It is a starting order, not a verdict: your own per-stage measurements override it the moment you have them.

    Part II

    Shrink the input

    Eight methods, ordered by how much of a typical agent's input they touch. The first two skip work entirely; the rest make the work smaller.

    1. Prompt caching

    Caching is prefix-based and it is the single highest-leverage lever in any repeated-call workload, so it goes first. The provider stores the tokenized prefix of your request up to a marked breakpoint. Any later request that begins with a byte-identical prefix is served from that store. On Claude the prefix is assembled in a fixed order, tools then system then messages, and the cache references everything up to and including the block you mark with cache_control.

    The economics are asymmetric in a way that decides your architecture. A cache write costs about 25 percent more than a normal input token. A cache read costs about 90 percent less. Break-even therefore arrives on the second hit, and everything after that is close to free. The design implication is blunt: put everything stable at the front and never let a variable token drift into the prefix. A timestamp injected at the top of a system prompt invalidates the entire cache on every call, and this is the most common reason a caching rollout shows no savings.

    Figure 3Cache economics over an agent loop
    No cache
    $0
    With cache
    $0
    Saving
    0%
    Cache hit rate
    0%

    Drag the invalidation slider off zero to see the failure mode. At 20 percent drift the cache still helps; at 60 percent you are paying the 1.25× write premium often enough that the benefit largely evaporates. History accumulation is included in both curves, which is why neither line is flat.

    Practical rules

    1. Order the prompt from most stable to least stable. Tools, then system instructions, then few-shot examples, then long reference documents, then the conversation, then the current turn.
    2. Place one breakpoint at the end of the static region. The system finds the longest matching prefix, so a single well-placed marker usually beats several scattered ones.
    3. Move anything volatile, current time, request ID, per-user greeting, out of the prefix and into the suffix.
    4. Match the cache lifetime to the traffic. The short default window suits interactive sessions; a longer window is only worth its higher write premium when you expect enough reads to amortize it.
    5. Log cache_read_input_tokens and cache_creation_input_tokens per call. A sudden spike in creation tokens means someone changed the prompt template.

    2. Semantic caching

    Prompt caching reuses the prefix and still runs the model. Semantic caching skips the call entirely. The incoming query is embedded, compared against a store of previous query embeddings, and if the nearest neighbour is close enough the stored response is returned without touching the model at all. GPTCache is the reference open-source implementation: queries go to the cache first, and a hit returns immediately, saving the API call and cutting response time substantially.

    This is a categorically different mechanism from prefix caching and it has a categorically different failure mode. Prefix caching is exact-match and therefore cannot be wrong. Semantic caching is approximate-match and can be, in two ways. A false hit returns an answer to a question the user did not ask, and embedding models are known to score texts with opposite meanings but similar wording as near neighbours, which is tolerable for search ranking and not tolerable when the cached text is presented as an answer. A stale hit returns an answer that was correct when it was cached and is not any more. The GPTCache authors themselves note that hit rates high enough for production are hard to reach without accepting more of these.

    Figure 4Similarity threshold: hit rate against wrong answers
    Hit rate
    0%
    False hits
    0%
    Calls avoided
    0%
    Wrong answers served
    0 per 1k

    The dashed line marks a one-in-a-thousand wrong-answer budget. Where the false-hit curve crosses it is your real threshold ceiling, and it moves left fast as embedding separation degrades. Note that the two curves are not symmetric: dropping the threshold buys hit rate slowly and buys false hits quickly.

    When it is safe

    3. Context growth and compaction

    In a naive agent loop the context is the full transcript, so cumulative billed input grows quadratically with turn count even though the useful information per turn is roughly constant. This is the cost curve that surprises teams in production: the tenth turn of a session costs several times what the first one did, for no additional user value.

    Anthropic's guidance describes three counters. Compaction summarizes a conversation approaching the window limit and reinitializes with the summary. Structured note-taking pushes durable state out to a file the agent re-reads, so the transcript does not have to carry it. Multi-agent architectures give each subtask its own window. The lightest touch of the three, and the one to try first, is tool result clearing: once a tool has been called deep in the history, the raw result rarely needs to be visible again, so replace it with a short stub and keep the call itself.

    Figure 5Four context management strategies over 40 turns
    Full transcript, total in
    0
    With clearing
    0
    With compaction
    0
    Notes file
    0

    The sawtooth in the compaction curve is the summarize-and-restart event. Note the trade it hides: each compaction is itself a model call that reads the whole window, so aggressive compaction on a cheap workload can cost more than it saves. Compaction earns its keep when the alternative is hitting the window ceiling.

    The compaction failure mode

    Overly aggressive compaction discards detail whose importance only becomes apparent later. The recommended tuning procedure is to maximize recall first, write a compaction prompt that captures every relevant item from a complex trace, then tighten for precision by removing what proved superfluous. Test it against real traces, not synthetic ones.

    4. Extractive prompt compression

    Natural language is redundant, and a model does not need all of it. The LLMLingua line of work exploits this directly: use a small language model to score every token by perplexity, and drop the tokens whose removal barely changes the entropy of the sequence. The original method adds a budget controller that allocates different compression ratios to different regions of the prompt, instructions versus demonstrations versus the question, plus iterative token-level compression that accounts for dependence between the tokens it keeps. The reported headline is up to 20× compression with little performance loss on reasoning, summarization and dialogue benchmarks.

    Two descendants matter for production. LongLLMLingua makes the compression question-aware and reorders documents, which raised benchmark performance while using substantially fewer tokens. LLMLingua-2 reframes compression as token classification, trains a small bidirectional encoder by distilling from a larger model, and is task-agnostic: it runs several times faster than its predecessors and cuts end-to-end latency at 2× to 5× compression ratios.

    Figure 6Informativeness-ranked token dropping
    Original
    0
    Compressed
    0
    Dropped
    0
    Cost per 1k calls
    $0

    This demonstration ranks tokens with a transparent heuristic, function words and high-frequency terms score low, rare and long content words score high, and drops from the bottom up. A real compressor uses a small model's per-token perplexity, which is a far better estimator, but the visible behavior is the same: syntax goes first, entities and numbers survive longest. Push past roughly 50 percent and watch where the sentence stops being reconstructable.

    When not to compress

    Compression adds an inference pass and a failure surface. If your prompt is stable across calls, cache it instead, caching gets you a 90 percent discount with zero information loss, which beats a lossy 3× reduction. Compression is for content that is large, variable, and therefore uncacheable: retrieved passages, freshly scraped pages, per-request transcripts.

    5. Learned compression

    The methods above delete words. A second branch compresses context into learned representations instead, trading a training step for a much higher compression ratio and a representation the model reads natively.

    Gisting trains a model to compress a prompt into a small set of gist tokens using nothing more than a modified attention mask during ordinary instruction finetuning, so downstream tokens can only attend to the prompt through the gists. On LLaMA-7B and FLAN-T5-XXL this reached up to 26× prompt compression with minimal quality loss, and because gists are cacheable activations, the compression is paid once and reused. AutoCompressors extend the idea to long contexts by recursively accumulating summary vectors across chunks. Cartridges take the furthest step: instead of putting a corpus in the window, train a small KV cache offline for that corpus and load it at inference. Naive next-token training on the corpus was not competitive with in-context learning, so the authors use self-study, generating synthetic conversations about the corpus and training with a context-distillation objective. The reported result is roughly 26× higher throughput at matched quality, with the training cost amortized over every query that touches the same corpus.

    MethodCompressesNeedsReuse model
    LLMLingua familyText into shorter textA small scorer at inferencePer request, nothing persists
    GistingPrompt into gist tokensInstruction finetuning of the target modelGist activations cached and reused
    AutoCompressorsLong context into summary vectorsRecursive trainingVectors reused as soft prompts
    CartridgesA whole corpus into a trained KV cacheOffline self-study per corpusCartridge loaded per corpus, amortized over all queries
    The catch that rules these out for most teams

    All of them require access to model weights or the serving stack. If you call a hosted API you cannot use any of them, and prefix caching is the hosted equivalent: it also pays the encoding cost once and reuses it, just without the compression ratio. These belong in your toolbox when you self-host or when a corpus is stable enough and queried often enough to justify an offline training run.

    6. Retrieval instead of stuffing

    The oldest lever and still the most misapplied. Stuffing a whole corpus into a long window is now technically possible and usually still wrong, for the accuracy reason in Part I: the relevant passage ends up in the middle, where recall is weakest, surrounded by distractors that compete for attention. Retrieval sends a small selected subset instead.

    The variant worth adopting in agent systems is just-in-time retrieval: rather than pre-loading content, the agent holds lightweight identifiers, file paths, query strings, record IDs, and pulls the underlying content into context only at the moment it is needed. The identifier costs a dozen tokens; the document costs thousands.

    Figure 7Top-k retrieval against a 96 chunk corpus
    Tokens sent
    0
    Versus stuffing
    0%
    Answer present
    yes
    Distractors
    0

    Ochre outline marks the chunk that actually contains the answer; teal fill marks what gets sent. Degrade the retriever and the honest fix is a better ranker, not a larger k: raising k to cover a bad retriever buys recall with distractors, and distractors are exactly what the position-sensitivity literature says will hurt you.

    7. Tool schemas and progressive disclosure

    This is the quiet budget killer in MCP-connected agents. Most clients load every connected tool's full JSON schema into the system prompt at session start, before the agent has read a single word of the request. Anthropic's write-up on code execution with MCP reports that tool definitions and tool results can consume more than 50,000 tokens before the agent even begins, and that restructuring the same workload, presenting servers as a filesystem of code APIs the agent explores on demand, and letting intermediate data stay in the sandbox rather than round-tripping through the model, took a benchmark task from roughly 150,000 tokens to about 2,000, a 98.7 percent reduction.

    The same principle ships in a lighter form as a tool search tool: keep the full catalog available, load definitions only for the tools the current step needs. Anthropic reported roughly 85 percent token reduction from that pattern while preserving access to the whole library. Both are instances of progressive disclosure: the catalog stays large, the working set stays small.

    Figure 8Upfront loading versus on-demand discovery
    Upfront, per call
    0
    On demand, per call
    0
    Reduction
    0%
    Saved over 30 turns
    0

    Teal bars are the tools loaded into context. Because the schema block sits in the prefix, this interacts with caching: schemas are stable, so they cache well, and the on-demand pattern trades a perfectly cacheable block for a smaller but more variable one. Measure both before switching, especially at low tool counts where the discovery overhead can dominate.

    A secondary effect is worth naming. When a model must evaluate hundreds of tool options on every request, selection itself consumes capability that would otherwise go to the task. Fewer relevant options in context tends to improve tool-choice accuracy, not just cost.

    8. Serialization format

    The cheapest optimization on this page, because it costs one line of code. JSON repeats every key on every record. For a 200 row result set with 8 fields, that is 1,600 redundant key strings plus punctuation. CSV states the keys once. The saving is mechanical and lossless for flat tabular data.

    Figure 9Serialization cost for a flat result set

    Estimated at roughly four characters per token. Pretty-printed JSON is the default output of most tool wrappers and the worst of the four. Note that this only applies to homogeneous flat records: for nested or sparse data, JSON's structure is carrying real information and flattening it will cost you more in confusion than it saves in tokens.

    Related input-side habits

    Part III

    Shrink the output

    One section, because there are only three levers here. They matter out of proportion to their number, since a generated token costs several times what an input token costs.

    9. The output side

    Constrain length and shape

    An explicit output schema does double duty: it removes the preamble, the restatement of the question and the closing summary, and it makes the response parseable. "Return only the JSON object" is worth more than any prompt-shortening you will do on the input side of a short-prompt workload.

    Emit diffs, not rewrites

    When an agent edits a 900 line file, having it reproduce the whole file costs the full file in output tokens and invites transcription errors. A targeted replacement costs the changed region. This is the single largest output-side saving in coding agents.

    Figure 10Full rewrite versus targeted edit
    Rewrite, output cost
    $0
    Diff, output cost
    $0
    Ratio

    The diff bar includes the anchor context a replacement needs in order to match unambiguously, which is why it does not collapse to nothing at one changed line. Failed matches force a retry, and retries are priced in Figure 15.

    Cap the reasoning budget

    Extended reasoning is billed as output. It earns its cost on genuinely hard problems and wastes it on classification, extraction and routing. Set the budget per task class rather than globally, and measure whether the extra tokens actually move your task metric. On many production workloads they do not.

    Part IV

    Change the architecture

    Five methods that change how many calls you make, how large the model is, or where the work happens. Higher effort, higher ceiling, and two of them can raise your bill on purpose.

    10. Model cascades and routing

    Chen, Zaharia and Zou observed that LLM API prices differ by up to two orders of magnitude, and proposed three strategies to exploit that spread: prompt adaptation, LLM approximation, and the LLM cascade. The cascade sends a query to the cheapest model first and consults a learned scoring function; if the response is judged reliable it is returned, and no further model is queried. Their reported result is that this can match the strongest single model's performance at up to 98 percent lower cost, or beat it by several points of accuracy at equal cost.

    The entire design rests on one component: the deferral signal. If you cannot tell when the cheap model is wrong, the cascade degrades into paying twice for every hard query. Practical signals include token-level confidence, self-consistency across samples, agreement between two cheap models, and a small trained verifier. Later work has extended this in several directions, including preference-trained routers and conformal prediction for probabilistic cost bounds.

    Figure 11Cascade cost and accuracy against the deferral threshold
    Escalation rate
    0%
    Cost vs large only
    0%
    Accuracy
    0%
    Versus large only
    0 pt

    Drop the router quality slider toward 0.4 and watch the useful operating region collapse. With a weak deferral signal there is no threshold that gets you both cheap and accurate, which is the honest reason many cascade projects quietly fail. Build and validate the signal before building the cascade.

    11. Batch prompting

    Distinct from a provider's asynchronous batch API, which changes latency and price but not token count. Batch prompting changes the token count: it puts several work items into a single prompt so the shared prefix, the instructions and the few-shot demonstrations, is paid once instead of once per item. Cheng, Kasai and Yu showed that under few-shot in-context learning the inference cost decreases almost inverse-linearly with the number of samples per batch, and measured up to a 5× reduction in token and time cost with six samples per batch across ten datasets, at comparable or better accuracy.

    The word "almost" is doing work in that sentence, and so is the ceiling. Accuracy degrades as batch size grows, and how fast depends on task complexity: simple classification tolerates large batches, multi-step reasoning does not, because errors on one item bleed into the reasoning for the next. Follow-up work addresses this with batch permutation and ensembling, at the cost of some of the savings.

    Figure 12Per-item cost and accuracy against batch size
    Tokens per item
    0
    Versus one at a time
    Accuracy
    0%
    Efficient batch size
    0

    The efficient batch size marks where the marginal token saving stops paying for the marginal accuracy loss, using a simple exchange rate of one accuracy point per ten percent of cost. Set that exchange rate from your own product, then read the number off the chart. Note also the interaction with prefix caching: if the shared prefix is already cached at a tenth of price, batching has far less left to save, which is why the two are near-substitutes rather than complements.

    Security note

    Batching mixes independent inputs into one prompt, so a malicious item can influence the answers given for its neighbours. This is a documented attack surface, not a theoretical one. Do not batch across trust boundaries, and never batch content from different tenants.

    12. Distillation and fine-tuning

    FrugalGPT calls this LLM approximation, and it is the only method here that removes tokens permanently. Forty few-shot examples in a prompt become weights; the prompt drops to a line of instruction. A smaller fine-tuned model can then replace a larger prompted one for a narrow task, which multiplies the saving by the price ratio.

    The decision is a break-even calculation, not a preference. Fine-tuning has a fixed cost, in data preparation, training and evaluation, and pays back a fixed saving per call. Below the break-even volume it is a waste; above it, nothing else on this page comes close.

    Figure 13Fine-tuning break-even
    Break-even
    0 days
    Saving per call
    $0
    Annual saving
    $0
    Verdict
    -

    Two costs this chart does not show. Fine-tuning freezes behavior, so every prompt change afterwards is a retraining run rather than an edit, and that operational drag is often the real reason teams stay on prompting. And a fine-tuned model on a narrow task can be brittle outside its training distribution in ways a prompted general model is not, so budget for an evaluation set you trust before you budget for the training.

    13. Context isolation and externalized state

    Subagents are the architectural answer to context pollution. A lead agent delegates a bounded subtask to a subagent that has its own window, its own tools and its own instructions; the subagent does the token-heavy exploration and returns a condensed result. The detailed search context stays inside the subagent while the lead agent works only on synthesis. Anthropic's multi-agent research system found that agents with isolated contexts outperformed a single agent on complex research tasks, largely because each subagent's window could be spent entirely on one narrow question.

    The cost this hides

    Multi-agent architectures are not cheap. Anthropic has reported multi-agent research consuming on the order of 15× the tokens of ordinary chat. Isolation buys capability and window headroom, not savings. Reach for it when a single window genuinely cannot hold the task, and reach for compaction or retrieval when it can.

    The related and much cheaper pattern is externalized state. Instead of carrying the plan, the findings and the open questions in the transcript, the agent writes them to a file and re-reads what it needs. A progress file plus version-control checkpoints lets an agent reconstruct where it was after a compaction event without the transcript having carried that state the whole way. And in the programmatic tool-calling pattern, sensitive or bulky intermediate data can move from one system to another without ever entering the model's window at all, which is a privacy property as much as a token one.

    Figure 14Where the tokens flow

    14. The serving layer

    Everything above assumes a hosted API, where the only levers are the tokens you send. If you serve the model yourself, a second set of levers opens up. They do not reduce the token count; they reduce what each token costs you in memory and time, which for a self-hosted deployment is the same conversation.

    The dominant constraint is the KV cache, whose memory grows linearly with sequence length and batch size, and which is the reason long-context serving is expensive rather than merely slow. PagedAttention, the technique behind vLLM, manages that cache in fixed-size blocks like operating-system pages instead of pre-allocating a contiguous region per request, which removes the fragmentation that otherwise wastes most of the allocation and lets many more requests share the same memory. On top of it, automatic prefix caching hashes each block by its contents plus its prefix, so identical system prompts, tool definitions and few-shot blocks are computed once and reused across users. That is the self-hosted equivalent of provider prompt caching, and it is why normalizing your prompts to be block-aligned and byte-identical matters as much here as it does against a hosted API.

    Two further levers: KV cache quantization trades a little precision for roughly half the cache memory, which converts directly into concurrency; and speculative decoding uses a small draft model to propose several tokens that the large model verifies in one pass, accepting all tokens up to the first rejection. Speculative decoding does not change the token count at all, and it does not change quality, but it can substantially cut latency on single-sequence generation.

    Figure 15KV cache memory and what it buys
    Per request
    0 GB
    Concurrent in 60 GB
    0
    With prefix sharing
    0
    Gain

    Memory is two arrays, keys and values, per layer per token. Sixty gigabytes is a rough headroom figure for a large model on one node after weights load; substitute your own. The prefix-sharing bar assumes the shared portion is stored once for the whole pool rather than once per request, which is what block-level hashing gives you. Halving the precision and sharing a system prompt across a pool are each worth more concurrency than most application-level optimizations.

    LeverReducesToken countQuality
    PagedAttention block allocationMemory fragmentationUnchangedUnchanged
    Automatic prefix cachingRecomputation of shared prefixesUnchangedUnchanged
    KV cache quantizationCache memory, roughly by halfUnchangedSmall, measurable degradation
    Weight quantizationWeight memory and bandwidthUnchangedTask-dependent degradation
    Speculative decodingDecode latencyUnchanged, extra draft computeUnchanged by construction
    Continuous batchingIdle GPU time between requestsUnchangedUnchanged

    Note what the third column says throughout. Not one of these is a token optimization. They belong in this monograph because if you self-host, they are usually where the money actually is, and because teams frequently spend a quarter shaving prompt tokens when a serving-config change would have delivered more.

    Part V

    Practice

    Measurement, the costs that hide from measurement, a worked case study, the mistakes that look like optimizations, and the order to do all of it in.

    15. Measure before you optimize

    Almost every pipeline has one or two calls that account for most of the spend, and teams routinely optimize the wrong one. Before touching anything, instrument per-stage token accounting: for every model call, record input tokens, cache read tokens, cache creation tokens, output tokens, and the stage name. Then look at the distribution rather than the total.

    MetricWhat it tells youHealthy direction
    cache_read / total_inputWhether your prefix is actually stableAbove 0.7 in steady-state agent loops
    cache_creation spikesPrompt template drift, or deploys mid-sessionOne per session, not per turn
    tokens per solved taskThe only number that matters end to endFalling, while task success holds
    tool_result / total_inputWhether results need truncation at the tool boundaryBelow 0.4
    output / input ratioWhether you are paying for verbosityTask-dependent, but watch for drift
    p95 context sizeHow close you run to compaction eventsWell under the window
    retry rate by causeHow much of your spend is reworkBelow 0.05, and attributed
    The metric that prevents self-deception

    Optimize tokens per solved task, not tokens per call. A change that halves per-call tokens and doubles the number of retries has made things worse, and per-call accounting will report it as a 50 percent win. Every figure on this page can be gamed by that mistake, which is why the next section exists.

    16. The retry budget

    Rework is the largest unmeasured line item in most agent pipelines. Malformed JSON that fails to parse, a diff whose anchor does not match, a tool call with a bad argument, a schema violation, a timeout: each one throws away a completed call and pays for another. None of it appears in a per-call token dashboard, because every individual call looks normal.

    The arithmetic is unforgiving. If a fraction r of calls must be repeated, effective cost multiplies by roughly 1/(1-r) for single retries, worse when retries themselves fail or when the retry prompt carries the failed attempt and the error as added context, which is the usual pattern. A 12 percent failure rate is a 14 percent cost increase before the added context, and comfortably 20 percent after it. That erases most application-level optimizations on this page.

    Figure 16How rework erases an optimization
    Nominal saving
    0%
    Rework overhead
    0%
    Actual saving
    0%
    Break-even failure rate
    0%

    The break-even figure is the failure rate at which rework exactly consumes the optimization. Below it you are ahead; above it you shipped a regression that your dashboard will report as a win. Constrained decoding or a stricter output schema, which lowers the failure rate, is frequently worth more than any prompt shortening, and it is the one change that makes every other optimization on this page more reliable rather than less.

    17. Worked case study

    A vehicle diagnostic agent. Thirty turns per session, eight connected MCP servers exposing 54 tools, a 4,000 token system prompt, 6,000 tokens of few-shot examples, tool results averaging 3,000 tokens, and 500 output tokens per turn. This is deliberately an ordinary pipeline, not a pathological one.

    Below, the thirteen methods are applied in the recommended order. Each bar is the marginal effect of that method given everything switched on above it, which is the number that matters and the number nobody publishes. Turn steps off and watch the later bars change, because that interference is the point.

    Figure 17Cumulative waterfall over one 30-turn session
    Baseline per session
    0
    Optimized
    0
    Total reduction
    0%
    Cost per session
    $0

    Three things to look for. Turn caching off and every later bar grows, because savings measured against an uncached baseline are inflated. Turn caching on and progressive tool loading shrinks to almost nothing, because it is removing a block that was already costing a tenth of list price. And subagent isolation is a red bar in both configurations: it is on the list because it buys capability, and pretending otherwise is how teams end up surprised by their bill.

    18. Anti-patterns

    Every one of these has been shipped by a competent team, and every one of them reports as a success on a per-call dashboard.

    Shortening a cached system prompt

    Why it is temptingThe system prompt is the biggest single block, so it looks like the obvious target.

    What happensIt was already billing at a tenth of list price, so trimming a thousand tokens saves a hundred tokens' worth of money, and the edit invalidates the cache for every in-flight session. Trim the uncached suffix instead.

    Raising k to cover a weak retriever

    Why it is temptingRecall goes up immediately and the evaluation improves.

    What happensYou buy recall with distractors, push the true passage toward the middle of the context where recall is weakest, and pay for all of it. Fix the ranker.

    Compressing something you could cache

    Why it is temptingA 4× compression ratio sounds better than a discount.

    What happensCaching is a 90 percent discount with zero information loss and no extra inference pass. Compression is lossy and costs a model call. Reserve it for content that changes every request.

    Compacting too early

    Why it is temptingThe context graph flattens and looks healthy.

    What happensEach compaction is a model call that reads the entire window. Compact at 30 percent occupancy and the summarization calls can exceed what the transcript would have cost. Compaction is for approaching the ceiling, not for tidiness.

    Optimizing tokens per call

    Why it is temptingIt is the number the API returns.

    What happensAny change that increases retries or turn count improves it while making the system worse. Only tokens per solved task is safe to optimize against.

    Batching across trust boundaries

    Why it is temptingBigger batches, better amortization, and the items are independent anyway.

    What happensThey are not independent inside one prompt. One item's content can steer the answers given for its neighbours, which is a documented attack, and it also mixes tenants' data in one context.

    Volatile tokens in the prefix

    Why it is temptingPutting the current timestamp or a request ID at the top of the system prompt is one line and feels harmless.

    What happensZero cache hits, forever, while the dashboard shows caching enabled. This is the most common reason a caching rollout shows no saving.

    Progressive tool loading with eight tools

    Why it is temptingThe published reduction figures are enormous.

    What happensThose figures come from catalogs of dozens of servers. With a small catalog the discovery overhead can exceed the schemas you avoided loading, and you have added a failure mode where the agent cannot find a tool it needs.

    Subagents as a cost measure

    Why it is temptingThe lead agent's context gets dramatically smaller.

    What happensTotal tokens go up, substantially. Isolation is a capability and headroom decision. Choose it for what a single window cannot do, not for the bill.

    Semantic caching without a re-ranker

    Why it is temptingEmbedding similarity is one vector search and the hit rate looks great.

    What happensEmbeddings score opposite meanings with similar wording as near neighbours, which is fine for search and not fine when the cached text is served as the answer. Add a cross-encoder check before accepting a hit.

    19. Order of work

    Ranked by expected saving per unit of engineering effort, for a typical hosted-API agentic workload. Figure 2 reorders this for your specific answers.

    #MethodEffortTypical effectRisk
    1Per-stage token accountingLowFinds the real targetNone
    2Prompt caching with a clean prefixLowLarge, on repeated callsNone if the prefix is truly stable
    3Output schema and length constraintsLowModerate, and lowers the retry rateOver-constraining hurts quality
    4Truncate and paginate tool resultsLowLarge in tool-heavy loopsTruncating the needed row
    5Tabular formats over JSONVery lowSmall to moderateWrong for nested data
    6Tool result clearingLowLarge in long sessionsClearing something still needed
    7Retry reduction: constrained decoding, stricter schemasLowOften exceeds every prompt edit combinedNone
    8Progressive tool loadingMediumLarge with many connectorsDiscovery overhead at low tool counts
    9Retrieval and just-in-time loadingMediumLarge, and usually raises accuracyRetriever quality becomes load-bearing
    10Compaction with a tuned promptMediumEnables long horizonsSilent loss of critical detail
    11Diff-based editingMediumLarge in coding agentsFailed matches, retries
    12Semantic cachingMediumVery large where queries repeatWrong or stale answers, cross-user leakage
    13Batch promptingMediumNear inverse-linear per itemAccuracy decay, cross-item interference
    14Extractive compression on variable contentMedium2× to 5× on compressible textLossy, adds an inference pass
    15Model cascadeHighVery large when the signal is goodFails entirely without a good deferral signal
    16Distillation and fine-tuningHighPermanent, largest ceilingFreezes behavior, brittle off-distribution
    17Subagent isolationHighRaises cost, raises capabilityCoordination complexity

    Two further sets sit outside this ranking. Serving-layer levers, in Section 14, apply only if you self-host, where they usually dominate everything above. Learned compression, in Section 5, needs weight access and belongs on the roadmap only when a corpus is stable and hot enough to amortize an offline training run.

    All of the above assumes one agent. If your pipeline is a fleet, Part VI covers the sources that only appear at that scale, and the ranking there differs: the largest lever stops being caching and becomes duplication.

    Two closing observations. First, these compose multiplicatively and interfere: progressive tool loading removes a block that cached beautifully, compaction rewrites a prefix and invalidates the cache, batching competes with caching for the same amortization, and compression on a cacheable region is strictly worse than caching it. Sequence the work and re-measure after each step rather than shipping all seventeen at once, which is exactly what Figure 17 is for. Second, an asynchronous batch API sits outside this ranking too, because it changes price and latency rather than token count, but where a workload tolerates delayed execution it stacks with caching for further savings.

    Part VI

    Multi-agent systems

    Where the token profile changes shape. In a single agent the dominant term is history accumulation, which grows quadratically in turns. In a multi-agent system the dominant term is duplication, which grows multiplicatively in agents times turns, and it usually arrives from a direction nobody is measuring.

    20. The multiplier, and when to pay it

    Start with the number everyone quotes. Anthropic's Research feature uses an orchestrator-worker architecture in which a lead agent plans, spawns three to five subagents that explore in parallel with their own context windows, and synthesizes their findings with a separate citation pass. On their internal research evaluation this beat single-agent Claude Opus 4 by 90.2 percent. It also consumes roughly fifteen times the tokens of ordinary chat, with plain agentic use sitting around four times. Reported alongside that: token usage alone explained about 80 percent of the performance variance on BrowseComp.

    Read those two facts together and the design principle falls out. The multi-agent architecture is not a clever way to get more from the same tokens. It is a way to spend more tokens on a problem than one context window can hold, and the performance follows the spending. So the first question is never how to optimize a multi-agent system. It is whether the task can absorb a fifteen-fold multiplier at all.

    The tasks that can share a shape: breadth-first, with independent branches, where the total information exceeds one window, and where the answer is worth dollars rather than cents. Legal due diligence, competitive intelligence, literature review, broad evidence gathering. The tasks that cannot are the tightly interdependent ones, coding foremost among them, where every branch needs to see what the other branches decided and the coordination cost swamps the parallelism.

    Figure 18Does fan-out earn its multiplier?
    Single agent
    0
    Fan-out
    0
    Quality gain
    0%
    Verdict
    -

    Drag independence down and the fan-out curve collapses, because interdependent branches force the orchestrator to re-broadcast what each subagent learned, and that re-broadcasting is the coordination cost that eats the parallelism. Drag the information-versus-window slider below 1 and fan-out loses on both axes at once: if it fits in one window, a single agent with compaction is cheaper, more coherent, and has no re-contextualization tax at all. A great many production "multi-agent" systems are sequential pipelines wearing a costume, and converting them back to one agent with staged prompts is often a five to ten times saving with an accuracy improvement attached.

    21. Anatomy of a multi-agent session

    Take a concrete system, close to what an internal agent kit looks like in practice: an orchestrator running 10 turns, four subagents at 8 turns each, 25 tools exposed, 40 skills available, tool results averaging 3,000 tokens. That is 42 model calls. Here is where the tokens go, and which of the six sources each belongs to.

    SourceMechanismScales with
    Preamble duplicationEvery agent carries its own copy of the harness prompt, tool schemas and skill instructions, and re-sends all of it every turnagents × turns
    Re-contextualizationThe orchestrator serializes what it knows into a brief; the subagent serializes what it found into a summary. Every boundary crossing is an encode and a decode, paid twicedelegations × 2
    Orchestrator accumulationThe lead agent's window holds every brief it wrote and every result it receiveddelegations squared
    Redundant explorationTwo subagents fetch the same document because neither can see the other's workagents × overlap
    Verification passesJudges, critics, citation agents, self-consistency samplesa deliberate purchase
    Coordination failureA subagent misreads the brief and returns the wrong artifact, so a whole session is discarded and re-delegatedfailure rate × session size

    The decomposition below is the centerpiece of this part. Each fix is a toggle; the stacked bar re-splits as you apply them.

    Figure 19Where the tokens go, and what each fix removes
    Model calls
    0
    Eager baseline
    0
    With fixes applied
    0
    Reduction
    0%

    The finding

    At default settings the skills segment is roughly 54 percent of the session, larger than tool schemas at 19 percent and vastly larger than everything the agents actually say to each other, which is under 1 percent. It is also the least measured line item in any agent framework, because skills are markdown files that nobody counts, while tool schemas at least appear in the API payload as structured objects people think about. If you maintain a kit of dozens of skills, this is where to look first.

    Now switch every fix on and watch what becomes dominant. Agent history, at about two thirds of what remains. Fix the duplication and you are back to the single-agent problem from Part II, which is the correct place to end up: the multi-agent-specific costs are the ones worth attacking first precisely because they are additions on top of a problem you already knew how to solve.

    22. Skills: the hidden budget

    A skill is instructions, and instructions loaded eagerly are indistinguishable from a very long system prompt. The Agent Skills specification addresses this directly with three loading tiers, and understanding the tiers is the whole optimization.

    1. Discovery. At startup the agent loads only the name and description from each skill's YAML frontmatter into the system prompt. One measurement across Anthropic's official skill set put the median discovery cost near 80 tokens per skill, ranging from about 55 to 235, so all 17 together came to roughly 1,700 tokens. An agent can be aware of dozens of skills for less context than a single activated one occupies.
    2. Activation. When the description matches the task, the agent reads the full SKILL.md body into context. In that same measurement, bodies ranged from about 275 to 8,000 tokens with a median near 2,000.
    3. Execution. Bundled reference files and assets are read only if the task touches them, and bundled scripts run without their source entering context at all, so only their output costs anything.

    The description field is doing the load-bearing work, because it is what the agent matches the request against. A vague description under-triggers, which costs you the capability; an over-broad one triggers constantly, which puts you back where you started. Guidance is to say both what the skill does and when to use it.

    Figure 20Skill loading: eager against tiered
    Eager, per call
    0
    Tiered, per call
    0
    Reduction
    0%
    Skills you can afford
    0

    The last figure is the one that changes how you build a kit: it is how many skills fit in the same context budget under each regime. Eager loading caps a useful kit at roughly a dozen; tiered loading makes a hundred cheaper than a dozen eager ones. That is why a large skill library is a good idea only if the loading is tiered, and a liability if it is not.

    Practical rules for skill authoring

    23. The harness, and the cache fragmentation trap

    Every agent needs a preamble: harness rules, output conventions, safety constraints, the shared vocabulary of the system. The instinct when building a kit of twenty-five agents is to give each one a bespoke system prompt tuned to its role. That instinct is correct about quality and expensive in a way that is not obvious.

    Caching is prefix-based, so a bespoke prompt per agent means a separate cache entry per agent. With a fixed number of calls in a session, splitting them across more personas means fewer calls per cache entry, which means the 1.25× write premium is amortized over fewer 0.10× reads. At the limit, one call per persona, you pay the write premium and never collect a single read: caching becomes a pure cost.

    The fix is to move specialization behind the breakpoint. One identical base preamble for every agent, marked as the cached prefix, then a short role block appended after it. You keep the specialization and the whole fleet shares one cache entry. But there is a real crossing point here rather than a universal answer, and the figure finds it.

    Figure 21Bespoke prefixes against a shared prefix with role deltas
    Bespoke prefixes
    0
    Shared plus role delta
    0
    Calls per cache entry
    0
    Better strategy
    -

    The crossing is real and it is worth finding for your own numbers. Push the role block up toward the size of the base and the shared strategy loses, because it pays full price for a large uncached block on every call while the bespoke strategy at least caches the whole thing. The rule that falls out: shared prefix with small role deltas when personas are many and their differences are small, bespoke prefixes when personas are few and genuinely different. If you find yourself with twenty personas whose role blocks are each ten thousand tokens, the real problem is that you have twenty agents where you needed four.

    Other harness-level costs

    24. Communication between agents

    This is the cost with no single-agent analogue. When one agent hands work to another, the context does not move, only a serialization of it does. The orchestrator writes a brief that re-states what the subagent needs to know; the subagent writes a summary that re-states what it found. You pay to encode and again to decode, and information is lost at both ends.

    The loss is what makes this expensive over time, because the natural response to a subagent that misunderstood its brief is to write a longer brief. That works, and it raises the per-delegation cost, and it does not fix the underlying problem, which is that prose is a lossy channel between two systems that could have shared a pointer instead.

    Three topologies

    Figure 22Communication cost by topology
    Full mesh
    0
    Star
    0
    Blackboard
    0
    Orchestrator context
    0

    The orchestrator figure is the one that bites in production, because it grows quadratically in delegations while everyone is watching the linear message count. Note also that the blackboard curve is nearly flat in artifact size: once payloads stop travelling, exchanging a 20,000 token finding costs almost the same as exchanging a 2,000 token one. That is the whole argument for pointer-passing in a single chart.

    Handoff design rules

    1. Return a pointer and an abstract, never the payload. The subagent writes its findings to the store and returns a path plus roughly 200 tokens of what is there. The orchestrator reads the full artifact only if it must.
    2. Use a schema for briefs and results, not prose. Objective, scope, expected artifact type, success criteria, exclusions. Structured handoffs are shorter and, more importantly, they fail loudly instead of silently.
    3. Make briefs specific. Delegation guidance from Anthropic's own system is blunt about this: a vague mandate produces duplicated work and misinterpretation, while a brief that names the sources, the scope and the exact fields to return does not.
    4. Give subagents read access to the store rather than copies of context. If two agents need the same background, they should both read it, not both receive it.
    5. Never re-broadcast. If the orchestrator finds itself forwarding subagent A's findings to subagent B, that is the blackboard asking to be built.

    25. Coordination failure is a token cost

    The most systematic study of this is MAST, a taxonomy built from over 1,600 annotated execution traces across seven popular multi-agent frameworks. It identifies 14 failure modes in three clusters: system design issues, inter-agent misalignment, and task verification failures. Across the analysed frameworks the observed failure rates ranged from roughly 41 percent to nearly 87 percent, and the authors are explicit that better base models alone will not close the gap, because these are architectural failures rather than capability failures.

    Two things follow for token budgets. First, the retry unit in a multi-agent system is enormous. When a single call fails you discard one call; when a subagent misreads its brief you discard an entire session, briefing, exploration, tool calls and all. Second, the failure modes that matter most for cost are the cheap ones to fix: step repetition, unawareness of termination conditions, and misaligned briefs are all addressable with clearer specifications and explicit stop criteria rather than with better models.

    Figure 23The price of a misread brief
    Useful work
    0
    Discarded and redone
    0
    Rework overhead
    0%
    Undetected, in the answer
    0

    The last readout is the uncomfortable one. Failures the orchestrator does not detect cost nothing extra in tokens and corrupt the output instead, which is the worse outcome and the one a cost dashboard will never show you. Raising detection converts silent corruption into visible expense, and that is a trade worth making deliberately rather than by accident.

    26. Verification and fan-out budgets

    Two things in multi-agent systems consume tokens on purpose, and both deserve an explicit exchange rate rather than a default.

    Speculative fan-out means launching several branches and keeping the best. Every discarded branch was paid for in full. It buys accuracy, and the returns diminish roughly logarithmically in branch count while the cost rises linearly, so there is always a point past which it stops paying, and that point is usually lower than teams assume.

    Verification passes, judges, critics, citation agents, self-consistency sampling, are frequently the second largest line item in a multi-agent bill and are almost never measured separately from the work they verify. Isolate them in your accounting. The question to answer is not whether verification helps, it is how many accuracy points per thousand tokens it is currently buying, and whether a cheaper verifier would buy the same.

    Figure 24Fan-out and verification against an explicit exchange rate
    Relative cost
    Accuracy
    0%
    Net value
    0
    Efficient branches
    0

    The exchange rate slider is the honest part of this figure. Every team already has an implicit answer to what an accuracy point is worth; making it explicit is what turns fan-out from a habit into a decision. Set it high, for due diligence or safety-critical review, and wide fan-out with multiple verification passes is correct. Set it low, for internal drafting, and the efficient configuration is one branch and no verifier.

    27. Measuring a multi-agent system

    Single-agent instrumentation does not survive contact with a fan-out architecture, because the totals hide everything interesting. Add these dimensions.

    MetricWhat it exposesHealthy direction
    tokens by roleWhether the orchestrator or the workers dominateWorkers dominant; a heavy orchestrator means accumulation
    preamble / totalThe duplication taxBelow 0.25 once caching and tiering are on
    skill body tokens per callWhether skills are tiered or eagerNear the metadata floor plus one or two bodies
    handoff tokens per delegationRe-contextualization taxFalling; if it rises, briefs are compensating for a design flaw
    orchestrator context growthQuadratic accumulation at the hubFlat, if pointers are being used
    document fetch overlapRedundant exploration across workersBelow 0.15 with a shared store
    discarded subagent sessionsCoordination failure, the largest retry unitBelow 0.05, and attributed to a cause
    verification tokens / totalWhat correctness is costingKnown, and defended by an exchange rate
    tokens per solved taskThe only end-to-end numberFalling while task success holds
    Runaway spend

    The fifteen-fold multiplier compounds when something misbehaves. A subagent that recursively spawns more subagents, or a tool that returns an oversized result into several windows at once, can multiply a single run by another order of magnitude. The published architectures generally describe the happy path and do not include circuit breakers, so build your own: a per-run token ceiling, a maximum delegation depth, a cap on concurrent subagents, and a hard stop on recursive spawning. This is the one item on this page that is a reliability control before it is an optimization.

    28. Order of work, multi-agent

    #ChangeEffortTypical effect
    1Confirm the topology earns its multiplier at allLowSometimes 5× to 10×, by deleting the architecture
    2Tier the skills: metadata at startup, bodies on activationLowUsually the largest single block in a skill-heavy kit
    3One shared cached preamble, role deltas after the breakpointLowLarge, and it stops cache fragmentation dead
    4Circuit breakers: run ceiling, depth cap, spawn limitLowBounds the tail rather than the mean
    5Pointer-and-abstract returns instead of payloadsMediumCuts handoffs and orchestrator accumulation together
    6Progressive tool loading per agentMediumLarge with many connectors, small once caching is on
    7Structured handoff schemasMediumCuts the largest retry unit you have
    8Shared store or blackboardMediumRemoves redundant exploration and re-broadcasting
    9Compaction and notes for the orchestrator specificallyMediumThe hub is usually the least optimized agent
    10Heterogeneous models by roleMediumLarge, given a 10× to 15× price spread
    11Explicit fan-out and verification budgetsMediumTurns a habit into a priced decision

    Two closing notes specific to this part. Item 1 is not a rhetorical flourish: the largest multi-agent optimization available to most teams is discovering that their pipeline is sequential and does not need the topology. And items 2 and 3 interact with each other exactly as Part V's waterfall predicts, because tiering the skills shrinks the very block that the shared cached preamble was making cheap. Apply them in order and re-measure between, rather than reading either one's headline reduction figure and assuming it will survive contact with the other.

    Appendix: the arithmetic behind each figure

    Every calculator on this page uses a simplified model. Here they are, so you can check them, disagree with them, or substitute your own. Rates throughout: base input p_in = $3/M, output p_out = $15/M, cache write 1.25 p_in, cache read 0.10 p_in.

    Figure 3, prompt caching

    uncached(T) = sum over t of (P + (U + O)(t-1)) * p_in + T * O * p_out cached(T) = P * p_in * (1.25 * writes + 0.10 * reads) + sum over t of [ 0.06 * (U+O)(t-1) + U ] * p_in + T * O * p_out writes = 1 + floor(T * inv), reads = T - writes

    The 0.06 factor on history is a stand-in for partial history caching with incremental breakpoints, which real implementations achieve imperfectly.

    Figure 4, semantic caching

    hit(th) = repetition * sigmoid( (0.90 + 0.06*sep - th) * 10 ) false(th) = (1 - repetition) * sigmoid( ((0.92 - 0.22*sep) - th) * 30 ) * 0.30

    Two logistic curves standing in for the overlap between the "genuinely equivalent" and "merely similar" similarity distributions. The slopes differ on purpose, 10 against 30: lowering the threshold buys hit rate gradually and buys false hits fast. Separation is the embedding model's ability to keep the two distributions apart, and it shifts the false-hit curve left rather than flattening it.

    Figure 5, context growth

    naive(t) = base + t * (user + assistant + result) clearing(t)= base + t * (user + assistant) + recent results only compact(t) = reset to base + summary whenever context > 0.70 * window notes(t) = base + t * (user + assistant + pointer)

    Figure 6, compression

    score(w) = 1.6*len(w) - 2.2*freq(w) - 22*[w is a function word] + 4*[w is capitalized] numbers score at the ceiling and are never dropped drop the lowest-scoring floor(ratio * N) words

    A real compressor substitutes a small model's per-token perplexity for this heuristic. The visible behavior is similar; the quality is not.

    Figure 8, tool schemas

    upfront = n_tools * schema_size ondemand = n_tools * 22 + n_used * schema_size + 900

    Twenty-two tokens is a name plus a truncated description; 900 is the discovery instruction block.

    Figure 9, serialization

    json_pretty = R * ( K*(L + V + 10) + 8 ) json_min = R * ( K*(L + V + 6) + 3 ) yaml = R * ( K*(L + V + 5) + 3 ) csv = K*(L+1) + R*( K*(V+1) ) tokens = characters / 4

    Figure 11, cascade

    qq = clamp( (router_quality - 0.5) / 0.5, 0, 1 ) escalated = clamp( qq * err_small * (th/0.7) + (1-qq) * th, 0, 1 ) precision = qq + (1-qq) * err_small caught = min( escalated * precision, err_small ) accuracy = min( 0.98, acc_small + caught * acc_large ) cost = min( 1, (1 + escalated * ratio) / ratio )

    Small model 74 percent accurate, large model 92 percent, cost relative to routing everything to the large model. Accuracy can exceed the large model alone, which is the effect FrugalGPT reported and not an artifact.

    Figure 12, batch prompting

    tokens_per_item = prefix/B + item + response accuracy(B) = acc_1 - decay * ln(B) , clipped at zero decay = 0.002 + 0.038 * task_complexity efficient B = argmax over B of [ cost_saving_pct - 10 * accuracy_loss_pts ]

    Figure 13, fine-tuning break-even

    saving_per_call = removed_tokens * p_in * (1 - 1/model_ratio_factor) break_even_days = fixed_cost / (saving_per_call * calls_per_day)

    Figure 15, KV cache

    bytes_per_token = 2 * layers * kv_heads * head_dim * precision_bytes per_request = bytes_per_token * seq_len concurrency = budget / per_request shared = budget / ( per_request * (1 - shared_fraction) )

    The factor of two is keys plus values. Shared blocks are counted once for the pool rather than once per request, which is what content-addressed block hashing provides.

    Figure 16, retries

    overhead = r * (1 + added_context) / (1 - r) actual_saving = 1 - (1 - nominal) * (1 + overhead) break_even r = value of r where actual_saving = 0

    Figure 17, waterfall

    Each method is a multiplier applied to a named component of the per-session token total, evaluated in list order so that each bar shows the marginal effect given its predecessors. Caching multiplies the prefix component by 0.10 after the first turn, which is why every downstream method that touches the prefix shrinks once caching is enabled. Subagent isolation is a multiplier greater than one on total tokens.

    Figure 18, topology

    single_cost = U * (1 + 0.35 * max(W - 1, 0)) fan_cost(b) = U * (0.55 + 0.95*b) * (1 + (1 - independence) * 0.5 * (b - 1)) fan_quality(b) = 0.62 + 0.33 * (1 - exp(-0.6 * (b-1) * (0.3 + 0.7*independence))) verdict compares value * quality_gain against the extra cost

    W is the ratio of information the task touches to one context window. The coordination penalty on fan_cost is what makes interdependent branches expensive: it grows with branch count and vanishes at full independence.

    Figure 19, multi-agent anatomy

    calls = orchestrator_turns + agents * turns_per_agent preamble = (harness + schemas + skills) * calls * cache_mult skills = K * 1500 eager = K * 80 + 2 * 2000 tiered schemas = O * 850 eager = O * 22 + 3*850 + 900 progressive handoff = (brief + result) * agents orch_accum = sum over orchestrator turns of (brief+result)*(t-1)*0.8 overlap = agents * doc_size * fetches * 0.45 (x0.18 with a shared store) rework = fail_rate * agents * session_size * 0.7

    Figure 20, skill loading

    eager = skills * body_size tiered = skills * metadata_size + triggered * body_size affordable(budget) = how many skills fit in the budget under each regime

    Defaults follow published measurements of Anthropic's official skill set: metadata median near 80 tokens per skill, body median near 2,000.

    Figure 21, harness caching

    calls_per_entry = calls / personas bespoke(p) = (base + role) * calls * (1.25 + 0.10*(calls/p - 1)) / (calls/p) shared(p) = base * calls * (1.25 + 0.10*(calls - 1)) / calls + role * calls

    The crossing exists because bespoke caches the role block and fragments the cache, while shared keeps one cache entry and pays list price for the role block on every call. Which wins depends on the ratio of role size to base size against persona count.

    Figure 22, communication topology

    mesh(n) = n * (n-1) * rounds * artifact star(n) = 2 * n * rounds * artifact blackboard(n) = 2 * n * rounds * pointer orchestrator_context = sum over messages of artifact * 2 * (t-1) * 0.5

    Figure 23, coordination failure

    failed = delegations * fail_rate caught = failed * detection silent = failed - caught wasted = caught * session * 2 + silent * session useful = (delegations - failed) * session

    A caught failure costs twice: the discarded session plus its replacement. A silent one costs once and corrupts the answer.

    Figure 24, fan-out and verification

    accuracy(b,v) = a0 + 0.19*(1 - exp(-0.6*(b-1))) + 0.055*(1 - exp(-0.9*v)) cost(b,v) = b + v * verifier_cost_ratio net(b,v) = accuracy_gain_pts * exchange_rate - extra_cost_pct

    Accuracy is logarithmic in branches and cost is linear, which is why an efficient branch count always exists and is usually smaller than expected.

    References

    1. [1] Liu, N. F., Lin, K., Hewitt, J., Paranjape, A., Bevilacqua, M., Petroni, F., Liang, P. "Lost in the Middle: How Language Models Use Long Contexts." Transactions of the ACL, 12:157-173, 2024. arXiv:2307.03172. arxiv.org/abs/2307.03172
    2. [2] Hong, K., Troynikov, A., Huber, J. "Context Rot: How Increasing Input Tokens Impacts LLM Performance." Chroma Technical Report, July 2025. research.trychroma.com/context-rot
    3. [3] Anthropic. "Effective context engineering for AI agents." Anthropic Engineering. anthropic.com/engineering/effective-context-engineering-for-ai-agents
    4. [4] Anthropic. "Context engineering: memory, compaction, and tool clearing." Claude Cookbook. platform.claude.com/cookbook/tool-use-context-engineering-context-engineering-tools
    5. [5] Anthropic. "Prompt caching." Claude Platform documentation. platform.claude.com/docs/en/build-with-claude/prompt-caching
    6. [6] Anthropic. "Pricing." Claude Platform documentation. platform.claude.com/docs/en/about-claude/pricing
    7. [7] Google Cloud. "Prompt caching" (Vertex AI, Claude partner models). Cache writes 25 percent above base input, cache reads 90 percent below. cloud.google.com/vertex-ai/generative-ai/docs/partner-models/claude/prompt-caching
    8. [8] Bang, F. "GPTCache: An Open-Source Semantic Cache for LLM Applications Enabling Faster Answers and Cost Savings." NLP-OSS 2023, pp. 212-218. aclanthology.org/2023.nlposs-1.24
    9. [9] Biton, D. D., Friedman, R. "From Exact Hits to Close Enough: Semantic Caching for LLM Embeddings." arXiv:2603.03301, 2026. arxiv.org/html/2603.03301v1
    10. [10] Jiang, H., Wu, Q., Lin, C.-Y., Yang, Y., Qiu, L. "LLMLingua: Compressing Prompts for Accelerated Inference of Large Language Models." EMNLP 2023, pp. 13358-13376. arXiv:2310.05736. arxiv.org/abs/2310.05736
    11. [11] Jiang, H., et al. "LongLLMLingua: Accelerating and Enhancing LLMs in Long Context Scenarios via Prompt Compression." arXiv:2310.06839. arxiv.org/pdf/2310.06839
    12. [12] Pan, Z., et al. "LLMLingua-2: Data Distillation for Efficient and Faithful Task-Agnostic Prompt Compression." Findings of the ACL 2024. arXiv:2403.12968. arxiv.org/abs/2403.12968
    13. [13] Microsoft Research. "LLMLingua Series" project page. microsoft.com/en-us/research/project/llmlingua
    14. [14] Mu, J., Li, X. L., Goodman, N. "Learning to Compress Prompts with Gist Tokens." NeurIPS 2023, 36:19327-19352. arXiv:2304.08467. arxiv.org/abs/2304.08467
    15. [15] Eyuboglu, S., Ehrlich, R., Arora, S., Guha, N., Zinsley, D., Liu, E., Tennien, W., Rudra, A., Zou, J., Mirhoseini, A., Re, C. "Cartridges: Lightweight and general-purpose long context representations via self-study." arXiv:2506.06266, 2025. arxiv.org/abs/2506.06266
    16. [16] Ge, T., et al. "In-context Autoencoder for Context Compression in a Large Language Model." arXiv:2307.06945. Contains the comparison of GIST, AutoCompressors and ICAE cited in Section 5. arxiv.org/pdf/2307.06945
    17. [17] Anthropic. "Code execution with MCP: Building more efficient agents." November 2025. Reports 150,000 to 2,000 tokens on a benchmark task. Summarized in: MCP.Directory, "MCP Context Bloat Fix 2026." mcp.directory/blog/mcp-context-bloat-fix-2026
    18. [18] Kruczek, M. "Progressive Disclosure MCP: Token Savings Benchmark." January 2026. matthewkruczek.ai/blog/progressive-disclosure-mcp-servers.html
    19. [19] Wire. "Progressive tool loading is the new MCP context pattern." May 2026. usewire.io/blog/progressive-tool-loading-mcp-context-pattern
    20. [20] Chen, L., Zaharia, M., Zou, J. "FrugalGPT: How to Use Large Language Models While Reducing Cost and Improving Performance." arXiv:2305.05176, 2023. arxiv.org/abs/2305.05176
    21. [21] Cheng, Z., Kasai, J., Yu, T. "Batch Prompting: Efficient Inference with Large Language Model APIs." EMNLP 2023 Industry Track. arXiv:2301.08721. arxiv.org/abs/2301.08721
    22. [22] "Efficient but Vulnerable: Benchmarking and Defending LLM Batch Prompting Attack." arXiv:2503.15551, 2025. Source for the batching security caveat. arxiv.org/html/2503.15551
    23. [23] Kwon, W., Li, Z., Zhuang, S., Sheng, Y., Yu, C. H., Gonzalez, J. E., Zhang, H., Stoica, I. "Efficient Memory Management for Large Language Model Serving with PagedAttention." arXiv:2309.06180, 2023. arxiv.org/abs/2309.06180
    24. [24] vLLM. "Automatic Prefix Caching" design documentation. docs.vllm.ai/en/v0.9.0/design/automatic_prefix_caching.html
    25. [25] vLLM. "Inside vLLM: Anatomy of a High-Throughput LLM Inference System." September 2025. Covers PagedAttention, continuous batching, prefix caching and speculative decoding. vllm.ai/blog/2025-09-05-anatomy-of-vllm
    26. [26] Chen, C., Borgeaud, S., et al. "Accelerating Large Language Model Decoding with Speculative Sampling." arXiv:2302.01318. arxiv.org/abs/2302.01318
    27. [27] LangChain. "Context Engineering for Agents." Covers scratchpads, summarization and subagent context isolation, including the reported 15× token multiple for multi-agent research. langchain.com/blog/context-engineering-for-agents
    28. [28] Anthropic. "How we built our multi-agent research system." Anthropic Engineering, June 2025. Orchestrator-worker architecture, the 90.2 percent improvement over single-agent Opus 4, and the approximately 15× token multiple over chat. anthropic.com/engineering/multi-agent-research-system
    29. [29] ZenML LLMOps Database. "Building Production Multi-Agent Research Systems with Claude." Summary of the above, including token usage explaining roughly 80 percent of performance variance. zenml.io/llmops-database/building-production-multi-agent-research-systems-with-claude
    30. [30] Anthropic. "Agent Skills" overview. Claude Platform documentation. Three-tier progressive disclosure: frontmatter metadata at startup, SKILL.md body on activation, bundled files on demand. platform.claude.com/docs/en/agents-and-tools/agent-skills/overview
    31. [31] SwirlAI. "Agent Skills: Progressive Disclosure as a System Design Pattern." Token measurements across Anthropic's official skill set: median discovery cost near 80 tokens per skill, body median near 2,000. newsletter.swirlai.com/p/agent-skills-progressive-disclosure
    32. [32] Cemri, M., Pan, M. Z., Yang, S., Agrawal, L. A., Chopra, B., Tiwari, R., Keutzer, K., Parameswaran, A., Klein, D., Ramchandran, K., Zaharia, M., Gonzalez, J. E., Stoica, I. "Why Do Multi-Agent LLM Systems Fail?" NeurIPS 2025 Datasets and Benchmarks. MAST taxonomy, 14 failure modes in three clusters over 1,600+ traces from 7 frameworks. arXiv:2503.13657. arxiv.org/abs/2503.13657
    33. [33] Sourcegraph. "Context Engineering: A Practical Guide for AI Agents." May 2026. Just-in-time retrieval and memory compaction in production systems. sourcegraph.com/blog/context-engineering