Costs and latency
15 minHow AI usage is priced, how to estimate a request's cost before you send it, and the levers that make apps faster. Includes the Module 1 project, a token and cost calculator.
Two questions decide whether an AI feature is viable in the real world: what does it cost? and how long does it take? This lesson gives you the numbers and the levers for both.
How pricing works
You pay per token, with separate prices for input and output, quoted per million tokens (MTok):
| Model | Input / MTok | Output / MTok |
|---|---|---|
| Claude Fable 5.2 | $8.00 | $40.00 |
| Claude Opus 5.5 | $4.00 | $20.00 |
| Claude Sonnet 5.5 | $2.00 | $10.00 |
| Claude Haiku 5.5 | $0.10 | $0.50 |
The formula
cost = (input_tokens × input_price / 1,000,000)
+ (output_tokens × output_price / 1,000,000)Worked example. A chat reply on Opus 5.5 with 2,000 input tokens and 500 output tokens:
- Input: 2,000 × $4 / 1,000,000 = $0.008
- Output: 500 × $20 / 1,000,000 = $0.010
- Total: $0.018, under two cents.
Cheap for one message. But multiply by 10,000 users sending 20 messages a day and it's $3,600 a day. Small numbers at scale become big numbers. That's why the levers below matter.
What makes a response slow
Latency is how long the user waits. It has two parts:
- Time to first token: how long before anything appears. Mostly driven by input size and how much the model thinks first.
- Generation time: how long it takes to write the output, token by token.
For most apps, output length dominates. A 2,000-token answer takes much longer than a 200-token one.
The levers
| Lever | Cuts cost | Cuts latency | How |
|---|---|---|---|
| Shorter output | Yes | Yes | Ask for concise answers in the system prompt |
| Lower effort | Yes | Yes | output_config: { effort: "low" } for simple tasks |
| Smaller model | Yes | Yes | Once quality is proven (previous lesson) |
| Streaming | No | Feels faster | Show tokens as they arrive (Module 3) |
| Prompt caching | Yes | Yes | Reuse a long, unchanging prompt prefix cheaply (Module 3) |
| Trim the context | Yes | Slightly | Send only what the task needs |
Streaming: the easiest UX win
Even when the total time is the same, users perceive a streaming answer as much faster, because words start appearing immediately. Here's a taste (you'll build a full streaming web app in Module 3):
import Anthropic from "@anthropic-ai/sdk";
const client = new Anthropic();
const stream = client.messages.stream({
model: "claude-opus-5-5",
max_tokens: 64000,
messages: [{ role: "user", content: "Explain how a turbocharger works, simply." }],
});
for await (const event of stream) {
if (event.type === "content_block_delta" && event.delta.type === "text_delta") {
process.stdout.write(event.delta.text);
}
}import anthropic
client = anthropic.Anthropic()
with client.messages.stream(
model="claude-opus-5-5",
max_tokens=64000,
messages=[{"role": "user", "content": "Explain how a turbocharger works, simply."}],
) as stream:
for text in stream.text_stream:
print(text, end="", flush=True)Mini-project: Token & Cost Calculator
Let's build a tool that tells you what a prompt will cost before you send it, then shows what it actually cost afterwards.
import Anthropic from "@anthropic-ai/sdk";
const client = new Anthropic();
// USD per million tokens. Check Anthropic's pricing page for current values.
const PRICES: Record<string, { input: number; output: number }> = {
"claude-opus-5-5": { input: 4, output: 20 },
"claude-sonnet-5-5": { input: 2, output: 10 },
"claude-haiku-5-5": { input: 0.1, output: 0.5 },
};
const MODEL = "claude-opus-5-5";
const prompt = process.argv.slice(2).join(" ") || "Write a haiku about a V8 engine.";
const messages: Anthropic.MessageParam[] = [{ role: "user", content: prompt }];
const usd = (n: number) => `$${n.toFixed(6)}`;
const price = PRICES[MODEL];
// 1. Estimate: count input tokens without running the model
const { input_tokens } = await client.messages.countTokens({ model: MODEL, messages });
console.log(`Prompt: ${input_tokens} input tokens ≈ ${usd((input_tokens * price.input) / 1e6)} before output`);
// 2. Actually send it
const started = Date.now();
const response = await client.messages.create({ model: MODEL, max_tokens: 16000, messages });
const seconds = (Date.now() - started) / 1000;
for (const block of response.content) {
if (block.type === "text") console.log(`\n${block.text}\n`);
}
// 3. Report what it really cost
const { input_tokens: inTok, output_tokens: outTok } = response.usage;
const cost = (inTok * price.input + outTok * price.output) / 1e6;
console.log(`Used ${inTok} in + ${outTok} out tokens in ${seconds.toFixed(1)}s → ${usd(cost)}`);
// 4. Compare: what would the same token counts cost on each model?
for (const [model, p] of Object.entries(PRICES)) {
console.log(` ${model.padEnd(20)} ${usd((inTok * p.input + outTok * p.output) / 1e6)}`);
}import sys
import time
import anthropic
client = anthropic.Anthropic()
# USD per million tokens. Check Anthropic's pricing page for current values.
PRICES = {
"claude-opus-5-5": {"input": 4, "output": 20},
"claude-sonnet-5-5": {"input": 2, "output": 10},
"claude-haiku-5-5": {"input": 0.1, "output": 0.5},
}
MODEL = "claude-opus-5-5"
prompt = " ".join(sys.argv[1:]) or "Write a haiku about a V8 engine."
messages = [{"role": "user", "content": prompt}]
price = PRICES[MODEL]
# 1. Estimate: count input tokens without running the model
counted = client.messages.count_tokens(model=MODEL, messages=messages)
print(f"Prompt: {counted.input_tokens} input tokens ≈ ${counted.input_tokens * price['input'] / 1e6:.6f} before output")
# 2. Actually send it
started = time.time()
response = client.messages.create(model=MODEL, max_tokens=16000, messages=messages)
seconds = time.time() - started
for block in response.content:
if block.type == "text":
print(f"\n{block.text}\n")
# 3. Report what it really cost
in_tok, out_tok = response.usage.input_tokens, response.usage.output_tokens
cost = (in_tok * price["input"] + out_tok * price["output"]) / 1e6
print(f"Used {in_tok} in + {out_tok} out tokens in {seconds:.1f}s → ${cost:.6f}")
# 4. Compare: what would the same token counts cost on each model?
for model, p in PRICES.items():
print(f" {model:<20} ${(in_tok * p['input'] + out_tok * p['output']) / 1e6:.6f}")Run it with your own prompt:
npx tsx cost.ts "Summarise the plot of a heist movie in three sentences."The comparison at the end is a rough guide: a different model would produce a different number of tokens (and different quality), but it shows the price gap clearly.
Try it: become cost-aware
- Run the calculator with a short prompt, then with a long one (paste in an article). How much does the input size change the cost?
- Ask for "a detailed, 1,000-word explanation" vs "a two-sentence explanation" of the same topic. Compare output tokens, time and cost.
- Add
output_config: { effort: "low" }to the request. What happens tooutput_tokensand the time taken? - Big question: if 1,000 people used your Module 0 chat app for 10 messages a day, roughly what would it cost per month? Use your measured numbers.
You now understand AI economics better than most people building with it. In Module 2, we'll make Claude's answers reliable.