LLM Tokens Explained: Tokenization, Context Windows, and Cost Control
A practical guide to how large language models handle text at the token level: what a token actually is, why text has to be tokenized at all, how BPE, WordPiece, and SentencePiece/Unigram differ in approach, and how token counts drive both context window capacity and API billing. It also covers engineering practices that reduce token consumption — trimming prompts, constraining output length, retrieving instead of stuffing context, caching shared prompts, and combining batching with streaming — along with tokenization pseudocode and an example for estimating the token usage of a single call.
1. What a Token Actually Is
Whether you are chatting with a large language model or calling its API, you keep running into the same unit of measurement: the token.
- Usage messages such as “This conversation has consumed 1,234 tokens.”
- Pricing quoted as a rate per million input tokens and a separate, usually higher, rate per million output tokens.
Many people assume on first contact that a token equals a character or a word. That is a common misconception. The accurate definition is that a token is the smallest unit of text a large model processes. The model does not read characters directly, nor does it work purely on words. Instead, raw text passes through a tokenizer, which splits it into a sequence of tokens, maps each token to an integer ID, and hands those IDs to the model for mathematical computation.
A useful analogy: tokens are the radicals of the model’s writing system. A token may be a complete English word, part of a word, a single Chinese character, or even a punctuation mark, a space, or a fragment of a number. Grasping this is the foundation for understanding every other aspect of token behavior.
2. Why Tokenization Comes First
If a model worked one character at a time, two serious problems would appear:
- Sequences become too long. Character-level units multiply the number of tokens in the same passage of text, crowding a limited context window and driving up compute cost.
- Semantic granularity is wrong. A single character carries almost no meaning, which makes it hard for the model to learn language patterns efficiently.
Working on whole words instead creates the opposite problem: vocabulary explosion and out-of-vocabulary (OOV) words. No vocabulary can enumerate every word, spelling variant, and technical term. This is why modern models generally adopt subword tokenization: common words stay as a single token, while rare words are split into smaller pieces. That keeps the vocabulary manageable and handles unseen words gracefully.
3. How the Mainstream Tokenization Algorithms Work
The most widely used algorithms differ in emphasis:
- BPE (Byte Pair Encoding): starts from characters and repeatedly merges the most frequent adjacent byte pairs into new units until a preset vocabulary size is reached. Because it operates at the byte level, it can cover arbitrary byte sequences and almost never produces OOV tokens.
- WordPiece: similar to BPE, but merges are chosen based on whether they improve the language model’s likelihood, rather than on raw frequency alone.
- SentencePiece / Unigram: works directly on raw text with no pre-tokenization step, searching for the optimal segmentation with a probabilistic model. It is particularly friendly to languages written without spaces, such as Chinese and Japanese.
Because different algorithms segment the same text differently, the token count varies between them. When estimating cost, rely on the actual tokenizer’s output rather than a simple character-to-token conversion.
The general flow, in pseudocode:
def tokenize(text):# 1. Preprocess the text: normalize case, whitespace, etc.text = normalize(text)# 2. Split into subword units according to the tokenizer's rulestokens = []for piece in split_into_subwords(text):token_id = vocab.lookup(piece) # look up the vocabulary to get an integer IDtokens.append(token_id)return tokensdef detokenize(token_ids):# Reverse step: map the IDs back to textreturn "".join(vocab.lookup_by_id(tid) for tid in token_ids)
A useful rule of thumb: English text averages roughly four characters per token, while Chinese packs more information into each character, so a single Chinese character often maps to one or two tokens. These are order-of-magnitude references only; the actual ratio shifts with domain, language, and the specific tokenizer.
4. Tokens and the Context Window
The context window is the total number of tokens a model can “see” in a single request, and it holds both input and output tokens:
total context window = input tokens + output tokens
This means that loading a document close to the limit compresses the room left for generation. When summarizing long documents, running multi-turn conversations, or building retrieval-augmented generation (RAG) pipelines, planning the input-to-output token split matters a great deal. Once the window is exceeded, the excess is either truncated or triggers an error, and information is lost.
5. How Tokens Drive API Cost
Mainstream LLM APIs bill by token, with input and output priced separately — output usually costs more per token. The reason is that the generation stage is autoregressive decoding performed one token at a time, which is more expensive to compute. Understanding this billing model is what makes accurate technology selection and budget estimation possible.
The example below shows how to roughly estimate the token volume of a single call:
def estimate_usage(input_text, expected_output_tokens=500):input_tokens = len(tokenize(input_text)) # consumed on the input sideoutput_tokens = expected_output_tokens # reserved on the output sidereturn {"input_tokens": input_tokens,"output_tokens": output_tokens,"total_tokens": input_tokens + output_tokens}# Measure real tokenization offline first, then calculate cost from itusage = estimate_usage(system_prompt + user_query)print(usage)
For enterprise applications, the recommendation is to add local token counting during the development phase and treat token measurement as part of the coding standards, rather than reacting to the bill after the fact.
6. Engineering Practices for Reducing Token Consumption
In real projects, token consumption is often an overlooked cost sink. The following practices cut it down significantly:
- Trim the prompt. Remove redundant pleasantries and repeated instructions, and keep the system prompt within what is necessary. Long openers burn input tokens for nothing.
- Control output length. Use explicit format constraints, such as fixed fields or a capped number of sentences, to reduce irrelevant generation and keep the model from rambling.
- Retrieve instead of stuffing. In long-document scenarios, retrieve the most relevant passages first rather than pushing the entire document into the context. This saves input tokens and improves results at the same time.
- Cache frequent content. When many requests share the same fixed system prompt, context caching support can reduce repeated computation and billing.
- Combine batching with streaming. Batch offline tasks to amortize cost, and use streaming output to improve the experience in interactive scenarios.
7. Practical Takeaways for Developers
Overall, understanding tokens comes down to three threads:
- Conceptually: a token is the model’s minimum processing unit. It sits between characters and words, and the tokenization algorithm decides where the boundaries fall.
- Mechanically: the token count governs both context window capacity and API cost, so input and output must be planned together.
- In engineering terms: move token accounting forward into the design and development stages, and keep optimizing through shorter prompts, controlled output length, and retrieval.
For teams building LLM applications, general-purpose cloud services — log services, monitoring and alerting, object storage, and similar offerings from providers such as Baidu AI Cloud — can help you observe and govern call volume and token consumption, keeping cost within a predictable range. Once you have a grip on tokens as the model’s unit of account, you understand the underlying logic of the trade-offs large models make between efficiency and cost.
