What are tokens, and why do they matter?

Learning path, stage 1 of 5: How LLMs work · question 2 of 10

Tokens are the units an LLM reads and writes. They are usually sub-word pieces produced by a tokenizer such as byte-pair encoding (BPE). Context limits, pricing, rate limits and speed are all measured in tokens, not characters or words.

Rules of thumb

  • In English, one token is about 3–4 characters, or roughly ¾ of a word. Code, non-English text and unusual strings use more tokens.
  • Each model family has its own tokenizer, so the same text gives different counts on different models. Count with the provider's API instead of guessing.
  • Input and output tokens are billed separately, and output usually costs several times more.

Why it matters in practice

  • Context window: the system prompt, history, retrieved docs, tool definitions and the answer must all fit.
  • Cost: a 20k-token system prompt sent on every request adds up fast. Prompt caching helps.
  • Latency: generation speed is measured in output tokens per second, so long answers are slow answers.
  • Odd behaviour: tokenization explains why models can miscount letters in a word. The model sees chunks, not characters.

Sources

Code example

tsx
1// Count tokens before sending, e.g. to decide whether to trim history.
2import Anthropic from "@anthropic-ai/sdk";
3
4const client = new Anthropic();
5
6const messages: Anthropic.MessageParam[] = [
7 { role: "user", content: "Summarise this contract: ..." },
8];
9
10const { input_tokens } = await client.messages.countTokens({
11 model: "claude-opus-5-5",
12 system: "You are a careful legal assistant.",
13 messages,
14});
15
16const BUDGET = 150_000;
17if (input_tokens > BUDGET) {
18 console.warn(`Prompt is ${input_tokens} tokens; trim or summarise history first`);
19}
20
21// After a real call, usage tells you exactly what you paid for:
22// response.usage.input_tokens, response.usage.output_tokens

To run it: follow the one-time setup guide, add npm i @anthropic-ai/sdk, save the code as a .ts file and run npx tsx file.ts. Anything marked declare is a part you supply.

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the AI Agents & LLMs set.

Open in study app