LLM Token Usage Accounting: Cost Estimation, Optimization, and Free Allowance Evaluation

    This article explains how tokens determine LLM costs, how to estimate per-call usage, how to evaluate credit-based free allowances, and how to reduce consumption through prompt design, output limits, caching, retrieval, history summarization, model routing, and budget monitoring.

    1. What Is a Token, and Why Does It Determine Cost?

    A token is the basic unit that large language models use to process text. A token may correspond to one English word, one Chinese character, one punctuation mark, or a subword fragment of a word. Models do not process text directly by character count. Instead, a tokenizer splits text into a token sequence, and input and output costs are calculated by token count.

    This leads to two direct conclusions. First, there is no fixed conversion relationship between character count and token count. A Chinese paragraph of the same length may produce significantly different token counts under different tokenizers. Variable names, symbols, and indentation in English code also increase the token count. Therefore, estimating cost by character count can easily produce errors, and the tokenizer results of the target model should be measured directly. Second, many billing schemes meter input and output separately. Input includes the system prompt, historical conversation, and user question; output is the content generated by the model. The unit prices of the two parts may differ, so they should be observed separately during optimization.

    Once this is understood, the approach to cost optimization becomes clear: reduce invalid input tokens in each call, control output length, and avoid unnecessary repeated calls.

    2. Estimating Usage for a Single Call

    The token consumption of a single call can be broken into four parts:

    Single-call total tokens = system prompt + historical conversation + current user input + model output

    For capacity planning, you can first use a rough character-based estimate and then calibrate it with real samples. The following example is for estimation only; precise values should be based on statistics from the target model’s tokenizer:

    1. def estimate_tokens(text: str, chars_per_token: float = 1.5) -> int:
    2. """Roughly estimate token count from character count for capacity planning only.
    3. chars_per_token should be calibrated with real samples:
    4. Chinese-heavy text is usually close to 1 to 2, while English and code often have higher ratios.
    5. """
    6. if not text:
    7. return 0
    8. return max(1, round(len(text) / chars_per_token))
    9. def estimate_cost(
    10. input_tokens: int,
    11. output_tokens: int,
    12. price_in_per_1k: float,
    13. price_out_per_1k: float,
    14. ) -> float:
    15. """Estimate the cost of a single call from input/output token counts and unit prices.
    16. Unit prices should come from the provider's official price list, not from values copied from others.
    17. """
    18. return (
    19. input_tokens / 1000 * price_in_per_1k
    20. + output_tokens / 1000 * price_out_per_1k
    21. )

    The calibration method is simple: sample dozens of real requests, use the tokenizer to count actual tokens, compare the result with character count, and derive a conversion coefficient suitable for your own business corpus. Subsequent estimates will then be closer to the real bill.

    3. How to View Credit-Based Free Allowances

    Many platforms offer free allowances in the form of credits, points, or trial credits, and tie credits to token counts. These rules share several common characteristics: the conversion ratio between credits and tokens is set by the platform and may change at any time; there are usually expiration dates, eligibility thresholds, and per-account caps; and some rewards require completing specific tasks or passing review.

    When evaluating this type of allowance, follow these steps:

    1. Read the campaign rules completely, and record how credits are obtained, their validity period, deduction method, and reset time.
    2. Do not assume that the conversion between credits and tokens is linear. Use a fixed set of test requests, record the credits deducted for each call, and calculate the actual conversion ratio.
    3. Record token consumption for each call, calculate cost per unit task, and compare it with paid plans.
    4. Check the data usage terms to confirm whether input content will be used for model training and whether the allowance is suitable for handling internal or sensitive data.

    While earning credits, follow the community guidelines of each channel. Repeated posting, bulk account registration, or artificial inflation may lead to account bans, and rewards may also be revoked. Invite codes, account credentials, and similar information are sensitive personal data and should not be shared through public channels.

    4. Reducing Token Consumption at the Engineering Level

    Reducing token consumption is usually more stable than seeking more free allowances. The following practices apply to most LLM applications.

    4.1 Streamline Prompts

    Common waste in prompts includes repeated role settings, background explanations unrelated to the task, and the same rule emphasized multiple times. Consolidate fixed rules into short bullet items, remove verbose modifiers, and use a few examples instead of long explanations.

    1. # Verbose: rules are scattered and repeated
    2. prompt_verbose = """You are a highly professional and very experienced assistant. Please answer questions carefully and thoroughly. Make sure the answer is accurate, accurate, and accurate again. Keep the answer concise."""
    3. # Concise: rules are centralized and clear
    4. prompt_concise = """Role: technical Q&A assistant.
    5. Requirements: accurate answers, concise length, state uncertainty when unsure."""

    4.2 Control Output Length

    Model output tokens are often more expensive than input tokens, so output control is especially important. This can be achieved in the following ways:

    • Set a maximum output token count to prevent the model from generating excessively long answers.
    • Require structured output, such as returning only JSON with specified fields, to avoid greetings and repeated explanations.
    • For classification and extraction tasks, explicitly require only labels or values as output.

    4.3 Cache Repeated Results

    Repeatedly calling the model with the same input is a common waste. For highly deterministic tasks, such as summaries of fixed text or answers to standard questions, results can be cached by the hash of the input content and returned directly on a cache hit. Some services also support caching fixed prefixes such as long system prompts; follow the provider’s documentation for specific rules.

    1. import hashlib
    2. _cache: dict[str, str] = {}
    3. def cached_call(prompt: str, call_model) -> str:
    4. """Cache results for identical prompts to avoid duplicate billing.
    5. call_model is a function that calls the model, injected by the caller.
    6. Note: use caching only when output can be reused; do not cache requests involving real-time data.
    7. """
    8. key = hashlib.sha256(prompt.encode("utf-8")).hexdigest()
    9. if key not in _cache:
    10. _cache[key] = call_model(prompt)
    11. return _cache[key]

    4.4 Use Retrieval Instead of Full-Text Input

    In knowledge Q&A scenarios, a common practice is to put an entire document into the prompt. A more reasonable approach is to first retrieve only the snippets relevant to the question and then pass them to the model. This can significantly reduce input tokens and usually also improves the focus of the answer.

    4.5 Truncate and Summarize Conversation History

    Multi-turn conversations continuously accumulate historical messages. When the history exceeds a certain length, you can keep the most recent turns and compress earlier content into a summary. This requires balancing context completeness and cost, and key constraints should always remain in the prompt.

    4.6 Route by Task Difficulty

    Not all tasks require the strongest model. Classification, format conversion, and simple rewriting can usually be handled by smaller, cheaper models; complex reasoning and long-form generation can then use stronger models. Tiered routing can reduce overall cost while keeping quality largely unchanged.

    5. Usage Monitoring and Budget Alerts

    Cost control without monitoring is unreliable. At the application layer, record key information for each call, including model name, input token count, output token count, latency, call result status, and business module. Logs should not record sensitive raw user text; keep only the numbers and identifiers needed for statistics.

    The following example shows a simple budget guard that issues a warning when usage approaches the limit and rejects new requests after the limit is exceeded:

    1. class TokenBudget:
    2. """Track token usage per period, warn before the limit, and reject requests after it."""
    3. def __init__(self, limit: int, warn_ratio: float = 0.8):
    4. self.limit = limit
    5. self.warn_threshold = int(limit * warn_ratio)
    6. self.used = 0
    7. self._warned = False
    8. def consume(self, tokens: int) -> None:
    9. if self.used + tokens > self.limit:
    10. raise RuntimeError("Token budget exhausted; request rejected")
    11. self.used += tokens
    12. if not self._warned and self.used >= self.warn_threshold:
    13. self._warned = True
    14. print(f"[Warning] Token usage has reached {self.used / self.limit:.0%} of the budget")

    In production environments, budget guards usually need to be set separately by user, by project, or by time window, and integrated with alert channels. A threshold of around 80% can leave time for manual intervention.

    6. Checklist for Evaluating Free Allowances

    Before using a free allowance for a formal project, confirm the following items one by one:

    • Expiration and reset rules: whether unused allowance becomes invalid after expiration.
    • Rate limits: whether requests per minute and tokens per minute meet business peak demand.
    • Data policy: whether input data is used for training, and whether storage location and retention period meet compliance requirements.
    • Feature scope: whether the free allowance covers the required model version, API capabilities, and output length.
    • Exit conditions: whether the application can switch smoothly to a paid plan after the campaign ends or rules change, without major rework.

    Wrapping model calls in a unified adapter layer helps switch between different providers and avoids deep binding between business code and a single platform.

    7. Implementation Recommendations

    1. Measure first, then estimate: calibrate the character-to-token relationship with real samples, and let actual bills drive decisions.
    2. Treat output length as a first-class concern, and set an explicit output ceiling for each task.
    3. Enable caching for deterministic tasks, and disable caching for dynamic data.
    4. Establish usage logs and budget alerts so overspending can be detected before it happens.
    5. Use free allowances as resources for validation and experimentation, and evaluate their stability and compliance before production launch.
    6. Review the cost structure regularly, watch changes in the input-to-output ratio, and adjust prompts and model selection promptly.