Token Metering and Cost Management: A Practical Guide to LLM Usage

    This article provides a comprehensive guide to managing Large Language Model (LLM) usage and costs. It covers the definition of tokens, how tokenization works, metering differences between input and output, quota conversion logic, practical methods for estimating usage, engineering practices for usage governance, and key checkpoints for procurement and model selection.

    1. Definition of Tokens

    When processing text, Large Language Models (LLMs) do not directly use characters or words as units. Instead, the model first splits the input into a sequence of discrete fragments, each called a token. The model encodes, computes, and generates output token by token, so the number of tokens directly determines the computational load, response latency, and resource consumption. In engineering terms, tokens can be understood as the unit of computational workload for the model.

    Whether prompting the model to write copy, organize meeting notes, generate code, or write text descriptions, tokens are consumed at the underlying level. The token consumption of a single API call consists of two parts: input (prompts, context, etc.) and output (content generated by the model). Understanding this is the prerequisite for estimating costs.

    2. How Tokens are Tokenized

    Tokenization is handled by a tokenizer. A common approach is subword algorithms like Byte Pair Encoding (BPE): high-frequency character combinations are merged into a single token, while low-frequency content is split into smaller fragments. Therefore, for text of the same length, the number of tokens will vary depending on the language, symbols, and format.

    • In English, one word usually corresponds to one token, though rare or compound words may be split into multiple tokens.
    • In Chinese, characters are the basis, and one character typically corresponds to one or two tokens, depending on the model’s vocabulary.
    • Symbols and indentation in code, JSON, and tables also consume tokens; structured data often consumes more tokens than natural language.
    • Whitespace characters and line breaks are also counted; redundant formatting will increase usage.

    Different models may use different tokenizers, meaning the same text might yield a different token count across two models. For precise billing or context window management, rely on the counting results provided by the specific model. The estimation methods below are only for preliminary assessment.

    3. Metering Differences Between Input and Output

    Many services meter input and output separately, and the unit prices for the two may differ. The output unit price is often higher than the input unit price, so both types of tokens must be recorded separately during tracking.

    In multi-turn conversations, historical messages are usually sent with each request, causing input tokens to accumulate with each turn. Assuming each turn adds about t tokens, the input size of the n-th request is approximately n*t, and the cumulative input total for the first n turns is roughly t*n(n+1)/2. As turns increase, total consumption grows faster than linearly, which is one of the main reasons why long conversation costs exceed expectations.

    System prompts, tool definitions, and retrieved reference materials also count towards the input. Many teams only focus on the length of the user’s question but ignore these fixed overheads, leading to budget deviations.

    4. Conversion Logic for Token Quotas

    Tokens are not intuitive to general users. It is difficult for users to determine how many tokens a request will consume, so service providers often convert tokens into credits, membership durations, or quota packages, allowing users to consume based on their quota. This lowers the barrier to entry and facilitates unified tracking.

    When it comes to the conversion method, two points need to be verified. First, whether the conversion ratio is transparent, including how many tokens correspond to one credit and whether input and output are deducted at the same ratio. Second, whether the quota’s validity period, refund rules, and usage details can be queried. Developers and enterprise users should include these rules in their evaluation checklist before purchasing.

    5. Practical Methods for Usage Estimation

    Estimation is done in three steps: count input tokens, estimate output tokens, and apply the unit price to calculate the cost. The example below uses rough empirical coefficients, suitable for preliminary budgeting, but cannot replace the official count from the model. The prices in the example are placeholder parameters; actual costs are subject to the provider’s price list.

    1. def estimate_tokens(text: str) -> int:
    2. """Roughly estimate the number of tokens. Chinese characters use an empirical coefficient of about 1.5, other characters about 0.25."""
    3. cjk = sum(1 for ch in text if "\u4e00" <= ch <= "\u9fff")
    4. other = len(text) - cjk
    5. return int(cjk * 1.5 + other * 0.25)
    6. def estimate_cost(input_tokens: int, output_tokens: int,
    7. price_in_per_1k: float, price_out_per_1k: float) -> float:
    8. """Calculate the cost of a single call based on the price per thousand tokens. Prices are placeholder parameters."""
    9. return (input_tokens / 1000) * price_in_per_1k + \
    10. (output_tokens / 1000) * price_out_per_1k
    11. if __name__ == "__main__":
    12. prompt = "Please organize the following meeting notes into three action items."
    13. in_tok = estimate_tokens(prompt)
    14. out_tok = 300 # Conservative estimate using the output limit
    15. cost = estimate_cost(in_tok, out_tok,
    16. price_in_per_1k=0.01, price_out_per_1k=0.03)
    17. print(f"Input approx {in_tok} tokens, output approx {out_tok} tokens, single call cost approx {cost:.4f}")

    When estimating output, it is recommended to use the maximum output length set in the request as the upper bound. This provides a conservative value and prevents actual output from exceeding the budget.

    6. Engineering Practices for Usage Governance

    Usage governance requires simultaneous control at the request, session, and task levels.

    • Limit the maximum input and output for a single request to prevent overly long contexts from entering the request.
    • Periodically summarize or truncate history in multi-turn conversations to control cumulative input.
    • For recurring long prompts, enable caching if the service supports it to reduce duplicate billing.
    • Submit batch tasks in smaller batches and record the token usage of each task for attribution and review.
    • Set usage threshold alerts and integrate them into the monitoring and alerting system to notify the responsible person when approaching the quota limit.

    The guard class below demonstrates the basic approach to managing quotas on a periodic basis:

    1. class TokenBudget:
    2. """Simple guard for managing token quotas per period."""
    3. def __init__(self, limit: int):
    4. self.limit = limit
    5. self.used = 0
    6. def consume(self, tokens: int) -> int:
    7. if self.used + tokens > self.limit:
    8. raise RuntimeError(
    9. f"Insufficient token quota: used {self.used}, requested {tokens}, limit {self.limit}"
    10. )
    11. self.used += tokens
    12. return self.limit - self.used

    In actual systems, used amounts should be stored persistently and updated with the real usage returned by the server, rather than relying solely on local estimates. Estimates are suitable for interception before a request is sent, but final accounting should be based on the metering returned by the service.

    7. Checkpoints for Procurement and Selection

    When evaluating token-based services, it is recommended to confirm the following items one by one:

    • Metering criteria: The counting rules for tokens, and whether input, output, and caching are billed separately.
    • Pricing structure: Unit price, tiered pricing, and the billing method after exceeding limits.
    • Quota rules: Validity period, carryover rules, refund conditions, and balance reminder mechanisms.
    • Usage details: Whether consumption records can be queried by time, project, or API.
    • Rate limiting policies: Limits on requests per minute and maximum context length per call.
    • Data terms: Whether input data is used for model training, and the data retention period, subject to the service agreement.

    8. Summary

    • Tokens are the metering unit for LLMs; both input and output count towards consumption.
    • The number of tokens depends on the tokenization method, language, and format. Leave a margin when estimating, and always use the provider’s count as the final standard.
    • Cumulative input in multi-turn conversations is the primary source of cost growth and needs to be controlled through truncation, summarization, and quotas.