Skip to main content

Tokens and the context window

When you send text to a large language model, it doesn't parse individual characters or complete words directly. Instead, it reads and writes in —discrete chunks of characters drawn from a fixed vocabulary established during training. Tokenization is the translation step that chops raw text into this sequence of numerical identifiers before computation ever begins.

In everyday English, common words usually map to a single token. Simple words like The, cat, and sat are each individual tokens, where the leading whitespace is typically attached directly to the word. Less common words, however, get split into smaller sub-word fragments. An unusual family name, technical jargon, or an unfamiliar acronym might take three or four tokens to represent. Numeric sequences get split as well, with multi-digit numbers chunked into groups of two or three digits.

Understanding tokenization is essential because every constraint and cost in working with language models is denominated in tokens. API billing, context window limits, and response latency all trace back to token counts.

The tokenizer is a fixed vocabulary

The is the software component responsible for breaking text into these chunks. It operates against a pre-compiled vocabulary—typically ranging from 30,000 to over 200,000 token entries—constructed through algorithms like Byte Pair Encoding (BPE) on a massive training corpus before model training starts. The process begins with raw bytes and iteratively merges the most frequently occurring character pairs into unified vocabulary entries until reaching a target vocabulary size.

Once a tokenizer's vocabulary is created, it is permanently frozen. Because every internal weight in the neural network is mathematically tied to the specific token IDs in that vocabulary, you cannot modify the token dictionary after training without invalidating the model. Any new slang, contemporary names, or brand-new terms coined after that point must be pieced together from existing sub-word fragments.

Tokenizers also vary significantly across model families. Different providers train their tokenizers on different corpora with distinct vocabulary sizes and optimization goals, meaning the exact same paragraph will produce different token counts depending on the model you use. Asking "how many tokens is this document?" has no universal answer until you know which model's tokenizer is processing it. A prompt that takes 3,800 tokens on one model might require 4,500 on another—a discrepancy that can easily push a tightly sized prompt over its limits.

The rule of thumb, and where it stops working

For standard English prose, a common estimation is that one token represents roughly four characters, or about 750 words per 1,000 tokens. This ratio works well for rough back-of-the-envelope planning, but relying on it for precise architectural limits will cause unexpected failures.

The same length of text, split into very different numbers of tokens Two rows, one above the other, drawn to the same scale so that a box's width matches the number of characters in it. The top row is the English sentence "The cat sat on the mat." It is 23 characters and is split into 7 token boxes: The, cat, sat, on, the, mat, and the full stop. Each box is drawn with a thin outline. The bottom row is the JSON fragment: open brace, quote, user, underscore, id, quote colon, space, 104, 82, comma, space quote, ok, quote colon, true, close brace. It is 30 characters, only seven more than the sentence, but is split into 15 token boxes, more than twice as many. Its boxes are drawn with a thicker dashed outline and are labelled JSON. A middle dot at the start of a token stands for a leading space. The counts are printed at the end of each row: 23 characters and 7 tokens for the prose, 30 characters and 15 tokens for the JSON. A note underneath says the split is illustrative and that every tokenizer divides text differently. One token is about four characters of English. Only of English. Prose thin outline The ·cat ·sat ·on ·the ·mat . 23 characters 7 tokens JSON dashed outline { " user _ id ": · 104 82 , ·" ok ": ·true } 30 characters 15 tokens Seven more characters, eight more tokens. A leading dot marks a space inside a token. The split shown is illustrative. Every tokenizer cuts differently.
Seven more characters of JSON than of English, and eight more tokens to pay for.

Several common types of input shift this ratio dramatically:

  • Code and structured data: JSON, YAML, and source code feature dense punctuation and formatting characters that rarely merge into larger tokens. A brief payload like {"user_id": 10482, "ok": true} is only 30 characters long, yet costs more than twice as many tokens as an equivalent sentence in plain English because braces, quotes, colons, and commas frequently become standalone tokens. Minified code and deeply nested data structures are even less efficient.
  • Non-Latin alphabets and international text: Most foundation model tokenizers are trained predominantly on English text. Consequently, languages using scripts such as Cyrillic, Arabic, Devanagari, Japanese, or Chinese are split into much smaller fragments. A passage in Japanese can easily require two to three times as many tokens as its English translation, making identical workflows significantly more expensive and context-heavy in other languages.
  • Long numbers and timestamps: Financial account numbers, ISO timestamps, and mathematical values get fragmented into small digit clusters. A single timestamp like 2026-09-09T14:32:07Z requires multiple tokens rather than one.
  • Unique identifiers and hashes: High-entropy strings like UUIDs, Base64-encoded blobs, and cryptographic hashes represent the worst case for token efficiency, often consuming nearly one token for every character or pair of characters.

