11B.2 Tokenomics: The Unit Economics of LLM Applications

ProductionLesson 2 of 87,057 words10 parts
Module 11B · 0 of 8 lessons done
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8

Lesson 11B.1 gave you the cost model for one request and a playbook for cutting it. Lesson 03.7 taught you to compute an exact bill from a usage object. This lesson steps back: why are tokens priced the way they are, how does cost scale as a product grows, what do real products charge and earn, and when does it make sense to switch model, tier, or hosting? That is tokenomics: the unit economics of a product whose cost of goods is a meter.

What you'll learn

  • The billing categories of a token (fresh input, output, cache write, cache read, reasoning, image, audio) and why output costs 4 to 6 times input
  • A cross-provider price map for November 2026 with the modifiers that move it: batch, flex, fast, long context, data residency, tokenizer changes
  • The price-per-capability trend, and the counter-trends that keep your bill from falling as fast as the headline
  • Why agent cost grows quadratically with turns, the algebra, and what caching and compaction each change
  • Unit economics at product level: cost per request, conversation, task, outcome and user; a short view of pricing models (the full treatment is 13A.6); the heavy-user problem; what is known and unknown about margins
  • Self-hosting break-even with a formula and a worked check
  • The tokenizer tax: why the same text costs different amounts across models and languages
  • Four worked examples (RAG chatbot, support agent, nightly batch job, coding agent) from a runnable calculator, with a decision table and a FinOps checklist

What you don't need

  • API keys. The calculator is pure Python; every price comes from a provider page read on 20 November 2026.
  • The per-call cost code (03.7) or the full optimisation loop (11B.1). This lesson links to them.

Setup

Python 3.11+ and the standard library only. Save the sample as tokenomics.py and run it with python tokenomics.py.

bash
uv init tokenomics --bare --python 3.13 && cd tokenomics
# nothing to install: the sample uses only the standard library

Read prices as dated facts. List prices change monthly, several providers have announced scheduled changes, and the OpenAI and Google pages were read through a summarising fetch tool. Treat every number as "as of 20 November 2026 and worth re-checking", and put prices in configuration, never in code you ship.


What you must be able to do after this lesson#

  • Name the billing categories of a token and explain why output costs more than input
  • Read the November 2026 price map and apply the batch, cache and long-context modifiers
  • Write the agent-loop input formula and say which term grows quadratically
  • Compute cost per request, per task and per outcome with the calculator
  • Compare per-seat, usage-based and outcome-based pricing for an agent product
  • Decide whether self-hosting pays using the utilisation break-even
  • Estimate the tokenizer premium for a given language or model

Why this matters for an AI engineer#

Situation What you need from this lesson
A prototype that cost $20 to build costs $40,000 a month at launch Per-request cost times volume, and which levers move it
An agent that "works" costs ten times what the demo suggested The quadratic term and the cached-versus-uncached curves
Finance asks for a price per customer Unit definitions and pricing models
You are choosing between a frontier model and a small one The price spread, the routing lever, and the eval caveat
Someone proposes self-hosting to save money The break-even formula and the utilisation reality

Common questions this lesson answers#

Question Where
"What am I actually paying for?" Part 1
"What do the major providers charge?" Part 2
"Are prices really falling?" Part 3
"Why did my agent's bill explode?" Part 4
"How do products price and earn?" Part 5
"What should I optimise first?" Part 6
"Should I self-host?" Part 8

Part 1: What a token costs, and why#

1.1 The billing categories#

Category How it is billed
Fresh input Base input price
Output Typically 4 to 6 times the input price
Cache write A premium over input (Anthropic: 1.25x for a 5-minute entry, 2x for 1 hour)
Cache read A discount (Anthropic 0.1x by default, 0.05x on Opus 5.5 and Sonnet 5.5, 0.025x on Fable 5.1 and 5.2; OpenAI 10 to 50% of input depending on model)
Reasoning or thinking Billed as output
Images Tokens, by size (Part 1.4)
Audio Tokens, often at a higher rate than text
Server tools For example Anthropic web search: $10 per 1,000 searches plus the tokens the results add to later turns

Never hard-code "caching is 90% off": the discount differs by provider, model and generation (OpenAI's cached-input rate has been 10% of input on the newest models, 25% on GPT-4.1 and 50% on GPT-4o), Anthropic's read multiplier has fallen on newer models, and Gemini adds a storage fee per hour on explicit caches. 11B.4 Part 4 has the provider-by-provider rules and 11B.3 the strategy.

1.2 Why output costs more#

Generation has two phases. Prefill processes every prompt token in one parallel pass and is limited by compute. Decode produces one token per forward pass, and each pass must stream the model's weights and the KV cache from memory, so it is limited by memory bandwidth and leaves compute idle. Each output token therefore uses the hardware less efficiently than each input token. (This explanation is consistent across technical write-ups, but this lesson's research did not confirm it against a vendor document; the price ratios below are the hard evidence.)

Output/input list-price ratios computed from the pages read on 20 November 2026:

Model Input / output per 1M Ratio
Claude Sonnet 5.5 $2 / $10 5x
Claude Opus 5.5 $4 / $20 5x
Claude Fable 5.2 $8 / $40 5x
Claude Haiku 5.5 $0.10 / $0.50 5x
GPT-5.5 $5 / $30 6x
GPT-6.2-Sol $2 / $10 5x
GPT-5-mini $0.25 / $2 8x
GPT-4.1 $2 / $8 4x
Gemini 3.1 Pro (up to 200k) $2 / $12 6x
gpt-oss-120B on Together $0.15 / $0.60 4x
GLM-5.3 on Together $1.40 / $4.40 about 3.1x

