What Is a Tokenizer: How Text Becomes Model-Readable Tokens

A Tokenizer segments text and maps it into numeric sequences that models can process; the segmentation result directly determines input usage, context occupancy, and billing. This article explains the three steps from characters to Token IDs, differences in Token density across Chinese, English, and code, trade-offs among common tokenization algorithms, and methods to measure Token counts for your own text, helping developers understand why cost estimates based on character counts are often inaccurate.

Tokenizer workflow diagram: text normalization, subword segmentation, mapping to Token IDs, and context accounting

Definition

A Tokenizer is a component that segments text and maps it into numeric sequences that models can process; the segmentation result directly determines input usage, context occupancy, and billing.

Tokenizer · Tokenizer, tokenization component, text segmentation component

What Is a Tokenizer: One-Sentence Definition and Workflow

A Tokenizer is a component that segments text and maps it into numeric sequences that models can process; the segmentation result directly determines input usage, context occupancy, and billing. Models receive numeric tensors rather than characters, so a passage must first go through three steps—normalization, subword segmentation, and ID mapping—before entering the model; during generation, the same Tokenizer converts IDs back into readable text. Understanding these three steps explains why cost estimates based on character counts are almost always inaccurate. This article's scope is as of December 2, 2026; specific parameters are subject to the AGTCloud Model Library display.

Step

What it does

Impact on usage

Text normalization

Unify case forms, whitespace, and Unicode representations

Redundant blank lines and invisible characters also occupy positions

Subword segmentation

Split text into subword units according to the vocabulary

Determines how many Tokens a passage corresponds to

ID mapping

Map subwords to integer IDs and add special tokens

Start/end markers and role markers are also counted in usage

The third step is often overlooked: role markers, system prompts, and message boundaries in conversational APIs also consume Tokens. In multi-turn conversations, historical messages appear repeatedly, so this overhead accumulates with turns regardless of body text length.

What steps are involved from characters to Token IDs?

Take a sentence that mixes Chinese and English as an example: the Tokenizer first performs normalization, then splits the string into subword units according to the vocabulary, and finally looks up the vocabulary to obtain a sequence of token IDs. The segmentation boundaries do not correspond to Chinese characters or English words; they are determined by high-frequency fragments counted during training.

Why segmentation results are neither characters nor words

Splitting by character makes the sequence too long and gives each token ID weak semantics; splitting by word encounters vocabulary explosion and out-of-vocabulary problems. The subword approach is a compromise: high-frequency words are kept as whole units, while low-frequency words are split into common fragments. Therefore, 'one token' may be a word, a Chinese character, half a word, or merely a punctuation mark or a piece of indentation. This is the root cause of why estimation formulas are hard to justify.

The vocabulary is built from statistics on the training corpus, so models with different languages and corpus distributions have different segmentation preferences. The same Chinese text can have noticeably different token counts on a multilingual-oriented model versus a Chinese-optimized model.

Differences in token density among Chinese, English, and code

The table below gives empirical magnitudes to illustrate structural differences, not exact conversion rates; specific results must be based on the measured output of the target model's Tokenizer.

Content type

Common segmentation characteristics

Empirical magnitude

Verification method

Chinese prose

Common Chinese characters are mostly independent units; high-frequency words may be merged

One Chinese character corresponds to about 1–2 tokens

Send a sample request and read usage

English prose

Common English words are mostly 1 token; long words are split into several fragments

Counting by word is usually fewer than counting by character

Same as above; do not divide character count by a fixed coefficient

Code and indentation

Identifiers, symbols, and spaces are segmented separately

Code with the same number of characters often uses more tokens than prose

Measure real code snippets

JSON and structured output

Key names, quotation marks, and brackets are all counted

Redundant formatting significantly increases the output segment

Compare after simplifying the output format

Punctuation and whitespace

They also occupy token ID positions

Blank lines in templates accumulate

Compress prompt templates

The biggest impact on cost is 'different structures with the same character count': two texts with the same number of characters, one Chinese prose and one indented JSON, can differ in token count by more than 2 times. If a budget table only multiplies character count by a coefficient, this kind of difference is completely smoothed out.

