What Is a Token? Understanding LLM Tokenization, Context Windows, and Costs

    Tokens determine how large language models process text, how much context they can handle, and how usage is billed. This guide explains tokenization, input and output tokens, cost calculations, usage estimation, and practical ways to manage token consumption without compromising application quality.

    1. Tokens Are Model Processing Units, Not Characters or Words

    When working with large language models (LLMs), it is tempting to treat a token as a character or a word. That assumption is not accurate.

    A token is a basic unit of text that a language model reads and generates. Rather than processing text exclusively as complete sentences, natural-language words, or individual characters, the model first uses a tokenizer to split the text into tokens. Those tokens are then mapped to numerical IDs that the model can process.

    Consider a short request:

    1. Please help me analyze this log.

    A tokenizer might split it into words, word fragments, punctuation, or combinations of these. The exact segmentation depends on the tokenizer’s vocabulary and encoding rules. Different models may use different tokenizers, so the same text can produce different token counts.

    The input process can be simplified as follows:

    1. Raw text
    2. ↓
    3. Tokenizer segmentation
    4. ↓
    5. Token sequence
    6. ↓
    7. Numerical IDs
    8. ↓
    9. Model computation

    Text generation follows roughly the reverse process:

    1. Model predicts the next token
    2. ↓
    3. Tokens are generated sequentially
    4. ↓
    5. Tokenizer decodes the sequence
    6. ↓
    7. Human-readable text

    A token is therefore a unit used internally to process language, not a fixed unit of human language.

    2. How Tokens Relate to Chinese Characters and English Words

    Chinese: One Character Does Not Necessarily Equal One Token

    In Chinese text, a character may correspond to one token, but multiple characters may also form a single token. Some characters, punctuation marks, or unusual strings may be split into smaller units.

    Common expressions may be represented as whole words or larger fragments in the tokenizer’s vocabulary. Less common words, technical terms, uncommon names, and mixed-character strings may be broken into smaller pieces.

    As a result, “1,000 Chinese characters equals 1,000 tokens” is, at best, a rough estimate—not an exact count.

    English: Tokens Often Represent Word Fragments

    English tokenization commonly involves words, word fragments, and punctuation. A common word may correspond to one token, while a longer or less familiar word may require several.

    A technical term might be split into fragments resembling:

    1. Prefix + root + suffix

    Code, file paths, URLs, long numbers, and random strings can produce relatively high token counts because they may contain fewer common language patterns.

    Code Is Not Necessarily More Token-Efficient Than Prose

    Code contains parentheses, commas, quotation marks, indentation, operators, and variable names. Although code is structured, many identifiers are uncommon strings that can be split into multiple tokens.

    Content that can increase token usage includes:

    • Very long variable names;
    • Randomly generated identifiers;
    • Large blocks of repeated configuration;
    • Minified, single-line code;
    • Encoded data;
    • Log timestamps, request IDs, and stack traces;
    • Large amounts of whitespace, line breaks, and formatting characters.

    Character count alone is therefore not enough to determine how many tokens a code-related request will consume.

    3. Input Tokens and Output Tokens

    An LLM request generally involves two categories of tokens: input tokens and output tokens.

    Input Tokens

    Input tokens represent the content sent to the model, including:

    • System instructions;
    • The user’s question;
    • Conversation history;
    • Reference material;
    • Tool results;
    • Structured parameters;
    • Code and logs.

    Applications often focus only on the latest user message and overlook conversation history or system instructions. In practice, the total input count usually includes all of these components.

    For example:

    1. System instructions: approximately 500 tokens
    2. Conversation history: approximately 3,000 tokens
    3. Current question: approximately 200 tokens
    4. Reference material: approximately 5,000 tokens

    The request contains approximately 8,700 input tokens—not just the 200 tokens in the current question.

    Output Tokens

    Output tokens are the tokens generated by the model. Longer responses generally use more output tokens.

    The output token count is not the same as the number of visible characters. Chinese, English, numbers, code, and punctuation are tokenized differently.

    Setting a large maximum output length does not mean the model will use the entire allowance. The actual output length can depend on:

    • Task complexity;
    • Required output format;
    • Instruction detail;
    • Whether explanations are requested;
    • Whether code is generated;
    • Whether tables or structured data are required;
    • The model’s stopping conditions;
    • The maximum output token limit.

    4. What Is a Context Window?

    A context window is the total token capacity a model can handle in a single request. It typically includes both input and output tokens, not just the user’s question.

    A useful planning relationship is:

    1. Input tokens + reserved output tokens ≤ context window

    If a model has a context capacity of N tokens and the request already contains M input tokens, the theoretical remaining space for output is approximately:

    1. N - M

    If the input becomes too long, possible outcomes include:

    1. The request is rejected.
    2. Conversation history is truncated.
    3. The available output length is reduced.
    4. The application automatically drops older messages.
    5. The model cannot fully use all the supplied material.

    Long conversations, knowledge-base question answering, code analysis, and document summarization therefore require management of both input size and output size.

    5. How Tokens Affect LLM Costs

    LLM services commonly meter input and output tokens separately. A basic cost formula is:

    1. Total cost =
    2. Input token count × input price per token
    3. +
    4. Output token count × output price per token

    If prices are quoted per million tokens, the calculation becomes:

    1. Input cost = input tokens ÷ 1,000,000 × input price per million tokens
    2. Output cost = output tokens ÷ 1,000,000 × output price per million tokens

    For a hypothetical example, assume a request contains 20,000 input tokens and 3,000 output tokens. If the input rate is CNY 5 per million tokens and the output rate is CNY 15 per million tokens:

    1. Input cost = 20,000 ÷ 1,000,000 × 5 = CNY 0.10
    2. Output cost = 3,000 ÷ 1,000,000 × 15 = CNY 0.045
    3. Total cost = CNY 0.145

    Always check the provider’s published billing terms. Pricing can vary by model, region, service type, and time. Published rates are useful for estimates, but they do not replace the actual bill.

    6. Why Responses of the Same Length Can Cost Different Amounts

    There is no fixed answer to the question, “How much does it cost to generate 1,000 characters?” Several factors affect the result.

    Token Density Varies by Language and Content Type

    A Chinese article, an English article, a code snippet, and a numeric table can produce different token counts even when each contains 1,000 visible characters.

    Plain Chinese prose may have a relatively consistent token density within a given tokenizer, but technical documents, code, logs, and mixed-language text can vary substantially.

    Input Content Also Contributes to the Bill

    Counting only the generated response overlooks the input cost.

    For example, asking a model to produce a 1,000-character summary of a long document may involve:

    • A system prompt;
    • Task instructions;
    • A 10,000-character source document;
    • Conversation history;
    • The generated 1,000-character summary.

    In this case, the input cost may exceed the output cost.

    Multi-Turn Conversations Can Reprocess History

    Many conversational applications include earlier messages in each new request. As the conversation grows, the input token count per request can increase.

    For example:

    1. Turn 1: 1,000 input tokens
    2. Turn 2: 2,000 input tokens
    3. Turn 3: 3,000 input tokens
    4. ...

    Even if each new question is short, the cumulative token consumption can become substantial.

    7. How to Estimate Token Counts

    Method 1: Use the Target Model’s Tokenizer

    The most accurate way to count tokens in a piece of text is to encode it with the tokenizer used by the target model and count the resulting tokens.

    The following pseudocode illustrates the process:

    1. text = "Text to count"
    2. tokens = tokenizer.encode(text)
    3. count = len(tokens)
    4. print(count)

    Here, tokenizer represents the tokenizer that matches the target model. A count obtained for one model should not automatically be treated as valid for another.

    Method 2: Estimate from Character Count

    When a tokenizer is unavailable, text type can provide a rough basis for estimation:

    • Chinese text: Token counts may be close to character counts, but they are not necessarily equal.
    • English text: Token counts are generally lower than character counts, although long words and technical terminology can increase usage.
    • Code and logs: Use a more conservative estimate.
    • Mixed Chinese and English text: Estimate each portion separately where practical, then combine the results.
    • Numbers and special symbols: Allow additional room.

    For planning, consider a safety margin of approximately 1.2 to 1.5 times the estimated count. This can reduce the risk of exceeding limits because the actual tokenization differs from the estimate.

    Method 3: Record Actual Usage by Request

    In production, actual usage records are more reliable than continued reliance on estimates.

    Useful fields include:

    • Request ID;
    • Model name;
    • Input tokens;
    • Output tokens;
    • Total tokens;
    • Request duration;
    • Response status;
    • Business use case;
    • Estimated cost.

    These records support analysis of average request cost, peak costs, and the share of spending attributable to each application feature.

    8. Practical Ways to Reduce Token Consumption

    Reduce Unnecessary Conversation History

    Avoid carrying the complete conversation indefinitely. Periodically summarize older messages and retain only information relevant to the current task.

    For example, ten rounds of detailed discussion might be condensed into:

    1. Project objective:
    2. Agreed approach:
    3. Open questions:
    4. Key constraints:
    5. Latest conclusions:

    This preserves useful context while reducing repeated content.

    Optimize System Prompts

    System prompts should be clear, consistent, and reusable. Avoid repeated instructions and irrelevant background.

    Common sources of inefficiency include:

    • Restating the same rule several times;
    • Including examples unrelated to the task;
    • Adding excessive conversational boilerplate;
    • Giving contradictory constraints;
    • Repeatedly transmitting fixed reference material.

    Use templates for stable rules and keep dynamic content separate.

    Process Long Documents in Chunks

    Rather than sending an entire long document in one request, consider a staged workflow:

    1. Clean the document
    2. ↓
    3. Split by section or semantic boundary
    4. ↓
    5. Summarize each chunk
    6. ↓
    7. Combine intermediate results
    8. ↓
    9. Generate the final answer

    Keep chunks semantically coherent. Avoid arbitrary cuts in the middle of sentences or code structures.

    Retrieve Relevant Content Before Generation

    For large knowledge bases, retrieve passages relevant to the user’s question and send those passages to the model instead of including the entire collection.

    The number of retrieved passages still needs to be controlled. Excessive retrieval can increase cost and introduce irrelevant information that reduces answer accuracy.

    Limit Unnecessary Output

    If a task requires only a structured result, do not ask for a lengthy explanation.

    For example, a classification task can use a fixed output format:

    1. {
    2. "category": "Category",
    3. "confidence": 0.92,
    4. "reason": "Brief explanation"
    5. }

    Clear output requirements make response length easier to control and simplify programmatic parsing.

    9. Token Cost Management for Enterprise Applications

    Token management should not depend solely on individual developers’ judgment. Production systems need a consistent governance process.

    Set Per-Request Limits

    Define input and output limits by use case. Customer support, summarization, code analysis, and data extraction typically have different requirements and should not automatically share the same limits.

    Apply User- and Application-Level Quotas

    Track usage by user, department, application, or project. Quotas can help prevent malfunctioning programs or repeated calls from rapidly increasing costs.

    Monitor Unexpected Growth

    Watch for patterns such as:

    • A sudden increase in input tokens per request;
    • Responses consistently approaching the output limit;
    • Repeated submission of the same request within a short period;
    • Continuously expanding conversation history;
    • Large numbers of failed requests and retries on an endpoint;
    • Daily token usage deviating from historical levels.

    Logging, alerts, and cost analysis can help identify the source of these changes.

    Evaluate Changes Offline

    Reducing token consumption should not come at the expense of application quality.

    After shortening prompts, reducing context, or restricting output, use a fixed evaluation set to check:

    • Whether answer accuracy has declined;
    • Whether important information is missing;
    • Whether output formatting remains consistent;
    • Whether long-document tasks omit relevant material;
    • Whether user satisfaction is affected.

    10. A Practical Understanding of Tokens

    Tokens connect three aspects of LLM applications: text representation, context capacity, and usage cost.

    Four principles are especially important:

    1. A token is not equivalent to a character or a word.
    2. Both input and output content may contribute to billing.
    3. Context capacity typically depends on both input and output length.
    4. Effective cost optimization means removing unnecessary information, managing context size, and improving the useful information density of each request—not simply making every prompt shorter.

    For individual developers, understanding tokens supports better prompt design and more predictable spending. Enterprise teams also need usage tracking, quotas, cost monitoring, and quality evaluation.

    As applications expand from simple question answering to knowledge-base retrieval, customer support, code analysis, and automated workflows, token management becomes part of system architecture rather than just an estimation task. Combining text organization, context management, model selection, and cost monitoring helps keep LLM applications reliable, controllable, and sustainable without sacrificing their effectiveness.