The typical range is 4 to 6 times, with outliers at 3x and 8x. The consequence for design: shortening an answer by 100 tokens saves as much as shortening the prompt by 400 to 600.

1.3 Reasoning tokens: paying for what you cannot see#

  • Anthropic: thinking tokens are billed as output, and the billed count is the full internal thinking, not the shorter summary you see. Choosing to display or omit the summary changes only what you see. usage.output_tokens_details.thinking_tokens reports the reasoning share, and output_tokens is the inclusive billing total. On newer models there is no explicit thinking budget; you steer with output_config.effort and max_tokens. Note that max_tokens is per request, "so it doesn't bound the whole turn's spend" in a tool loop. Thinking blocks from earlier turns that stay in context are billed as input tokens on models that keep them.
  • OpenAI: reasoning tokens "are billed as output tokens", are not visible, still occupy context, and are reported in output_tokens_details.reasoning_tokens. The guide recommends reserving at least 25,000 tokens for reasoning and output, and warns you can pay for input and reasoning without receiving a visible answer if the limit is hit.
  • Gemini: the output price is labelled "incl. thinking".

The invisible-token rule: log reasoning tokens per request, or you cannot explain a bill. Reasoning effort is a cost dial (02.8).

1.4 Image and audio tokens#

  • Anthropic images: visual tokens = ceil(width / 28) × ceil(height / 28), capped per tier. A 1000×1000 image is 1,296 tokens; a 1920×1080 image is 1,560 on the standard tier and 2,691 on the high-resolution tier available on 4.7 and later models; a 4K image is 1,560 versus 4,784. By Anthropic's own examples, a 1000×1000 image on a $1-per-million model is about $1.30 per 1,000 images, and the same image on Opus 5.5 high-resolution about $5.18 per 1,000. The same picture can cost up to about three times more tokens on the high-resolution tier.
  • Gemini: images up to 384 pixels in both dimensions are 258 tokens, larger images are tiled at 258 tokens per 768-pixel tile, and audio is 32 tokens per second. (Gemini's video rate is inconsistent on the page read, so it is not quoted here.)
  • Audio premium: audio is priced above text. Gemini 3.1 Flash-Lite is $0.25 per million for text, image and video input and $0.50 for audio. OpenAI's gpt-realtime-2 lists audio input at $32 and output at $64 per million against $4 and $24 for text, so audio input costs 8 times text input and audio output about 2.7 times text output. Transcription is billed per minute (gpt-4o-transcribe $0.006 per minute).

Part 2: The price map, November 2026#

Reference

All prices are USD per million tokens, read from the providers' pages on 20 November 2026.

2.1 Price tiers#

Tier Examples (input / output)
Small Haiku 5.5 $0.10 / $0.50; gpt-6-luna $0.10 / $0.50; gpt-5-nano $0.05 / $0.40; Gemini 3.1 Flash-Lite $0.25 / $1.50; Gemini 2.5 Flash-Lite $0.10 / $0.40
Workhorse Sonnet 5.5 $2 / $10; gpt-6.2-sol $2 / $10; gpt-5.4 $2.50 / $15; Gemini 4 Hydrogen $1.50 / $7.50; Gemini 3.1 Pro $2 / $12
Frontier Opus 5.5 $4 / $20; gpt-5.5 $5 / $30; gpt-6.2-astra $8 / $40; Fable 5.2 $8 / $40; Gemini 4 Neon $3 / $15
Premium compute gpt-5.5-pro $30 / $180 (6 times gpt-5.5)

The spread from the most expensive frontier output ($40 on Fable 5.2 or gpt-6.2-astra) to the cheapest small-model output ($0.50) is about 80 times. That spread is the headroom for routing. Open-weight models on hosts such as Together are priced in the same band as the small proprietary tier (output $0.25 to $0.60 for models like gpt-oss-120B or Qwen3.5 9B), which is about 17 to 40 times below Sonnet 5.5 output. Whether the capability gap matters is an eval question, not a price one.

2.2 Anthropic#

Model Input 5-min write 1-h write Cache read Output
Fable 5.2 $8 $10 $16 $0.20 $40
Opus 5.5 $4 $5 $8 $0.20 $20
Opus 5 / 4.8 / 4.7 / 4.6 / 4.5 $5 $6.25 $10 $0.50 $25
Sonnet 5.5 $2 $2.50 $4 $0.10 $10
Sonnet 4.6 / 4.5 $3 $3.75 $6 $0.30 $15
Haiku 5.5 (prompts up to 100k tokens) $0.10 $0.125 $0.20 $0.01 $0.50
Haiku 4.5 $1 $1.25 $2 $0.10 $5

Notes: Haiku 5.5 charges more for prompts over 100,000 tokens (five times input and output) and counts cache reads and writes toward that threshold. Claude 4.6 and later models other than Haiku 5.5 include the full 1M-token window at the standard rate: "a 900k-token request is billed at the same per-token rate as a 9k-token request."

2.3 OpenAI#

Cells are input / cached input / output.

Model Standard Batch Fast (formerly Priority)
gpt-6.2-astra 8 / 0.40 / 40 4 / 0.20 / 20 16 / 0.80 / 80
gpt-6.2-sol 2 / 0.10 / 10 1 / 0.05 / 5 4 / 0.20 / 20
gpt-6-luna 0.10 / 0.01 / 0.50 0.05 / 0.005 / 0.25 0.20 / 0.02 / 1
gpt-5.5 5 / 0.50 / 30 2.50 / 0.25 / 15 12.50 / 1.25 / 75
gpt-5.4 2.50 / 0.25 / 15 1.25 / 0.13 / 7.50 5 / 0.50 / 30
gpt-4.1 2 / 0.50 / 8 1 / n/a / 4 3.50 / 0.875 / 14
gpt-4o 2.50 / 1.25 / 10 1.25 / n/a / 5 4.25 / 2.125 / 17

2.4 Google Gemini (Standard tier, input / output including thinking / cache read)#

Model Input Output Cache read
Gemini 4 Carbon / Argon $2 (then $4 from 1 Dec 2026) $10 (then $20) $0.10 (then $0.20)
Gemini 4 Neon $3 $15 $0.15
Gemini 4 Hydrogen $1.50 $7.50 $0.075
Gemini 3.8 / 3.6 Flash $0.75 (then $1.50 from 1 Jan 2027) $3.75 (then $7.50) $0.075
Gemini 3.1 Pro Preview $2 (up to 200k) / $4 $12 / $18 $0.20 / $0.40
Gemini 3.1 Flash-Lite $0.25 ($0.50 audio) $1.50 $0.025
Gemini 2.5 Flash-Lite $0.10 $0.40 $0.01

The scheduled doublings above are on Google's own page, so the price trend is not monotone. Also note that Gemini 2.5 Pro and Flash route to newer models from 1 December 2026: deprecation is a cost event.

2.5 The modifiers#

Modifier Effect
Batch 50% off input and output on all three providers; asynchronous; Anthropic's batch discount stacks with caching and residency; fast mode is not available with batch
Flex (OpenAI, Gemini) About the batch price for slower synchronous-style requests on models that offer it
Fast / Priority Pay more for speed: 2x on Anthropic's fast mode and most OpenAI models, 2.5x on gpt-5.5, 1.8x on Gemini
Long context OpenAI over 272k input tokens: 2x input and 1.5x output on gpt-5.5; Gemini 3.1 Pro over 200k: 2x input, 1.5x output; Haiku 5.5 over 100k: 5x
Data residency Anthropic inference_geo: "us": 1.1x on all token categories for Claude 4.6 and later; OpenAI regional endpoints: +10% on models released on or after 5 March 2026
Tokenizer Claude 4.7 and later use a tokenizer that produces "approximately 30%" more tokens for the same text (content-dependent)
Background discount (OpenAI) 30% below standard for a 2-hour window or 40% for 8 hours on four listed models
Web search, tools Per-call fees plus token costs

Two lessons from the tokenizer row. First, a flat per-token price cut can hide a rise: Opus 4.5 at $5 / $25 to Opus 5.5 at $4 / $20 is a 20% price cut, but with about 30% more tokens per text the net is about +4% (0.8 × 1.3 = 1.04, content-dependent, my arithmetic). Second, always re-count tokens with the new model's counter (03.7).


Deep-dive

3.1 The headline: fixed capability gets cheaper fast#

  • a16z, "Welcome to LLMflation" (12 November 2024): "For an LLM of equivalent performance, the cost is decreasing by 10x every year." The cited example: GPT-3 in November 2021 was the only model reaching MMLU 42 at $60 per million tokens; Llama 3.2 3B on Together reached the same score at $0.06, a factor of 1,000 in three years. The author listed the drivers as GPU performance per dollar, quantisation (16 to 4 bit), software optimisation, smaller models trained on more tokens, better instruction tuning and open-source competition, and noted the rate might slow.
  • Epoch AI (12 March 2025): the price to reach GPT-4-level performance on a PhD-level science benchmark (GPQA Diamond) fell about 40 times per year, with a range across benchmarks and thresholds of 9 to 900 times per year. The fastest declines were in the most recent year, and Epoch noted it was "less clear that those will persist". Their data points: GPT-4-0314 at a blended $37.50 per million tokens against Gemini 2.0 Flash at $0.18, which scored 88.0 on MMLU versus 86.0, roughly a 208-fold drop in about two years (37.50 / 0.18).
  • A later Epoch analysis reported by secondary summaries puts the decline at about 13 times per year for a high GPQA threshold. This was not verified against Epoch's pages.
  1. The price of the best model is roughly flat. Fable 5.2 at $8 / $40 and Opus-class at $4 to $5 / $20 to $25 are not far from GPT-4-0314's launch price of $30 / $60. What collapsed is the price of a fixed capability.
  2. Same-tier cuts within a vendor are real. Opus 4.1 at $15 / $75 became Opus 4.5 at $5 / $25 and Opus 5.5 at $4 / $20, about 3.75 times cheaper on both sides. Sonnet went from $3 / $15 to $2 / $10, and the small tier from Haiku 4.5 at $1 / $5 to Haiku 5.5 at $0.10 / $0.50, a 10-fold cut.
  3. Reasoning models emit more tokens per task, so cost per task falls more slowly than cost per token. (One secondary source; the direction follows from Part 1.3.)
  4. Tokenizer changes (about 30% on Claude 4.7 and later).
  5. Scheduled increases (Gemini above) and deprecations.
  6. Agents re-read context (Part 4), which multiplies tokens faster than price falls for long-running work.

The planning rule: assume the price of a fixed capability keeps falling, do not assume your bill does, and keep prices and model names in configuration so a change is a deploy, not a rewrite.


Part 4: How cost grows: the agent loop#

4.1 The algebra#

The API is stateless: every model call re-sends the whole transcript. Let the fixed prefix (system prompt, tool definitions, task) be S tokens, and each step add a tokens (tool result plus assistant output). Input at step t is S + (t−1)a, so over N steps:

text
total input tokens = N·S + a·N(N−1)/2

The second term is quadratic in N. With S = 3,200, a = 750 and N = 20, that is 64,000 + 142,500 = 206,500 input tokens, of which only 17,450 (8.5%) are new; the rest is re-reading. Doubling N to 40 multiplies input tokens by 3.45, not 2.

4.2 What each lever changes#

  • Caching does not remove the quadratic token count. It changes the price coefficient of the re-read, from 1x to 0.1x (0.05x on Sonnet 5.5), so the quadratic term is cheap but still there.
  • Compaction, summarising and clearing old tool results change the number of tokens, bending the growth towards linear. Sub-agents with isolated contexts do the same (08A.4).
  • After caching, the shape of the bill flips. In the cached 20-turn run below, output is about 32% of the cost, cache writes about 47%, reads about 20%: it is no longer input-dominated.

A worked agent run in dollars (a 9-step support agent) is 11B.1, 1.6, and 11B.8, Part 1 has the agent-cost calculator and the p95 tail.

4.3 Gotchas#

A user who pauses longer than the 5-minute TTL pays a full re-write of the whole context, and changing effort or thinking settings mid-conversation can invalidate cache breakpoints (11B.4, 2.5 and 5.2 list the causes). The cost is large at long contexts: at 100,000 tokens, one cold miss on Sonnet 5.5 costs 100,000 × $2.50 / 1M = $0.25 against $0.01 as a read, 25 times more.


Part 5: Unit economics and pricing models#

5.1 Choose the unit#

The unit is the thing one cost number is divided by: a request, conversation, task or ticket, resolved outcome, or active user per month. Pick the one that matches how you charge, and compute percentiles as well as averages, because the cost distribution is fat-tailed. You will meet the full treatment, including the cost-per-successful-task formula and a calculator, in 13A.6, 6.1 and 6.2, later in the path.

A real anchor: Anthropic's Claude Code documentation reports that across enterprise deployments the average is about $13 per developer per active day and $150 to $250 per developer per month, with 90% of users below $30 per active day (list-price estimates). The same page explains the climb: the whole conversation is re-sent on every request, each tool use is another request, a cache miss after the TTL reprocesses the context, sub-agents add parallel contexts, and compaction is itself a large request. Its advice, in order: clear between tasks, pick the right model (Sonnet for most work, Haiku for sub-agents), trim tool definitions, filter hook output (a 10,000-line log reduced to a few hundred tokens), lower effort, delegate verbose operations to sub-agents.

5.2 Pricing models#

There are four common models, and the cost risk differs for each:

  • Per seat: a fixed monthly fee. The cost risk is unbounded cost per heavy user.
  • Usage-based: pass tokens or credits through. Revenue tracks cost, but it is harder to sell.
  • Outcome-based (a per-outcome price: charge per successful result, for example a resolved conversation): the cost of unresolved conversations is yours.
  • Hybrid: seat plus an included allowance plus overage, with rolling usage windows. It needs good metering.

The full comparison (best use and the trap of each, tiered and freemium pricing, and the outcome-definition warning) is in 13A.6, 6.4, later in the path. Two dated price points stay here (as of November 2026) because 13A.6 lacks them: Intercom seats at $29 list for Essential ($19 for new customers), $85 and $132 per seat per month (annual billing); and the exact rules of Intercom's Fin AI Agent at $0.99 per outcome (resolved, or the customer does not ask for more, or a workflow completes), with no charge if it cannot answer, an action fails or the customer asks for a human, and at most once per conversation.

Tie an outcome price to token cost. At $0.99 per outcome, the 20-turn support agent below costs $0.0925 per conversation cached (9.3% of revenue) or $0.443 uncached (45%), before retrieval, hosting and human escalation. If only half of the conversations resolve, cost per outcome doubles, so the margin depends on the resolution rate. (Derived, illustrative.)

5.3 The heavy-user problem#

A flat price on a variable-cost resource has a fat tail of cost. Anthropic announced weekly limits for Claude Code in July 2025, reportedly after some subscribers ran it continuously and one user consumed "tens of thousands" of dollars of usage on a $200 plan, expected to affect under 5% of subscribers. This comes from news coverage; the primary post was not read for this lesson. The standard defences: usage windows, spend caps at organisation, group and member level, an included allowance with credits beyond it, cheaper models for sub-agents, and metering.

5.4 Margins: what is known and what is not#

Be careful here. No audited gross margins have been published for the coding-assistant companies, and reports conflict. Everything in this paragraph is reported or estimated and unverified: Cursor was reported at about −23% gross margin for the quarter ending January 2026 and slightly positive by April 2026 after routing most requests to an in-house model; Replit reports ranged from about 23% to negative, with its CEO saying in 2026 it had been margin-positive for over a year; Lovable was estimated near 35% for 2025; one survey summary put the average AI product at about 45% gross margin for 2025, rising towards 59% by 2027; analysts computed about 85% for Anthropic from an S-1 cost-of-revenue line, but the filing does not report a gross margin and the figure excludes training compute. The safe teaching statement: AI application gross margins sit below classic software because cost of goods scales with usage, and the spread between companies is driven by routing to cheaper or own models, caching and pricing model. Estimates of inference cost as a share of revenue range from 40% to above 100% for coding tools.


Part 6: The levers, ranked#

The full playbook is 11B.1, Part 4: each lever with what it costs you, when it wins and a decision table. Measure your own waste first (11B.1, Part 3) before acting. The list below is only a one-line reminder, ranked by the usual size of the effect (a synthesis), with the price figures from this lesson.

  1. Model choice and routing is usually the biggest: about 80 times between the dearest frontier and the cheapest small output price, 20 times between Sonnet 5.5 and Haiku 5.5 (Part 2). It needs an eval-verified router (11B.5); Cursor reportedly routes about 80% of requests to an in-house model (unverified).
  2. Context hygiene in agents bends the quadratic term (Part 4): compaction, clearing tool results, sub-agents, deferred tool definitions.
  3. Caching reads at 0.1x or less; in the worked example the 20-turn agent is 4.8 times cheaper (Part 7).
  4. Batch and flex take 50% off for work that can wait.
  5. Output length and reasoning effort: output is 4 to 6 times input, and thinking is output.
  6. Prompt and retrieval size is linear in input and matters most on uncached single-shot calls.
  7. Distillation and fine-tuning is a qualitative lever (a small model trained on a larger model's outputs), not quantified here.
  8. Avoid long-context thresholds (2x to 5x above the line: OpenAI over 272k, Gemini over 200k, Haiku 5.5 over 100k), then region and residency (+10%, only where required), then self-hosting (Part 8).

Part 7: Worked examples#

The calculator below encodes the prices from Part 2 and the shapes in each example. The workload shapes are assumptions for illustration, not measurements; replace them with your own logs.

7.1 tokenomics.py#

python
"""tokenomics.py - unit economics of LLM workloads. Prices: USD per 1M tokens, list prices checked 2026-11-20."""
from dataclasses import dataclass

@dataclass(frozen=True)
class Price:
    inp: float; cache_write: float; cache_read: float; out: float

SONNET = Price(2.00, 2.50, 0.10, 10.0)     # Claude Sonnet 5.5
HAIKU = Price(0.10, 0.125, 0.01, 0.50)     # Claude Haiku 5.5, prompts <= 100k tokens
OPUS = Price(4.00, 5.00, 0.20, 20.0)       # Claude Opus 5.5

def cost(p, fresh=0, write=0, read=0, out=0):
    return (fresh * p.inp + write * p.cache_write + read * p.cache_read + out * p.out) / 1e6

def agent_run(p, turns, system=3000, user=200, add=750, out=150, cache=True):
    """Stateless API: every turn re-sends the whole transcript. Cached: only the new increment is written."""
    total, ctx, prev = 0.0, system + user, 0
    for _ in range(turns):
        total += cost(p, write=ctx - prev, read=prev, out=out) if cache else cost(p, fresh=ctx, out=out)
        prev, ctx = ctx, ctx + add
    return total

def input_tokens(turns, system=3000, user=200, add=750):
    return sum(system + user + t * add for t in range(turns))

if __name__ == "__main__":
    print("== RAG chatbot, per request (6,000 input, 400 output)")
    base = cost(SONNET, fresh=6000, out=400)
    steps = [("baseline", base),
             ("cache 1,000-token system prompt", cost(SONNET, fresh=5000, read=1000, out=400)),
             ("+ retrieval 4,000->2,500, output cap 300", cost(SONNET, fresh=3500, read=1000, out=300))]
    haiku = cost(HAIKU, fresh=3500, read=1000, out=300)
    steps.append(("+ route 70% to Haiku", 0.7 * haiku + 0.3 * steps[-1][1]))
    for name, c in steps:
        print(f"{name:<44} ${c:.5f}/request  ${c * 100_000:>7,.0f}/month at 100k requests  ({c / base:4.0%} of baseline)")

    print("\n== Support agent: cost per conversation by number of tool turns (Sonnet 5.5)")
    print(f"{'turns':>5} {'input tokens':>13} {'uncached':>10} {'cached':>9}")
    for n in (10, 20, 40, 80):
        print(f"{n:>5} {input_tokens(n):>13,} ${agent_run(SONNET, n, cache=False):>8.4f} ${agent_run(SONNET, n):>8.4f}")
    n20, n40 = input_tokens(20), input_tokens(40)
    new = 3200 + 19 * 750
    print(f"20 turns: {new:,} of {n20:,} input tokens are new ({new / n20:.1%}); doubling turns raises input tokens {n40 / n20:.2f}x")

    print("\n== Nightly batch: 200,000 documents x (800 in, 20 out), 30 nights")
    for name, p, mult in [("Haiku 5.5 sync", HAIKU, 1), ("Haiku 5.5 batch (50%)", HAIKU, .5),
                          ("Sonnet 5.5 sync", SONNET, 1), ("Sonnet 5.5 batch (50%)", SONNET, .5)]:
        per = cost(p, fresh=800, out=20) * mult
        print(f"{name:<24} ${per:.6f}/doc  ${per * 200_000:>8,.2f}/night  ${per * 200_000 * 30:>9,.0f}/month")

    print("\n== Self-hosting break-even: tokens/s needed = (GPU $/hr / API $ per Mtok) x 1e6 / 3600")
    api_blend = (8000 * 0.15 + 1000 * 0.60) / 9000      # gpt-oss-120B on Together, 8k in / 1k out
    for gpu, hr in [("H100 dedicated, Together", 5.49), ("H100, Lambda", 4.29)]:
        tps = hr / api_blend * 1e6 / 3600
        print(f"{gpu:<26} API blend ${api_blend:.3f}/Mtok -> needs {tps:,.0f} tokens/s sustained, 24/7")

Real output:

text
== RAG chatbot, per request (6,000 input, 400 output)
baseline                                     $0.01600/request  $  1,600/month at 100k requests  (100% of baseline)
cache 1,000-token system prompt              $0.01410/request  $  1,410/month at 100k requests  ( 88% of baseline)
+ retrieval 4,000->2,500, output cap 300     $0.01010/request  $  1,010/month at 100k requests  ( 63% of baseline)
+ route 70% to Haiku                         $0.00339/request  $    339/month at 100k requests  ( 21% of baseline)

== Support agent: cost per conversation by number of tool turns (Sonnet 5.5)
turns  input tokens   uncached    cached
   10         65,750 $  0.1465 $  0.0455
   20        206,500 $  0.4430 $  0.0925
   40        713,000 $  1.4860 $  0.2092
   80      2,626,000 $  5.3720 $  0.5325
20 turns: 17,450 of 206,500 input tokens are new (8.5%); doubling turns raises input tokens 3.45x

== Nightly batch: 200,000 documents x (800 in, 20 out), 30 nights
Haiku 5.5 sync           $0.000090/doc  $   18.00/night  $      540/month
Haiku 5.5 batch (50%)    $0.000045/doc  $    9.00/night  $      270/month
Sonnet 5.5 sync          $0.001800/doc  $  360.00/night  $   10,800/month
Sonnet 5.5 batch (50%)   $0.000900/doc  $  180.00/night  $    5,400/month

== Self-hosting break-even: tokens/s needed = (GPU $/hr / API $ per Mtok) x 1e6 / 3600
H100 dedicated, Together   API blend $0.200/Mtok -> needs 7,625 tokens/s sustained, 24/7
H100, Lambda               API blend $0.200/Mtok -> needs 5,958 tokens/s sustained, 24/7

7.2 Reading the RAG chatbot#

Shape: 1,000-token system prompt, 4,000 retrieved tokens, a 200-token question and 800 tokens of history (6,000 input), 400 output.

  • Caching the 1,000-token system prompt saves only 12%, because most of the prompt is per-request retrieval that changes every time.
  • Trimming retrieval (top-5 to top-3) and capping output saves a further 25 points, with an eval needed to check answer quality.
  • Routing 70% of easy traffic to Haiku 5.5 brings the total to 21% of baseline, about $339 a month against $1,600.
  • On GPT-5.5 the same baseline would be $0.042 per request, $4,200 a month, 2.6 times Sonnet 5.5.

Lesson: for RAG the big levers are retrieval size and routing, not caching. Routing without an eval-verified router risks silent quality loss (11B.1 false savings).

7.3 Reading the support agent#

Shape: 3,000-token system and tools, a 200-token user message, each turn adds 750 tokens (a 600-token tool result and a 150-token call) and the model emits 150 tokens.

  • Uncached 20-turn conversation: $0.443. Cached: $0.0925, 4.8 times cheaper.
  • Doubling turns from 20 to 40 raises the uncached cost 3.35 times and the cached cost 2.3 times: caching flattens the curve but does not remove its curvature. At 80 turns the uncached cost is $5.37 against $0.53 cached.
  • Haiku 5.5 would run the same uncached conversation for $0.0221 and cached for about $0.0056, with the usual quality caveat.
  • This extends the 9-step run in 11B.1 ($0.131) to longer conversations and shows the scaling.

7.4 Reading the nightly batch#

Shape: 200,000 documents a night, 500-token document plus a 300-token instruction (800 input), 20 tokens of output. Input dominates, so the output/input ratio barely matters and model choice dominates: Haiku 5.5 on the batch API is about 40 times cheaper than Sonnet 5.5 synchronous ($270 versus $10,800 a month). Validate accuracy on a labelled set before downshifting. Caching the shared instruction can stack with batch pricing on paper, but cache hits are best-effort in asynchronous batches, so do not count on the saving.

Check the self-hosting alternative for this shape: 200,000 × 820 tokens is 164 million tokens a night. At an assumed 5,000 tokens a second one H100 would need about 9 hours, roughly $39 a night at $4.29 an hour, against $9 a night for Haiku 5.5 batch through the API. (The throughput figure is an illustrative assumption and depends on model and configuration.) The API wins at this price tier.

7.5 A coding-agent session#

Shape: 60 model calls, starting at 15,000 tokens of context and adding 2,500 tokens per step, 500 output tokens per step; context reaches 162,500 tokens and about 5.3 million input tokens are processed in total. On Sonnet 5.5 (full 1M window at standard price) the session costs about $10.95 uncached and $1.22 cached, 9 times less. Compacting at step 30 (a 3,000-token summary, resetting context to 20,000) removes about 39% of the input tokens but only about 11% of the cost once caching is on (about $1.09). So before caching, compaction saves tokens and dollars; after caching it mostly buys latency and quality headroom. On Opus 5.5 the same session is about $21.90 uncached and $2.45 cached. These figures come from the research calculation for this lesson (not reproduced in the script above); Anthropic's reported average of about $13 per developer per active day is consistent with roughly ten such cached sessions a day.


Part 8: Self-hosting break-even#

Deep-dive

8.1 The formula#

text
break-even tokens/s  = (GPU $/hr / API $ per Mtok) × 1,000,000 / 3,600
self-hosted $/Mtok   = GPU $/hr / (tokens/s × 3,600 / 1e6) / utilisation

The last line of the script applies it with Together's published prices: gpt-oss-120B serverless is $0.15 in and $0.60 out per million, so for an 8,000-in, 1,000-out request the blend is $0.20 per million. An H100 at $5.49 an hour needs 7,625 tokens a second sustained around the clock to match it.

8.2 What a detailed 2026 analysis found#

A secondary analysis dated 23 October 2026 (one detailed source, treat as indicative) measured gpt-oss-120B on a Lambda H100 at $4.29 an hour at about 8,973 tokens per second under a 50-tokens-per-second-per-user service level. Break-even needed about 5,958 tokens per second, which is about 66% utilisation, 24 hours a day; at a 100-tokens-per-second-per-user service level it could not break even even at full load. A B200 at $6.99 an hour broke even at about 22% utilisation. A business-hours-only H100 at about 30% utilisation cost about 2.2 times the API. Default vLLM settings produced about 2.6 times fewer output tokens per second than tuned benchmark configurations in one cited benchmark, and an engineer-quarter of effort shifts the break-even by thousands of tokens per second.

8.3 The verdict#

Use an API by default. Self-host when you have a reason other than price (data residency, an air-gapped environment, version pinning) or steady 24/7 or overnight batch utilisation that keeps GPUs busy; utilisation, not list price, decides the economics. 11B.1, Part 9 has the requests-per-day break-even calculator in code and the decision frame, and 11C.6 the hosting side.


Part 9: The tokenizer tax#

Deep-dive
  • Same text, different models. Claude 4.7 and later produce about 30% more tokens for the same text than earlier Claude models, depending on content.
  • Same text, different languages. Petrov, La Malfa, Torr and Bibi (NeurIPS 2023) found that the same text can tokenize to lengths differing by up to 15 times across languages, measured over 17 tokenizers, and named the effect the "tokenization premium"; the paper's examples include much higher costs for some languages (an Arabic figure of about three times English was not re-verified for this lesson). They call for "tokenization parity". (The paper does not use the phrase "token tax".)
  • Tokenizer generations improve. A single-author blog measurement (indicative only) found OpenAI's o200k tokenizer cut the Arabic-to-English token ratio from about 3.30 to about 1.35 relative to cl100k, Spanish from 1.48 to 1.24 and Korean from 1.82 to 1.38.
  • Rule of thumb: Gemini documents "about 4 characters per token".

Consequences: compare models on price per word or per task, not per token; non-English users reach the context limit and the bill sooner; and the discount ratios of caching and batch are unchanged, only the base. A Korean prompt at 1.38 times the English token count costs 1.38 times as much on input on the newer tokenizer.


Part 10: A decision table and a FinOps checklist#

Situation Move
Single-shot, high volume, input-heavy Smallest model that passes the eval; batch if it can wait
RAG with variable retrieved context Trim retrieval and route; cache only the stable prefix
Long agent runs Cache aggressively and compact; isolate sub-agents
Bursty interactive traffic Caching with the right TTL; avoid paying for fast mode unless latency demands it
Sparse overnight work Batch, or self-host only if GPUs stay busy
Heavy-user risk under flat pricing Allowance plus overage, spend caps, cheaper models for sub-agents

FinOps checklist

  • Put prices, model names and tier in configuration, with the date they were read.
  • Log, per request: model, input, output, cache read and write, reasoning tokens, tier, region, route, feature and customer.
  • Report cost per unit (request, conversation, outcome, user), as percentiles as well as averages.
  • Set budgets and alerts at several levels: per request, per customer, per day (11B.6 for budgets and attribution, 11B.7 for kill switches and spend alerts).
  • Re-count tokens on every model change; compare cost per task, not per token.
  • Review the bill when prices, tokenizers or models change, including deprecations.
  • Treat a cost reduction as a quality change until the eval says otherwise (11B.1).

Common misconceptions#

Misconception Reality
"Token prices keep falling, so cost will take care of itself." Fixed-capability prices fall; frontier prices are roughly flat; tokenizers, reasoning and agent loops push the other way.
"Caching makes everything about 90% cheaper." It discounts the re-read of an exact prefix. In the RAG example it saved 12%.
"Output and input tokens cost about the same." Output is typically 4 to 6 times input, and reasoning is billed as output.
"An agent's cost is linear in its steps." Total input tokens are quadratic in steps; caching cuts the price, compaction cuts the tokens.
"Per-seat pricing is predictable." Revenue is, cost is not; the heaviest users can cost many times the fee.
"Self-hosting is cheaper at scale." Only at high sustained utilisation; business-hours traffic usually costs more than an API.
"A 20% price cut is a 20% saving." Not if the tokenizer produces 30% more tokens.
"AI products have software margins." Reported margins are well below classic SaaS, and mostly estimates.

Key takeaways#

  • A token is billed in several ways: fresh input, output (4 to 6 times input), cache read and write, reasoning (as output), images and audio.
  • Prices span about 80 times between frontier and small models, and open-weight hosting sits in the small-model band. Routing is the biggest lever when you can verify quality.
  • Fixed-capability prices fall fast (10 to 40 times a year in the cited analyses); your bill need not, because of reasoning, agent loops, tokenizer changes and scheduled increases.
  • Agent input tokens grow as N·S + a·N(N−1)/2. Caching changes the price of the re-read; compaction changes the number of tokens.
  • Pick a unit (request, conversation, outcome, user) and measure its distribution, not its mean.
  • Self-hosting pays only with high sustained utilisation or non-price reasons.
  • Treat all prices as dated, configurable facts.

Terms introduced in this lesson#

Term One-line definition
Tokenomics The unit economics of an LLM product, whose cost of goods is metered in tokens
Output/input ratio The price of an output token divided by the price of an input token (typically 4 to 6)
Reasoning tokens Hidden thinking tokens, billed as output and reported separately in usage
Batch tier A 50%-off asynchronous pricing tier
Fast mode A premium tier that charges more for lower latency
Quadratic context cost Total input tokens of an agent growing with the square of the number of steps
Per-outcome price A price charged per successful result (for example a resolved conversation) rather than per seat or token
Heavy-user problem A flat price on variable-cost usage, with a fat tail of very expensive users
Self-hosting break-even The sustained tokens per second at which owning GPUs costs the same as an API
Tokenization premium The extra tokens a language needs for the same content (Petrov et al.)

Exercises#

  1. Add a lever (7.1): extend the RAG example with a fifth step that caches the 800-token history (assume 50% of requests continue a conversation within the TTL). Is it worth the added write cost?
  2. Break-even (Part 8): compute the break-even tokens per second for an H100 at $3.99 an hour against Haiku 5.5's blended price for an 8,000-in, 1,000-out request ($0.10 in, $0.50 out per million). What does the result say about self-hosting small proprietary-tier prices?
  3. Curves (7.1): change the support agent's per-turn addition from 750 to 300 tokens. How does the uncached-to-cached ratio at 40 turns change, and why?
  4. Outcome pricing (5.2): with $0.0925 per conversation and a $0.99 charge per outcome, find the resolution rate at which token cost is 25% of revenue.
  5. Tokenizer (Part 9): a product serves English and Korean prompts equally on a model whose Korean token ratio is 1.38. Compute the blended input-cost uplift versus an English-only estimate.
  6. Trend (Part 3): Opus 4.5 to Opus 5.5 is a 20% price cut with about 30% more tokens. Compute the net change for a workload that is 70% input and 30% output by cost (assume both sides scale the same way).
  7. Design (Part 10): pick one of your own features and write its unit definition, the three metrics you would log and the first lever you would test.
  8. Critique (5.4): a pitch deck quotes an 85% gross margin for an AI product. List four questions you would ask before believing it.

Check yourself#

  1. Why does an output token cost more than an input token?
  2. How are reasoning tokens billed, and how can you see them?
  3. Which is cheaper to cut by 100 tokens, prompt or answer, and why?
  4. What is the approximate price spread between frontier and small model outputs, and what does it enable?
  5. State the agent-loop input formula and say which term is quadratic.
  6. What does caching change in that formula, and what does compaction change?
  7. Why can a 20% price cut be a price rise?
  8. Why is per-seat pricing risky for an agent product?
  9. What does outcome-based pricing do to the cost of unresolved conversations?
  10. At what point does self-hosting pay, in terms of utilisation?
  11. What is the tokenization premium?
  12. Why did caching save only 12% in the RAG example?

Further resources#

Not verified in this lesson: all gross-margin figures; the 2025 heavy-user anecdote (news coverage only); Epoch's later 13x per year figure; distillation savings; Together's batch discount; OpenRouter and Groq prices; the prefill and decode explanation against a vendor document; the coding-agent session figures in 7.5 (from the research calculation, not the script).


← 11B.1: Cost and Latency Optimization | Module 11B overview | 11B.3: Caching Strategies →

Esc
02.2Tokens and TokenizationHow LLMs Work · 21k wordsLesson
02.3EmbeddingsHow LLMs Work · 18k wordsLesson
07Retrieval-Augmented Generation (RAG)11 lessons · Everyone who will build LLM features that must answer from knowledge the model doesn't have in its weights: internal handbooks and help centres, contracts, ticket histories, product docs, or any corpus that changes faster than a training run. The module covers the full RAG stack — architecture, retrieval strategy, query understanding, grounded generation, citations, conversation, managed services, advanced patterns, evaluation, debugging and production operation — and shows where each major provider's managed retrieval and citation features fit (OpenAI, Anthropic, Google Gemini and OpenRouter). All code is Python.Overview
08E.1The Model Context Protocol (MCP)Protocols and Extensibility · 12k wordsLesson
↑ ↓ navigate↵ openesc close