Pasting a 400-line CSV export of transaction IDs into a prompt will consume far more tokens than word count metrics suggest. An application sized and tested exclusively on clean English text can easily hit context limits when faced with production stack traces or raw database dumps.

Counting tokens

Count tokens with the tokenizer of the model you will call. Do not estimate from a character count.

  1. Use the provider's token-counting endpoint, or the tokenizer library that provider publishes.
  2. Count the full request. Include the system prompt, the tool definitions and the whole message history.
  3. Add the maximum output length you allow to the input count.
  4. Compare that total against the model's context window before you send the request.
  5. Repeat the count when you change model. Token counts do not carry across model families.

Everything in the call is tokens

The text typed by the end user is usually only a modest fraction of what actually gets tokenized on a given API call. The supplied by the application or platform is tokenized as well, along with the full history of preceding messages. Because model APIs are stateless and hold no memory between requests, the client must resend the entire conversation on every single turn.

Active definitions contribute substantial token overhead too. If a harness provides twenty tools to a model, every request packages twenty tool names, descriptive summaries, and complete JSON schemas for their arguments. This catalog alone often adds several thousand tokens to the payload before a user even enters a prompt—an overhead that frequently gets overlooked during token budgeting.

The model's generated response consists of tokens as well, produced sequentially and billed upon generation.

Cloud providers divide usage into two distinct categories: represent everything sent in the request, while cover what the model generates. Output tokens are typically priced three to five times higher than input tokens. They are also fundamentally slower to process: whereas input tokens are digested in parallel across GPU cores, output tokens must be generated one after another in a sequential loop. A 4,000-token response takes substantially longer in wall-clock time and costs far more than a 200-token reply, as explored in the inference chapter.

Encouraging concise outputs yields tangible cost and latency savings. At the same time, long conversations quietly accumulate heavy input costs over time because the entire history must be resent with each interaction. Techniques like help mitigate this expense, and the what fills the window guide details how tokens distribute across real requests.

The window is one budget

The defines the maximum total number of tokens a model can hold in memory during a single inference call. This limit is an architectural property of the model itself, not an account quota. Crucially, the input prompt and the generated response must both fit within this single allocation.

A common pitfall is treating the context window solely as an input limit. If a model offers a 200,000-token window and an application sends 199,000 input tokens, only 1,000 tokens remain available for the output. Providers generally require setting an explicit cap on the maximum output tokens allowed, and that reserved capacity subtracts directly from the available window budget.

What happens at the edge

When conversations expand toward the context boundary, how the system handles the limit depends on where the boundary is caught. Understanding the difference is vital for debugging conversational applications.

If the incoming request exceeds the context window, the provider API will reject it outright with an error specifying the limit and the received token count. While disruptive, this explicit failure is straightforward to diagnose and trace.

In contrast, when an intermediate manages the conversation, it often attempts to prevent API errors by silently shedding context. It may summarize older messages, evict earlier file contents, or truncate tool results. This process—known as —happens behind the scenes. The symptom you observe is not an overt error, but a model that suddenly forgets constraints established at the beginning of the chat or re-reads code it already inspected. The context management chapter explores these compaction strategies and their associated tradeoffs.

A bigger window is not free

Context windows have expanded dramatically, with multi-million-token windows readily available across leading providers. However, having a large context window available does not mean you should fill it indiscriminately.

Cost scales linearly with volume: processing a million input tokens costs real money on every call, and repeating that in an agent loop quickly escalates cloud spending.

Latency also climbs with prompt size. Because the model must process every input token in the prompt before generating the very first token of the response, large inputs introduce noticeable delays before users see any output.

Finally, retrieval accuracy and attention fidelity decline in overstuffed prompts. A critical constraint or fact positioned in the middle of a massive context window is attended to far less reliably than when placed in a focused prompt—a dynamic detailed in what fills the window. Relying on oversized prompts often leads to paying higher bills for slower, less accurate answers.

Terms introduced

  • Token: the unit a model reads and writes, a chunk of a few characters drawn from a fixed vocabulary.
  • Tokenizer: the software that splits text into tokens, using a vocabulary learned once and frozen before training.
  • Context window: the maximum number of tokens a model can hold for one call, covering the request and the answer together.
  • Input tokens: everything sent to the model in a request, including the system prompt, the history and the tool definitions.
  • Output tokens: everything the model generates, billed at a higher rate than input and produced one at a time.

How providers do it

All three sell a million-token window and all three now run a token-counting endpoint. The row that changes a design is the last one, because the three answers are not the same shape.

