Tokens, context windows and cost
The unit you are billed in is not a word, the model forgets everything you do not re-send, and the re-sending is where the money goes
A chatbot has a 1,000-token system prompt. Each user message is about 100 tokens and each reply about 200. Over a 20-turn conversation, how many input tokens do you pay for in total?
The previous chapter treated tokens as roughly three quarters of a word. That approximation is good enough for English prose and wrong for almost everything else. This chapter shows where tokens come from, why the same text produces different token counts in different models and different languages, what the context window is and what happens when you fill it, and how to estimate the cost of an LLM feature before you build it. Prices quoted here are the Anthropic first-party API rates as of November 2026; check the pricing page before you put a number in a budget.
Tokens are not words
A model’s vocabulary is fixed when it is trained. It cannot have one entry per word: English alone has hundreds of thousands of word forms, and code, names, URLs and other languages add millions more. It cannot use single characters either: sequences would be four or five times longer, and every chapter-three cost that grows with sequence length would grow with them.
The compromise almost every modern model uses is byte-pair encoding (BPE), introduced for neural translation by Sennrich, Haddow and Birch in 2015. Training the tokeniser works like this:
- Start with a vocabulary of the 256 possible byte values. Any text can be written in it, which means no input is ever unrepresentable.
- Count every adjacent pair of symbols in a large training corpus.
- Add the most frequent pair to the vocabulary as a new symbol and replace every occurrence.
- Repeat until the vocabulary reaches the target size.
The early merges are things like t+h and th+e. After tens of thousands of merges, whole common words, word stems, and frequent code fragments like return are single tokens. Rare words stay split into several pieces. Text the tokeniser saw little of during training stays close to raw bytes.
Vocabulary sizes have grown over time: GPT-2 used 50,257 tokens, OpenAI’s cl100k_base about 100,000, o200k_base about 200,000, and Llama 3 uses 128,256. A larger vocabulary means fewer tokens per text, at the price of a larger embedding table in the model.
Three properties of BPE matter in practice.
Spaces belong to tokens. Most tokenisers attach the leading space to the word, so " cat" and "cat" are different tokens with different ids. This is why a trailing space at the end of a prompt can change a completion: the model was trained on text where the space usually arrives with the next word.
Numbers are split unevenly. 1234567 might be 123, 456, 7 in one tokeniser and 1, 234, 567 in another. The model never sees the digits as a number with place values, which is part of why the previous chapter put arithmetic in the “bad at” column.
Tokenisers are model-specific. Every model family has its own. Claude models count tokens differently from Llama, which counts differently from GPT models. Within Claude, the tokeniser introduced with Claude Opus 4.7 and used by the current models produces roughly 30% more tokens for the same text than the one before it. A token count is only meaningful next to the name of the model that produced it.
The same text, different counts
How many tokens a text becomes depends on how much text like it the tokeniser saw while learning its merges.
| Text | Typical characters per token | Why |
|---|---|---|
| English prose | about 4 | The training corpus is dominated by English; common words are one token |
| Python code | 2.5 to 4 | Keywords and common identifiers merge well; indentation, operators and unusual names do not |
| Japanese | about 1 to 1.5 | Each character is 3 bytes in UTF-8; common ones have their own tokens, rarer ones split into bytes |
| Yoruba | about 1.5 to 2 | Latin letters, but tone marks and under-dots are combining characters that the merges rarely saw together |
The ranges are rough and you will measure the real ones in the lab. The consequence is not rough at all. A conversation in Yoruba can cost one and a half to two times what the same conversation costs in English, fill the context window that much faster, and leave less room for the documents you wanted the model to read. It is often also answered less well, because a model has seen less text in that language. This is sometimes called the token tax, and if you are building for users who do not write in English, measure it before you set prices.
A trap inside the trap: the same visible text can be encoded in Unicode more than one way. The Yoruba ọ̀ can be one precomposed character plus a combining accent, or a plain o plus two combining marks. They look identical and tokenise differently. Normalise input (Python’s unicodedata.normalize("NFC", s)) before you count or send it.
Never estimate Claude token counts with tiktoken. It is OpenAI’s tokeniser, and on Claude’s tokeniser it undercounts, by more on code and non-English text. To count for a Claude model, call the token counting endpoint (client.messages.count_tokens in the Python SDK) with the model id you plan to use. It is free, has its own rate limit separate from message creation, and returns input_tokens. Anthropic describes the result as an estimate that can differ from the billed count by a small amount.
The context window is the model’s entire memory
The context window is the maximum number of tokens the model can attend to in one request. On the Claude API it includes everything: the system prompt, every message in the conversation, tool definitions, documents and images, and the output being generated, including thinking tokens.
It is the model’s entire working memory. The model has no other memory. Weights are fixed at inference time and the API keeps nothing between requests. If a fact is not in the context, the model does not know it for this request, apart from what it absorbed in training. Every “memory” feature in an LLM product is software that decides what to put back into the context next time.
Current sizes, from the Anthropic models documentation and the Ollama library:
| Model | Context window | Max output per request |
|---|---|---|
| Claude Opus 5.5, Claude Sonnet 5.5, Claude Haiku 5.5 | 1,000,000 tokens | 128,000 tokens |
| Claude Haiku 4.5 | 200,000 tokens | 64,000 tokens |
| Llama 3.2 3B (the model) | 131,072 tokens | limited by context |
| Llama 3.2 3B under Ollama, default | 4,096 tokens unless you set num_ctx |
limited by context |
The last row catches almost everyone who runs models locally. The model supports 128K tokens; Ollama allocates a 4,096-token window unless you raise it with options: {"num_ctx": 32768} per request or OLLAMA_CONTEXT_LENGTH for the server. The reason is memory: chapter three shows that each token in the window costs about 112 KiB of cache for this model, so a full 128K window needs about 14 GiB on top of the weights.
A large window is not a promise that the model uses all of it well. Liu and colleagues showed in 2023 that models retrieve information from the start and end of a long context more reliably than from the middle, and Anthropic’s own documentation describes accuracy and recall degrading as the token count grows. Chapter three explains part of why: attention spreads a fixed budget of weight over more and more tokens. Module three returns to the question of when to put a whole document in context and when to retrieve the relevant parts.
What happens past the limit
Two different systems, two different failures, and one of them is silent.
The Claude API rejects input that does not fit. If the input alone exceeds the context window, the request fails with a 400 invalid_request_error, “prompt is too long”. If the input fits but input plus max_tokens does not, current models accept the request and stop generation at the limit with stop_reason: "model_context_window_exceeded". Separately, if the output reaches your max_tokens, the response ends mid-sentence with stop_reason: "max_tokens". Check stop_reason on every response: a truncated JSON object that you parse without checking is a production incident.
Ollama trims silently. Send a prompt longer than num_ctx and Ollama drops tokens from the start of the prompt to make it fit, returns a normal response, and raises no error. In a test for this chapter, a 900-word prompt sent with num_ctx set to 512 came back with prompt_eval_count: 259: about two thirds of the prompt never reached the model, and the answer was confidently about the part that did. If your local RAG pipeline puts the retrieved documents first and the question last, the documents are what gets cut. Compare prompt_eval_count with your own count of what you sent.
Input and output are priced differently
Every hosted API bills input tokens and output tokens separately, and output costs more. The current Claude rates per million tokens:
| Model | Input | Output | Cache read |
|---|---|---|---|
Claude Opus 5.5 (claude-opus-5-5) |
$4.00 | $20.00 | $0.20 |
Claude Sonnet 5.5 (claude-sonnet-5-5) |
$2.00 | $10.00 | $0.10 |
Claude Haiku 5.5 (claude-haiku-5-5), prompt up to 100,000 tokens |
$0.10 | $0.50 | $0.01 |
| Claude Haiku 5.5, prompt over 100,000 tokens | $0.50 | $2.50 | $0.05 |
Output is five times the price of input on all of them. The reason is in the generation loop from the previous chapter. Input tokens are all known up front, so the model processes thousands of them in one parallel pass, called prefill, which keeps the accelerator’s arithmetic units busy. Output tokens are produced one at a time, each needing its own pass through all of the weights, called decode. Decode is limited by how fast weights and cached state can be read from memory rather than by arithmetic, and it holds a slot on expensive hardware for the whole response. Chapter three and the serving chapter in module four go further.
Three details that change real bills:
- Thinking tokens are output tokens. Current Claude models think before answering, and those tokens are billed at the output rate whether or not you display them. The
effortsetting is the main control over how many there are. - Haiku 5.5 has a price step at 100,000 prompt tokens. A request whose prompt is over the threshold pays the higher rate on all of its tokens, not only on the excess. A 99,000-token prompt and a 101,000-token prompt differ in price by a factor of five.
- Cached input is much cheaper. When the start of a request is identical to a recent one, prompt caching bills those tokens at the cache-read rate: 5% of the input price on Opus 5.5 and Sonnet 5.5, 10% on Haiku 5.5. A long, stable system prompt is the textbook case. Module two’s chapter on caching covers how to arrange prompts so it works.
Conversations cost more the longer they run
Because the API is stateless, a chat application re-sends the whole conversation on every turn. With a system prompt of S tokens, user messages of u tokens and replies of r tokens, turn k sends S + k·u + (k-1)·r input tokens. Summed over n turns, the input grows with n². The Predict above worked through one case; here it is at several lengths, priced on Claude Sonnet 5.5 (S = 1,000, u = 100, r = 200):
| Turns | Total input tokens | Total output tokens | Cost on Sonnet 5.5 |
|---|---|---|---|
| 5 | 8,500 | 1,000 | $0.03 |
| 20 | 79,000 | 4,000 | $0.20 |
| 50 | 422,500 | 10,000 | $0.95 |
| 100 | 1,595,000 | 20,000 | $3.39 |
Five times the turns from 20 to 100 costs seventeen times as much. Individual requests stay well inside the window here (turn 100 sends about 31,000 tokens), so nothing fails; the bill grows quietly.
The levers, in the order you should reach for them:
- Prompt caching. The history is the same prefix on every turn, so most of it can be read from cache at a fraction of the price. This is the biggest single saving for chat and costs almost nothing to adopt.
- Cap and trim history. Keep the last N turns, or drop tool results the model no longer needs.
- Summarise or compact. Replace old turns with a summary. The Claude API offers server-side compaction for long conversations; you can also do it yourself.
- Smaller system prompts. Every token in the system prompt is paid on every turn of every conversation. A 3,000-token prompt across 10,000 conversations of 6 turns is 180 million input tokens a day before anyone has said anything.
Estimating cost before you build
The estimate takes five numbers: requests per day, input tokens per request, output tokens per request, and the two prices. For multi-turn features, compute input per conversation with the sum above rather than multiplying one turn by the number of turns.
A worked example. A support assistant handles 10,000 conversations a day, averaging 6 turns. The system prompt is 2,000 tokens, user messages average 80 tokens and replies 250. Input per conversation is the sum over k = 1 to 6 of 2,000 + 80k + 250(k-1), which is 17,430 tokens. Output is 6 × 250 = 1,500 tokens.
| Model | Cost per conversation | Per day | Per 30 days |
|---|---|---|---|
| Claude Opus 5.5 | $0.0997 | $997 | $29,900 |
| Claude Sonnet 5.5 | $0.0499 | $499 | $14,960 |
| Claude Haiku 5.5 | $0.0025 | $25 | $750 |
These are before caching, and the 2,000-token system prompt is 69% of the input (12,000 of 17,430 tokens per conversation). With it cached, Sonnet’s input cost per conversation falls by roughly 65%. The spread between models is 40 times, which is why the model choice is a product decision and not a detail: chapter seven of module two covers how to make it with evaluation numbers rather than intuition.
Then sanity-check against measurement. Before launch, run a sample of realistic conversations, log usage.input_tokens and usage.output_tokens from every response, and compare with the estimate. The usual surprises are longer outputs than assumed (models are wordier than your examples), more thinking tokens on hard questions, retries that double some requests, and conversations far longer than the average because a few users never leave.
For a local model the marginal cost is electricity and the hardware you already own. A laptop running a 3B model draws roughly 30 to 60 W under load. Summarising a 100,000-token document takes a few minutes of prefill on an Apple-silicon laptop, so the energy is in the order of a few watt-hours: a fraction of a cent at European household prices. The real costs are elsewhere: memory for the context (about 11 GiB of cache for 100,000 tokens on this model), the quality gap to a frontier model, and the engineer-hours to run it. The lab measures your own machine.
You will count the same texts with three tokenisers, price a 100,000-token summarisation job on two Claude models and on your own laptop, and plot how input tokens grow over a 20-turn conversation. No step calls a paid endpoint: token counting is free and the conversation runs on the local model.
1. Set up.
From the root of your ATLAS checkout:
cd labs/ai && uv add tiktoken matplotlib
mkdir -p tokens && cd tokens
export ANTHROPIC_API_KEY=sk-ant-...labs/ai/pyproject.toml, the project the previous chapter’s lab created (anthropic and requests are already in it), and installs them into labs/ai/.venv. tiktoken downloads its vocabulary files on first use, a few MB each, and caches them.2. Tokenise four texts with OpenAI’s tokenisers.
Create texts.py with the samples. The English, Yoruba and Japanese lines say the same thing:
TEXTS = {
"english": "Good morning. How is your family? I want to buy a book at the market.",
"yoruba": "Ẹ kú àárọ̀. Báwo ni ìdílé yín? Mo fẹ́ ra ìwé kan ní ọjà.",
"japanese": "おはようございます。ご家族はお元気ですか?市場で本を一冊買いたいです。",
"python": "def mean(xs: list[float]) -> float:\n return sum(xs) / len(xs) if xs else 0.0\n",
}Then tiktoken_counts.py:
import tiktoken
from texts import TEXTS
for name in ("cl100k_base", "o200k_base"):
enc = tiktoken.get_encoding(name)
print(f"== {name}")
for label, text in TEXTS.items():
ids = enc.encode(text)
print(f" {label:9} chars={len(text):3} tokens={len(ids):3} chars/token={len(text) / len(ids):.1f}")
enc = tiktoken.get_encoding("cl100k_base")
for label in ("english", "yoruba"):
pieces = [enc.decode_single_token_bytes(i) for i in enc.encode(TEXTS[label])]
print(label, pieces[:14])uv run python tiktoken_counts.pycl100k_base and 28 in o200k_base; in Japanese, 32 and 26. The larger, more multilingual o200k_base vocabulary narrows the gap but does not close it. The Python line is 27 or 28 tokens, about 3 characters per token. The printed pieces show why: English splits into whole words with their leading spaces (b' morning'), while Yoruba splits into fragments and raw bytes such as b'\xe1\xba', part of a single character.3. Count the same texts for Claude.
Create claude_counts.py. The endpoint counts a whole message, which includes a few tokens of message framing, so the script subtracts the count for a one-character message:
import anthropic
from texts import TEXTS
client = anthropic.Anthropic()
def count(model, text):
return client.messages.count_tokens(
model=model, messages=[{"role": "user", "content": text}]
).input_tokens
for model in ("claude-opus-5-5", "claude-haiku-4-5"):
base = count(model, ".")
print(f"== {model} (framing overhead {base - 1})")
for label, text in TEXTS.items():
n = count(model, text) - base + 1
print(f" {label:9} tokens={n:3} chars/token={len(text) / n:.1f}")uv run python claude_counts.pyclaude-opus-5-5 uses the newer tokeniser and returns higher counts than claude-haiku-4-5 for the same text, by roughly a quarter to a third. The ordering across languages is the same as in step 2: Yoruba and Japanese cost several times more tokens than English for the same sentence. If you had estimated a Claude bill with tiktoken, every number would be low.4. Price a 100,000-token summary three ways.
First measure your laptop. Create local_speed.py, which feeds the local model a long, real document (the built-in help text for Python’s str type, a few thousand tokens) with a context window large enough to hold it:
import pydoc, requests
doc = pydoc.render_doc(str, renderer=pydoc.plaintext)
r = requests.post("http://localhost:11434/api/generate", json={
"model": "llama3.2:3b",
"prompt": doc + "\n\nSummarise the text above in five bullet points.",
"stream": False,
"options": {"num_ctx": 16384, "num_predict": 300},
}, timeout=600).json()
pre = r["prompt_eval_count"] / r["prompt_eval_duration"] * 1e9
dec = r["eval_count"] / r["eval_duration"] * 1e9
print(f"prompt tokens {r['prompt_eval_count']}, prefill {pre:.0f} tok/s, decode {dec:.0f} tok/s")uv run python local_speed.pyThen price.py, with your measured speeds filled in:
DOC_IN, SUMMARY_OUT = 100_000, 1_000
PRICES = { # USD per million tokens, Anthropic pricing page, November 2026
"claude-opus-5-5": (4.00, 20.00),
"claude-sonnet-5-5": (2.00, 10.00),
}
for model, (p_in, p_out) in PRICES.items():
cost = DOC_IN * p_in / 1e6 + SUMMARY_OUT * p_out / 1e6
print(f"{model:18} ${cost:.3f}")
PREFILL_TPS, DECODE_TPS = 600, 40 # replace with your measurements
WATTS, USD_PER_KWH = 45, 0.30
seconds = DOC_IN / PREFILL_TPS + SUMMARY_OUT / DECODE_TPS
kwh = WATTS * seconds / 3.6e6
print(f"{'llama3.2:3b local':18} ${kwh * USD_PER_KWH:.4f} ({seconds / 60:.1f} min, {kwh * 1000:.1f} Wh)")uv run python price.pylocal_speed.py prints something like prompt tokens 3639, prefill 699 tok/s, decode 62 tok/s on an Apple-silicon laptop. claude-opus-5-5 comes to $0.420 and claude-sonnet-5-5 to $0.210: input is 95% of each bill, because summarising reads a lot and writes a little. The local line is a fraction of a cent of electricity and several minutes of wall-clock time. Your measured prefill speed on a few-thousand-token prompt is an upper bound: prefill slows as the context grows, because attention cost grows with the square of the length (chapter three), so the real 100,000-token run would take longer and need num_ctx above 100,000 and about 11 GiB of memory for the cache. Add claude-haiku-5-5 at (0.50, 2.50) and see the over-100K rate apply, because the prompt is 100,000 tokens plus the instruction.5. Watch a conversation grow.
Create chat20.py. The local model writes the replies; the Claude counting endpoint measures what each turn would send to Sonnet 5.5:
import anthropic, requests
import matplotlib.pyplot as plt
client = anthropic.Anthropic()
SYSTEM = "You are a concise assistant for a bookshop in Lagos. " * 40 # stands in for a real system prompt
messages, per_turn = [], []
for turn in range(1, 21):
messages.append({"role": "user", "content": f"Recommend book number {turn} for a long flight, in two sentences."})
n = client.messages.count_tokens(model="claude-sonnet-5-5", system=SYSTEM, messages=messages).input_tokens
per_turn.append(n)
reply = requests.post("http://localhost:11434/api/chat", json={
"model": "llama3.2:3b", "stream": False,
"messages": [{"role": "system", "content": SYSTEM}] + messages,
"options": {"num_ctx": 16384, "num_predict": 120},
}, timeout=300).json()["message"]["content"]
messages.append({"role": "assistant", "content": reply})
print(f"turn {turn:2}: input {n:5} tokens")
cumulative = [sum(per_turn[:i + 1]) for i in range(len(per_turn))]
naive = [per_turn[0] * (i + 1) for i in range(len(per_turn))]
print(f"total input {cumulative[-1]} tokens, ${cumulative[-1] * 2 / 1e6:.4f} on Sonnet 5.5 before caching")
plt.plot(range(1, 21), cumulative, marker="o", label="full history re-sent (what you pay)")
plt.plot(range(1, 21), naive, linestyle="--", label="first turn x n (the naive estimate)")
plt.xlabel("turn"); plt.ylabel("cumulative input tokens"); plt.legend()
plt.savefig("chat20.png", dpi=120)uv run python chat20.py && open chat20.png # xdg-open on Linuxtexts.py, wrap the Yoruba string in unicodedata.normalize("NFD", ...) (add import unicodedata) and re-run steps 2 and 3. The text prints identically on screen, and the cl100k_base count goes from 38 to 47, because each tone mark and under-dot is now a separate combining character. Same words, same meaning, a bigger bill. Then go back to local_speed.py, set num_ctx to 512, and run it again: prompt tokens falls from about 3,600 to about 260. The model saw the last few lines of the document, wrote a five-bullet summary anyway, and nothing raised an error.Template
# Cost estimate and monthly budget: <feature>
Owner <role>. Approver <role>. Date <date>. Decision needed: <what, from whom, by when>.
## 1. What one task is
<one request or one conversation>, on <model>. Prices as of <month year>, from <source>.
## 2. Token assumptions per task
| | Input tokens | Output tokens | Source or assumption |
Fixed part (system prompt): <n>. Per turn: user <n>, reply <n>. Turns: <n>.
## 3. Volume
<tasks per day>, <days per month>, <tasks per month>. Source or assumption.
## 4. Cost at each assumption
| Case | Model | Cost per task | Per day | Per month | Caching |
## 5. Budget, ceiling and alert
- Monthly budget: $<amount>. Alert at $<amount> (<how it is measured>). Ceiling at $<amount>.
## 6. When the ceiling is hit
<what is switched off or capped, who is told, what the user sees, who may lift it>
## 7. How this could be wrong
<one way, and what would show it. Check against logged usage after <n> days.>
## 8. Out of scope and sign-off
Out of scope: <what this estimate leaves out>. Prepared <name, date>. Approved <name, date>. WORKED EXAMPLE
A product manager or engineering lead writes this before launch; the head of support and the finance owner approve it. Here it covers the support assistant from this chapter.
Header. Owner: product manager, support assistant. Approvers: head of support and the finance owner. Date: 20 November 2026. Decision needed: which model to launch on, and the monthly budget, before launch.
Task. One conversation, on Claude Sonnet 5.5, at the November 2026 rates in this chapter.
Tokens. Assumed: a 2,000-token system prompt, 80-token user messages, 250-token replies, 6 turns. That is 17,430 input tokens and 1,500 output tokens per conversation.
Volume. Assumed: 10,000 conversations a day, 30 days, so 300,000 a month.
Cost.
| Case | Per conversation | Per month |
|---|---|---|
| Haiku 5.5, no caching | $0.0025 | $750 |
| Sonnet 5.5, no caching | $0.0499 | $14,960 |
| Opus 5.5, no caching | $0.0997 | $29,900 |
| Sonnet 5.5, caching on | not measured | about $6,000 to $6,500 (this chapter’s estimate) |
Budget. $8,000 a month. Assumed alert: $7,200 (90%), checked daily against logged usage. Ceiling: $8,000.
At the ceiling. Assumed: new conversations stop at 20 turns, then new ones go to the human queue; the support lead is told at the alert and the head of engineering lifts the cap.
Could be wrong. Conversations may run longer than 6 turns; the logged average would show it. Caching may save less than hoped: if only the 2,000-token system prompt is cached, input falls by about 65%, so the month is about $8,160, over budget.
Decision. Approve Sonnet 5.5 with caching, to be re-measured in a shadow run. Out of scope: staff cost of escalations.
Now you
A 40-person legal-tech startup wants to add a contract summary feature. A customer uploads a contract of about 100,000 tokens and gets a 1,000-token summary, one request each. Assume 300 summaries a week, which you can treat as 1,300 a month, and a budget of $400 a month. The feature has no chat, so each task is a single request. Reuse step 4 of the lab: price.py prints $0.420 on claude-opus-5-5 and $0.210 on claude-sonnet-5-5 for exactly this job, and the step tells you to add Haiku 5.5 at the over-100K rate. Choose your own alert and ceiling, and say what customers see when the ceiling is hit. The head of product reads it and the founder approves it. It decides which model the feature launches on and what spend stops it.
Self-check
You are launching the support assistant from the worked example: about 10,000 conversations a day, 6 turns each, a 2,000-token system prompt. The monthly budget is $8,000. In a 200-conversation pilot graded by the support team, Claude Sonnet 5.5 resolved 91%, Claude Haiku 5.5 resolved 84%, and Claude Opus 5.5 resolved 93%. Which do you ship?
- PAPER Neural Machine Translation of Rare Words with Subword Units Rico Sennrich, Barry Haddow, Alexandra Birch, 2015
The paper that brought byte-pair encoding to neural models. The algorithm fits on a page and is the ancestor of every tokeniser in this chapter. Read: sections 1 and 3.2 (the BPE algorithm, with its ten-line Python listing); skip the translation experiments.
- TALK Let's build the GPT Tokenizer Andrej Karpathy, 2024
Two hours building a byte-level BPE tokeniser from scratch, with a long list of model failures that trace back to tokenisation. The first hour is enough to understand everything here; the second is for the curious.
- CODE Tiktokenizer
Paste text and see it split into coloured tokens with their ids. The fastest way to build intuition for how code, numbers and other languages tokenise; remember the counts are for OpenAI tokenisers, not Claude.
- DOC Anthropic API pricing
The source for every price in this chapter, plus cache, batch and long-context rules. Read the model table and the long-context section; prices change, so check here before any estimate goes into a budget.
- DOC Token counting
How to count tokens for a specific Claude model before sending, including system prompts, tools, images and PDFs. Note the section on the newer tokeniser and why counts from older models should not be reused.
- DOC Context windows
What counts toward the window, how thinking tokens are handled across turns, and the exact overflow behaviour. Read the overflow section before you write any error handling.
- PAPER Lost in the Middle: How Language Models Use Long Contexts Liu, Lin, Hewitt, Paranjape, Bevilacqua, Petroni, Liang, 2023
The experiment showing that models use information at the start and end of a long context better than the middle. Newer models do better, but the effect is why a bigger window is not a substitute for choosing what goes in it. Read: sections 1 and 2, and figure 1.
All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.