How the Tokenizer determines API cost and context usage

Billing and the context window are both measured in tokens, so the segmentation result determines two things at once: how much this call costs and how much content can still fit. The calculation formula for a single call is as follows, where P_in / P_out are the input and output unit prices (yuan per million tokens), read in real time from the model library; this article does not hard-code them.

单次成本 = (输入Token数 × P_in + 输出Token数 × P_out) / 1,000,000
窗口占用 = 系统提示 + 检索片段 + 历史消息 + 用户输入 + 预留输出

说明:输入与输出分开计数,因为单价不同;特殊标记与角色标记计入输入段
示例:输入 4,000 Token、输出 200 Token 的任务,与输入 200 Token、输出 4,000 Token
      的任务,总 Token 数接近,成本结构却完全不同

Aspect

Part determined by the Tokenizer

Controllable by engineering?

Input usage

Total segmentation count of prompts, retrieved snippets, and history

Controllable: compress context, simplify templates

Output usage

Total number of token IDs in generated text

Controllable: set limits, constrain format

Whether the window overflows

Whether the total number of input IDs exceeds the context length

Controllable: sliding window, summarize history

Unit price

Not affected by the Tokenizer

Determined by the model service

Segmentation rules themselves

Determined by the model vocabulary

Not controllable, but can be measured

The last row is worth emphasizing: switching models means switching vocabularies. Before switching, re-measure the token distribution on 20–50 representative samples; do not reuse the estimation coefficients from the old model.

Why the context window is counted in tokens rather than characters

Because the model actually processes token ID sequences, and the number of positions in attention computation is determined by the number of IDs. The window length is an upper limit on IDs, not on characters. When designing long-document scenarios, first estimate the input by tokens, then reserve space for output; if the window is full, the system usually truncates or rejects the request rather than automatically compressing the content.

Comparison of common tokenization algorithms

Different model series use different segmentation algorithms; understanding the differences helps explain why the same text uses different amounts on two models. The table below compares methods only and does not involve implementation details or benchmark scores of any specific model.

Algorithm

Basic idea

Characteristics

Common impact

BPE

Starts from characters and repeatedly merges the highest-frequency adjacent fragments

Vocabulary size is controllable; robust to out-of-vocabulary words

Better compression ratio for English and code

WordPiece

Selects fragments to merge by likelihood gain

Subword boundaries are finer

Long words are split into more fragments

Unigram

Starts from a large vocabulary and gradually removes low-contribution units

Can provide probabilities for multiple segmentations

The same text may have multiple segmentations

SentencePiece

Processes raw text directly as a sequence

Does not rely on language-specific pre-tokenization

Common in multilingual scenarios

Character-level / byte-level

Uses characters or bytes as the smallest units

No out-of-vocabulary problem

Longer sequences and higher usage

These algorithms have no absolute advantages or disadvantages; they are trade-offs among compression ratio, vocabulary size, multilingual coverage, and robustness. For users, the conclusion is only one: segmentation rules belong to model implementation and cannot be assumed to be universal across models.

How to measure the token count of your own text

The most reliable method is not to find a conversion table, but to send a sample request and read the returned usage. The structure below corresponds to the usage fields of OpenAI-compatible APIs; please verify specific field names in the developer documentation to verify.

samples = load_representative_texts()      # 20~50 条真实样本
for text in samples:
    resp = client.chat.completions.create(
        model=model,
        messages=[{'role': 'user', 'content': text}],
        max_tokens=1,                         # 只需输入段用量
    )
    u = resp.usage
    report.append({
        'chars': len(text),
        'input_tokens': u.prompt_tokens,
        'ratio': u.prompt_tokens / len(text),
    })
# 输出:ratio 的分布,而不是一个固定系数
# 分别按 中文 / 英文 / 代码 / JSON 分组统计