QuestionAnthropicOpenAIGoogle
Tokenizer published?No file found; counting endpoint insteadYes, tiktokenNo file found; SDK tokenizer on Vertex
Counting endpointPOST /v1/messages/count_tokensPOST /v1/responses/input_tokensmodels/<id>:countTokens
Characters per token, their figureAbout 3.5Not stated on a page read todayAbout 4
Largest window read today1M (Opus 5, Sonnet 5, Fable 5.1)1,050,000, with input capped at 922,0001,048,576
Maximum output128K (64K on Haiku 4.5)128K65,536
Cheapest current model, per 1M in / outHaiku 4.5, $1 / $5gpt-5-nano, $0.05 / $0.40gemini-3.5-flash-lite, $0.30 / $2.50
Price varies with prompt size?NoNoYes, above 200K tokens on Pro-class models
Behaviour at the edge400 "prompt is too long" on oversized input; stop_reason: model_context_window_exceeded if generation runs out of roomstatus: "incomplete" with reason: max_output_tokens, billed but possibly emptyfinishReason: MAX_TOKENS on output; input overflow not documented

Every row above is confirmed except Google's input-overflow behaviour, OpenAI's encoding for its newest models, and OpenAI's characters-per-token figure, which are open in the tabs below.

Two things travel badly. A token count from one vendor does not transfer to another, and OpenAI's window figure is not the amount you may send, because the input cap sits well below it.

What this maps to: the Messages API. Tokens are counted under the tokenizer of the exact model you name, and there is a free endpoint that does the counting for you rather than a published tokenizer file.

QuestionAnswerStatus
Which tokenizer?Model-family specific. Claude Opus 4.7 and later use a newer tokenizer that produces about 30% more tokens for the same text than Sonnet 4.6 and earlierconfirmed
Is the tokenizer published?No public tokenizer file or vocabulary was found on the docs site. The docs point at the counting endpoint insteadunconfirmed; no vendor page states this either way
Characters per token"For Claude, a token approximately represents 3.5 English characters"confirmed
How do you count tokens?POST /v1/messages/count_tokens, returning {"input_tokens": N}. Free, rate-limited by tier, and documented as an estimateconfirmed
Published context window1M tokens on Fable 5.1, Opus 5, Sonnet 5, Opus 4.6 through 4.8 and Sonnet 4.6. 200K on Haiku 4.5 and on Sonnet 4.5 and olderconfirmed
Maximum output128K on the 1M-window models, 64K on Haiku 4.5. Batch API can reach 300K output with a beta headerconfirmed
Is 1M gated?No. "For every model with a 1M-token context window, 1M is the default: you don't need a beta header, and long-context requests are billed at standard pricing"confirmed
What counts against the window?System prompt, every message, tool definitions, and the output including extended thinking. Cached tokens still occupy the windowconfirmed
Input and output pricesPer million tokens: Opus 5 $5 in / $25 out. Sonnet 5 $2 / $10. Haiku 4.5 $1 / $5. Fable 5.1 $10 / $50. Batch API is half price both directionsconfirmed
Cache pricingOpus 5: $6.25 per million for a 5-minute cache write, $0.50 to read. Sonnet 5: $2.50 write, $0.20 readconfirmed
Tool definition overheadTool use adds a per-model system prompt overhead. Opus 5: 286 tokens for tool_choice auto or none, 406 for any or toolconfirmed
What happens when the input is too big?400 invalid_request_error, "prompt is too long", on every modelconfirmed
What if input plus max_tokens overflows?On Claude 4.5 and newer the request is accepted, and generation stops with stop_reason: "model_context_window_exceeded" if it reaches the limit. Older models need a beta headerconfirmed

Their vocabulary

Standard termTheir term
Context windowContext window
Input tokensInput tokens; cache write and cache read tokens are priced separately
Output tokensOutput tokens, which include thinking tokens
Maximum output lengthmax_tokens, a required field on every request

Where to look

usage on every Messages API response carries input_tokens, output_tokens, cache_creation_input_tokens and cache_read_input_tokens. Call count_tokens with the same body before sending if you need the input figure in advance.

Last verified: 2026-09-09 against the Anthropic platform docs: token counting, models overview, pricing, context windows, and Create a Message (platform.claude.com/docs/en/build-with-claude/token-counting, /models/overview, /about-claude/pricing, /build-with-claude/context-windows, /api/messages/create).


Check your understanding

0 of 4 answered

  1. A colleague says a 20,000-word document is "about 27,000 tokens". What is wrong with stating it that way?
  2. A prompt that fits comfortably in the window when it holds English documentation blows past it when the same volume of minified JSON is pasted in. Why?
  3. A retrieval step can fill a one-million-token window with everything remotely relevant, and the request still fits. Why is that a poor default?
  4. A model has a 200,000-token context window. A request carries 199,000 input tokens. What should you expect?