Token Cost Control Practices for Pay-Per-Use LLMs

    As AI productivity tools increasingly adopt credit-based or pay-per-use billing, costs can become opaque. This article explores the relationship between credits and tokens, outlines methods for estimating token consumption, and provides practical engineering strategies to minimize costs. Topics include prompt optimization, context length control, model tiering, and usage monitoring, complete with Python examples for cost estimation and budget guarding.

    1. Background: Credit-Based Billing Makes Costs Opaque

    More and more AI productivity tools use credit or point-based billing. Before performing an action, it is often difficult to judge how many credits will be consumed, and package prices frequently lack a direct correlation with actual usage. Once free quotas are exhausted, users typically face two questions: which operations consume the most credits, and how to reduce consumption without noticeably compromising performance.

    To solve this, we must first understand the underlying billing unit. Most credit-based products bill based on Tokens. A Token is the smallest segmentation unit when a model processes text; both the input content and the model’s output count towards the total tokens. Credits are usually a wrapper around token consumption, featuring an added multiplier. Different models and different features may have varying multipliers.

    2. The Conversion Logic Between Tokens and Credits

    2.1 Basic Concepts of Tokens

    Tokens do not equate to word or character counts. In Chinese contexts, one character typically corresponds to one or two tokens, depending on the tokenizer. In English contexts, a common word roughly corresponds to one token. Therefore, Chinese and English texts with the same word count may yield very different token counts.

    2.2 Cost Differences Between Input, Output, and Cache

    Most model services price input and output tokens separately, with the output unit price usually being higher. Some services also offer cache discounts for repeated context hits. For a single call, if the output is long, the cost will increase significantly.

    2.3 Cost Formula for a Single Call

    The cost of a single call can be estimated using the following formula:

    Single Call Cost = Input Tokens × Input Price + Output Tokens × Output Price

    If the platform bills via credits:

    Credit Consumption = (Input Tokens + Output Tokens) × Model Multiplier ÷ Conversion Factor

    The conversion factor is published by the platform. Estimations should be based on the platform’s actual rules rather than borrowing conversion ratios from other products.

    3. Cost Estimation Methods

    Cost estimation involves four steps:

    1. Decompose tasks: Break the business workflow into independent model calls, such as document summarization, table generation, and email polishing.
    2. Sample statistics: Extract 20 to 50 real calls for each task type and record the input and output token counts.
    3. Calculate mean and high percentiles: The mean reflects average consumption, while the 95th percentile reflects high-consumption scenarios. Both should be factored into the budget.
    4. Reserve a margin: Actual usage is usually higher than sample estimates; a buffer of around 20% is recommended.

    The following sample script demonstrates how to aggregate estimation results by task type. The prices used are fictional parameters, intended solely to illustrate the calculation logic.

    1. from dataclasses import dataclass
    2. @dataclass
    3. class CallProfile:
    4. task: str
    5. input_tokens: int
    6. output_tokens: int
    7. calls_per_month: int
    8. INPUT_PRICE = 0.002 # Price per 1k input tokens (example)
    9. OUTPUT_PRICE = 0.006 # Price per 1k output tokens (example)
    10. SAFETY_MARGIN = 1.2 # Reserve a 20% buffer
    11. def monthly_cost(profiles: list[CallProfile]) -> float:
    12. total = 0.0
    13. for p in profiles:
    14. per_call = (p.input_tokens / 1000) * INPUT_PRICE \
    15. + (p.output_tokens / 1000) * OUTPUT_PRICE
    16. total += per_call * p.calls_per_month
    17. return total * SAFETY_MARGIN
    18. if __name__ == "__main__":
    19. profiles = [
    20. CallProfile("Document Summarization", 6000, 800, 120),
    21. CallProfile("Email Polishing", 800, 300, 400),
    22. CallProfile("Table Generation", 3000, 1500, 60),
    23. ]
    24. print(f"Estimated monthly cost: {monthly_cost(profiles):.2f}")

    4. Engineering Strategies to Reduce Token Consumption

    4.1 Streamline Prompts

    System prompts and fixed templates are billed repeatedly in every call. Redundant descriptions should be removed in favor of short, structured instructions. For example, rewrite “Please act as an experienced editor and carefully process the following content” into “Role: Editor. Task: Compress into three sentences. Format: Plain text.” This retains the constraints while reducing input tokens.

    4.2 Control Context Length

    Long conversations bring all historical messages into the next request. Common practices include: keeping only the most recent rounds of messages, compressing earlier content into summaries, or passing only relevant chunks in Retrieval-Augmented Generation (RAG) scenarios. The chunk size needs to be adjusted according to the document structure. Chunks that are too small will lose semantic meaning, while those too large will waste tokens.

    4.3 Tiered Model Selection Based on Task

    Not all tasks require the most powerful model. Simple tasks like classification, format conversion, and keyword extraction can often be handled by smaller models, while complex reasoning and long-form writing can invoke larger models. The application layer can implement a routing rule to select models based on task type or input length.

    4.4 Limit Output Length

    Setting a maximum output token count and instructing the model to provide brief answers can effectively control output costs. Since output pricing is usually higher than input pricing, the savings here are often the most significant.

    4.5 Cache and Reuse

    Results from identical inputs can be cached. For standardized Q&A, the hash of a normalized input can serve as the cache key. For semantically similar questions, vector similarity checks can be introduced. When a cache hit occurs, no model call is made, directly saving credits.

    4.6 Merge Small Requests

    Numerous short requests each carry a system prompt, amplifying fixed overhead. Merging multiple texts to be processed into a single batch call can reduce repeated instruction tokens. However, merging too many items may affect output quality, so appropriate batch sizes should be determined through sample testing.

    5. Usage Monitoring and Budget Control

    Cost governance relies on monitoring. It is recommended to achieve at least the following three points:

    • Record token usage by project, feature, and user to easily locate high-consumption areas;
    • Set daily, weekly, and monthly thresholds, issuing alerts when usage exceeds 80%;
    • Upon reaching the limit, degrade to a smaller model or pause non-critical tasks instead of directly interrupting the business.

    Below is a simple budget guard example:

    1. class BudgetGuard:
    2. def __init__(self, monthly_limit: float):
    3. self.monthly_limit = monthly_limit
    4. self.spent = 0.0
    5. def can_spend(self, estimated_cost: float) -> bool:
    6. return self.spent + estimated_cost <= self.monthly_limit
    7. def record(self, actual_cost: float) -> None:
    8. self.spent += actual_cost
    9. def usage_ratio(self) -> float:
    10. return self.spent / self.monthly_limit

    Before making a call, first use the can_spend method to verify the remaining budget.