What Is a Token? From Text Segmentation to Agent Cost Management
This article explains what a token means in large language model applications, how tokenization affects token counts, how tokens relate to context windows, input and output pricing, multi-turn conversation costs, and agent execution costs. It also covers practical methods for measuring token usage, engineering practices for cost control, and safety constraints for data analysis tasks.
1. What Is a Token? Defining the Scope
Token has different meanings in different technical fields. In identity authentication, it usually refers to a credential used to prove access rights. In blockchain, it can represent a digital asset or right on a chain. This article discusses tokens in artificial intelligence, where the term is often translated into Chinese as “ciyuan,” roughly meaning “word element.”
For a text large language model, a token is the basic unit produced when a tokenizer converts input text into a sequence that the model can process. A token may correspond to a complete word, part of a word, a Chinese character, punctuation, a whitespace combination, or another text fragment.
A simplified flow can help illustrate the idea:
Raw text → tokenizer segmentation and encoding → token ID sequence → model computation → output token sequence → decoding into text
The model does not process the complete sentence as a human sees it. It processes the encoded ID sequence. Those IDs are further converted into vector representations and participate in model computation. Therefore, tokens affect both how text enters the model and how context capacity and service usage are measured.
It is important to note that a token is not a strict synonym for a word, nor is it a fixed conversion unit for characters or bytes.
2. How Tokens Are Formed: Why the Same Sentence Can Have Different Counts
1. The tokenizer determines segmentation
A tokenizer usually represents text as a series of recognizable fragments based on a prebuilt vocabulary and segmentation rules. Common approaches treat high-frequency text fragments as relatively complete units and split uncommon content into finer pieces.
For example, a common English word may correspond to only one token, while a longer or less common word may be split into multiple tokens. A Chinese phrase may sometimes be encoded as a whole and sometimes split by individual characters or at a finer granularity.
The examples here are only for explaining the mechanism. They do not represent the actual segmentation results of any specific model. Accurate counts must be based on the tokenizer corresponding to the target model.
2. “One token is roughly equal to one Chinese character” is only a rough estimate
Understanding a token as “one Chinese character, one punctuation mark, or one English word” can help with initial intuition, but it is not suitable as a basis for cost budgeting or program control.
Reasons include:
- One Chinese character may correspond to one or more tokens.
- Multiple characters may together form one token.
- Spaces may be encoded together with adjacent text rather than counted independently.
- Line breaks, special symbols, code, and long numeric strings may produce different segmentation results.
- Different models use different vocabularies, so the same passage may have different token counts.
Therefore, the same character count does not mean the same token count, and the same information content does not mean that different language versions will have the same token count.
3. Is Chinese always more expensive than English?
It is not valid to treat “Chinese consumes a fixed percentage more tokens than English” as a universal rule.
Differences between languages are affected by vocabulary coverage, training corpora, text domain, and expression style. Even when the same meaning is expressed, changes in translation length affect the final count.
A more reasonable approach is to select real business samples and compare token counts, answer quality, and overall cost under the same model and the same task requirements, rather than comparing only the language of the input text.
Forcing translation to reduce tokens may also cause terminology drift and information loss. For Chinese-language business content, removing duplicate content and clarifying task boundaries is usually more reliable than simply changing the language.
3. How Tokens Relate to the Context Window
The context window is the token capacity constraint for a single model request. It differs from the word count of an article, and the specific calculation basis should follow the documentation of the service being used.
A single request may include:
- System instructions and application rules;
- The current user question;
- Historical conversation resent by the application;
- Retrieved document fragments;
- Tool definitions and tool execution results;
- Space reserved for the model’s answer.
Some services also set separate limits for input length and output length. Therefore, it is not enough to check whether the user question is short. The entire request must also satisfy the limits.
For example, the user may currently ask only one sentence, but the application may also attach a large amount of history and documents, so the actual input can still be very long.
When context capacity is insufficient, methods such as truncation, segmentation, retrieval filtering, or history summarization can be used. However, any compression may lose information. Facts, constraints, and conclusions directly relevant to the current task should be prioritized.
In addition, supporting a longer context does not mean the model can use every piece of information in it with equal accuracy. Irrelevant content, repeated material, and contradictory descriptions in long input can all reduce task quality.
4. Why Model Costs Distinguish Input and Output
In metered model services, input tokens and output tokens are usually counted separately and may have different prices. Actual prices, caching rules, and other fees should be checked in the billing documentation of the service being used.
A simplified cost formula is:
Total cost = input tokens ÷ billing unit × input unit price
- output tokens ÷ billing unit × output unit price
Assume a service uses one million tokens as the billing unit, with an input price of RMB 2 and an output price of RMB 6. A request has 12,000 input tokens and 2,000 output tokens:
Input cost = 12,000 ÷ 1,000,000 × 2 = RMB 0.024
Output cost = 2,000 ÷ 1,000,000 × 6 = RMB 0.012
Total cost = RMB 0.036
The prices above are only calculation examples and do not correspond to any actual service.
Many services charge more for output than for input. One reason is that text generation usually proceeds step by step and has computational and scheduling characteristics different from input processing. However, this is not a pricing rule that every service must follow.
If a service uses separate accounting for cached input, reasoning processes, or other processed items, those should also be counted separately. All costs should not be mechanically attributed to the visible answer.
For multimodal tasks, note that images, audio, and video may each have their own measurement methods. Text character estimation methods should not be directly applied to them.
5. Why Multi-Turn Conversations Become More Expensive
A model usually cannot automatically obtain all historical information in an application solely from a session identifier. To help the model understand previous exchanges, the application often needs to resubmit relevant historical messages in subsequent requests or submit a summarized history.
This means the same historical content may repeatedly become input across multiple requests.
The input for the k-th turn can be approximated as:
k-th turn input = fixed rules + current question + retained history + external materials
If all history is retained in every turn, the single-turn input gradually grows as the conversation progresses, and the cumulative input for the entire session may grow significantly faster than the number of turns.
Therefore, the “length of the new question” in a chat window cannot represent the actual consumption of that call.
Common optimization methods include:
- Keep only the most recent several turns of detailed conversation.
- Organize earlier content into a structured summary.
- Store user preferences, confirmed facts, and unfinished items separately.
- Remove duplicate references and irrelevant tool outputs.
- Start a new context after a task ends to avoid unlimited appending.
Summarization is not a free operation and may omit details. For tasks such as contract clauses, numerical analysis, or exact citations, retrievable original materials should be retained rather than relying only on summaries.
6. Why Agents May Consume Large Amounts of Tokens
Ordinary question answering often requires only one model call. An agent may instead perform multiple rounds of “judge—act—observe—judge again” around a goal.
For example, completing a financial data organization task may require:
Define the time range → collect candidate materials → read the main text → judge relevance → deduplicate → extract facts → cross-check → generate a report → execute a sending action
Some of these steps can be completed directly by deterministic programs and do not necessarily require model involvement. However, if every step calls the model and each call includes a large amount of history and raw material, cumulative token consumption will grow rapidly.
1. Repeated reading is often the real cost driver
In each round, the agent may re-read the task description, existing plan, tool definitions, historical execution records, and document body. Even if the final report is only a few hundred words, the cumulative input behind it may be very large.
Therefore, the final output length cannot represent the total task cost.
2. Retries and loops amplify consumption
Irrelevant search results, page read failures, abnormal data formats, or unclear judgment conditions can all trigger retries.
If stop conditions are missing, the system may loop among repeated searches, repeated verification, and repeated rewriting. High consumption sometimes reflects problems in execution design rather than task complexity.
3. Large tool results can also increase costs
A tool may return an entire page, a complete table, or a large amount of logs. If these results enter the model without filtering, the context will be occupied quickly.
A more reasonable approach is to first perform body extraction, field filtering, structured transformation, and duplicate content removal, and then pass the necessary information to the model.
The consumption of one agent task cannot be used to infer the costs of all agents. Tool capabilities, data scale, number of calls, and context management strategies all significantly affect the result.
7. How to Accurately Measure Token Consumption for a Task
1. Estimate before the request
Use a tokenizer that matches the target model to estimate the complete text to be submitted. Do not count only the user question. Rules, history, documents, and tool descriptions should also be considered.
Local estimation is suitable for capacity checks and budget alerts. However, if the server side adds additional wrappers, the estimate may differ from the final count.
2. Verify after the request
If the model service provides usage statistics, record the input, output, and other applicable billable items for each call, and reconcile them against the actual billing basis.
3. Aggregate by task
For an agent, one user task may correspond to dozens of requests. Both “per-call usage” and “cumulative task usage” should be retained. Looking only at the statistics for the final answer is not enough.
Recommended fields to record include:
- Task identifier and call order;
- Execution stage;
- Input and output token counts;
- Call latency;
- Whether a retry occurred;
- Cost of the current call;
- Task success status.
When sensitive data is involved, monitoring records should prioritize usage and necessary metadata. Complete prompts, personal information, or business documents should not be indiscriminately stored.
8. Engineering Practices for Cost Control
1. Reduce invalid context first
Remove duplicate rules, irrelevant documents, and redundant examples. Filter retrieved materials for relevance first instead of sending all results directly to the model.
For table tasks, sorting, filtering, and aggregation can first be computed programmatically, and then the model can explain the results. Deterministic computation should not repeatedly be assigned to the model.
2. Set clear task boundaries
Task descriptions should include the time range, data scope, output format, and completion conditions.
“Continuously collect all important information” is difficult to judge as complete. “Extract up to ten relevant items within a specified time range, and label source time and uncertain items” is easier to execute and verify.
3. Distinguish application-level budgets from model output limits
A model output length limit can constrain only one answer. It cannot directly limit the cumulative input, retry count, and tool costs of an entire agent task.
The application should also set controls such as maximum call count, cumulative budget, timeout, and repeated failure count. These are application design mechanisms and should not be mistaken for parameters with the same name provided by all models.
4. Allocate model capability by task difficulty
Clear classification, field extraction, and format organization can use lower-cost processing paths. Complex reasoning and verification of key conclusions can then use stronger model capabilities.
However, any tiering strategy needs to be evaluated with real samples. If lower-cost calls lead to more retries, the final result may not be cheaper.
5. Measure quality and cost together
Enterprise applications should not focus only on the “price per million tokens.” They should also consider:
- Average cost per successful task;
- Task completion rate;
- Output accuracy;
- Average response time;
- Human review cost;
- Failure and retry ratio.
A low-cost solution with frequent failures may have a higher overall business cost than a solution that completes the task in one pass.
9. What Safety Constraints Do Data Analysis Tasks Need?
When an agent reads local files, retrieves external information, or sends reports, it needs permissions and data quality controls in addition to a token budget.
For tables containing sensitive information, the read scope should be limited, and only fields necessary to complete the task should be submitted. When sending emails, modifying files, or performing other external actions, human confirmation steps should be set according to risk.
Content from external webpages and documents should be treated as data to be analyzed, not as content that automatically receives instruction authority. Otherwise, malicious text in the material may induce the system to deviate from the user’s goal.
For financial analysis, data dates, units, and metric definitions should also be clarified. Stock prices, valuation metrics, and return-related data may come from different points in time and cannot be directly mixed and compared without verification.
Model-generated conclusions should not be treated as facts merely because they are fluent. Key numbers, sources, and judgment basis need to be traceable, and uncertain information should be clearly labeled.
10. Conclusion: Token Is Fundamental to Understanding LLM Usage Costs
Tokens connect text encoding, context capacity, call billing, and task execution. Understanding them depends on three key points:
First, there is no universal character-to-token conversion ratio. Accurate counting requires the specific tokenizer and the usage basis of the service.
Second, the cost of a call comes not only from the current question and final answer, but also potentially from historical messages, system rules, retrieved materials, and tool results.
Third, agent cost depends on the execution process. Repeated reading, invalid retries, and missing stop conditions are often more important than final output length.
For individual users, defining the question scope, reducing irrelevant materials, and constraining output format are direct and effective optimizations. For developers and enterprises, the focus should be on management mechanisms that record per call, aggregate per task, and evaluate by quality. The goal is not simply to reduce tokens, but to complete tasks reliably at a controllable cost.