Setting max_tokens to 1 makes the output segment barely interfere with measurement, letting you focus on obtaining input usage. The truly useful result is not the average, but the distribution grouped by content type: the proportions of Chinese, English, code, and JSON often differ greatly; using a single coefficient would lump these four categories together.

Why estimation formulas are unreliable

Because tokenization results are jointly affected by the vocabulary, language, symbol density, and template format, and the vocabulary may also change when the model is upgraded. Empirical coefficients only hold approximately under narrow conditions where the sample distribution is stable, the model does not change, and the format is fixed. If any one of these changes, the estimate will be systematically biased—once call volume rises, this bias directly turns into billing differences.

Therefore, estimation tables should note the measurement date, target model, and sample composition, and be re-measured regularly. Treat them as versioned engineering data, not as common knowledge that can be reused long term.

Relationship between Tokenizer and related concepts

Concept

Relationship with Tokenizer

Further reading

Token

The basic unit after tokenization, and the measurement unit for billing and context windows

On-site encyclopedia entries related to 'Token billing'

Context window

The positional limit measured in tokens, including input and reserved output

Context parameters in the model library

Prompt caching

Reuses computation results for stable prefixes, with prefixes compared by token sequence

Cache documentation in the developer docs

API cost

Input and output tokens are multiplied by their respective unit prices

On-site article 'API cost breakdown'

Model quantization

Changes the numerical representation of weights without changing tokenization rules

On-site article 'What is model quantization'

The most easily confused pair is quantization and tokenization: the former acts on model weights, while the latter acts on text input, and neither changes the other's rules. Once you understand this, you will not mistake 'the model became lighter' for 'the same text uses fewer tokens'.

Common misconceptions about Tokenizer

Common statement

Why it is inaccurate

More accurate statement

'Tokens are just character count divided by a coefficient'

Tokenization is jointly affected by vocabulary, language, symbols, and format

Measure the distribution for the target model by content type

'All models use the same tokenization rules'

Vocabularies change with model series and training corpora

Re-measure samples when switching models

'Punctuation and blank lines do not consume tokens'

After normalization, they are still mapped to IDs

Simplifying templates can reduce this overhead

'When the context window is full, it will be automatically compressed'

It usually results in truncation or request rejection

Plan input by tokens and reserve output

'Tokenizer affects model price'

Price is set by the service provider; tokenization only affects usage

Read unit prices from the model library and measure usage empirically

What these misconceptions have in common is treating a quantity determined by a specific implementation as a universal constant. Any estimate involving tokens should be grounded in three limiting conditions: which model, what type of text, and when it was measured.

Verify usage on AGTCloud

In the developer docs after confirming the request structure and usage fields, you can go to the console to send a sample request and compare the returned input and output tokens with your estimation table; the context lengths and related parameters for different models are consolidated in the AGTCloud model library for viewing; you do not need to copy them into articles or code.

According to the Step-5 launch announcement published by AGTCloud on December 1, 2026, the model's overall intelligence index increased by 11 points to 40 points, total output tokens decreased by about 38%, and the equivalent API cost decreased by 36%. This kind of change comes from the inference process rather than tokenization rules, which illustrates that 'usage' and 'model efficiency' are two independent variables and should be attributed separately.

Keeping the method in the content and leaving variable parameters in the model library is the prerequisite for this batch of encyclopedic content to be cited stably over the long term by AI engines: when the next model update comes, the article will not become outdated information.

Frequently asked questions

Models process numeric tensors, so text must first be converted into sequences of IDs. A Tokenizer normalizes raw text, segments it into subword units according to a vocabulary, and maps those units to integer IDs; when the model outputs IDs, it converts them back into text. This step determines how many positions a passage occupies, directly affecting input usage, how much content fits in the context window, and the Token count used for billing.

Source

Related reading

L

Lin Zhiyuan

LLM Research

AGTCloud columnist on large model technology, focusing on large language models, reasoning models, multimodal generation, and model capability evaluation. Mainly provides technical interpretation and application analysis of the technical characteristics, applicable scenarios, and selection methods of models such as DeepSeek, Tongyi Qianwen, and Doubao.