LLM API Cost Management: How to Estimate and Optimize Token Costs
This guide explains how token-based billing works for large language model APIs and how to evaluate and reduce costs without sacrificing output quality. It covers input and output token pricing, caching and call frequency, a reusable Python cost estimator, context trimming, result caching, task-based model routing, usage monitoring, selection criteria, rollout steps, and common cost-management pitfalls.
Large language model (LLM) services are usually billed by token. A token is the basic unit of text processed by a model, produced by splitting text with a tokenizer. In Chinese text, one token roughly corresponds to one or two Chinese characters, depending on the tokenizer. In English text, a common rule of thumb is that about four characters correspond to one token. For billing, providers count input tokens (prompts, context, and attachment content) and output tokens (the model-generated answer) separately, then charge each at its own unit price.
Expanded context windows have changed the cost structure. In the past, developers often had to split long documents into small sections and submit them one at a time. Now, when the context window is large enough, an entire code repository or a long document can be submitted in a single call. This reduces manual splitting work, but it also significantly increases the input size of each call. Without controls, cost rises linearly with input size and can quickly exceed expectations.
Therefore, evaluating the economics of an LLM application requires considering single-call cost, call frequency, and effective output together, rather than looking only at a price table.
Breaking Down the Billing Structure
- Input tokens. These include the system prompt, conversation history, retrieved documents, and the user question. The longer the input, the higher the single-call cost.
- Output tokens. These include all text generated by the model. Generation decodes token by token and is computationally expensive, so most services price output tokens higher than input tokens.
- Cache-related fees. Some services support prefix caching, which reuses computation for repeated fixed prefixes such as long system prompts or fixed documents. Cached portions are usually billed at a lower unit price, subject to the provider’s documentation.
- Number of calls. If a task requires multiple calls, such as multi-round correction or tool-calling loops, total cost is the sum of all calls.
Single-call cost can be estimated with the following formula:
Single-call cost = input_tokens ÷ 1,000,000 × input_price + output_tokens ÷ 1,000,000 × output_price
Here, prices are expressed per million tokens.
Implementing Cost Estimation in Code
The function below packages the formula into a reusable estimator. Price parameters are passed in by the caller, making it easy to adapt to different providers’ price tables.
def estimate_cost(input_tokens: int,output_tokens: int,input_price_per_m: float,output_price_per_m: float,) -> float:"""Estimate single-call cost using per-million-token prices. The return value uses the same currency unit as the prices."""if input_tokens < 0 or output_tokens < 0:raise ValueError("Token counts cannot be negative")input_cost = input_tokens / 1_000_000 * input_price_per_moutput_cost = output_tokens / 1_000_000 * output_price_per_mreturn input_cost + output_cost
The following example uses hypothetical prices (1 CNY per million input tokens and 4 CNY per million output tokens) only to demonstrate the calculation method; it does not represent the price of any actual service. Assume a call uses 100,000 input tokens and generates about 15,000 output tokens:
- Input cost: 100,000 ÷ 1,000,000 × 1 = 0.1 CNY
- Output cost: 15,000 ÷ 1,000,000 × 4 = 0.06 CNY
- Total: 0.16 CNY
In this example, input consumes the larger share of the budget. If input is reduced to 20,000 tokens, the total cost drops to 0.04 CNY plus 0.06 CNY, or 0.10 CNY. This shows that controlling input size is often more effective than reducing output, but both need to be part of the evaluation.
Two cautions apply when estimating costs. First, Chinese token counts cannot be converted directly from character counts; use the target service’s tokenizer or usage statistics returned by the API to calibrate estimates. Second, output token count is uncertain, so estimate it using the mean and percentiles of historical call data rather than a single fixed value.
Key Variables That Affect Cost
1. Input Size
Input size is the most direct variable. Submitting an entire repository may be convenient, but many irrelevant files increase cost and can dilute the model’s attention to key information. A safer approach is to retrieve relevant snippets first, then submit them to the model.
2. Output Length
Output length can be constrained through task instructions, structured formats, and maximum-length parameters. For example, a classification task only needs to return a label, not a full explanation. A clear output format reduces cost and makes parsing easier.
3. Call Frequency and Batching
Frequent small requests accumulate substantial fixed overhead. For tasks that can run offline, merging requests or using batch APIs usually reduces overall cost. For interactive scenarios, design appropriate caching and deduplication mechanisms.
4. Repeated Prefixes
System prompts, fixed rules, and commonly used documents appear repeatedly in every call. Place this stable content at the front of the prompt and keep it byte-for-byte consistent as much as possible to improve prefix-cache hit rates. Put dynamic content, such as the user question, at the end.
5. Model Tiering
Not every task requires the most capable model. Smaller models are often sufficient for classification, extraction, and format conversion. Reserve stronger models for complex reasoning and long-form writing. Routing by task type is one of the most common ways to control cost.
Engineering Practices for Reducing Cost
Context Trimming
Under a limited budget, prioritize content most relevant to the question. The function below sorts chunks by relevance score and selects snippets within a token budget.
def trim_context(chunks, budget_tokens, count_tokens):"""Select text chunks by relevance score from highest to lowest, keeping total tokens within budget.chunks: list of dictionaries with "text" and "score" fieldscount_tokens: function that takes text and returns its token count"""selected = []used = 0for chunk in sorted(chunks, key=lambda c: c["score"], reverse=True):n = count_tokens(chunk["text"])if used + n > budget_tokens:continueselected.append(chunk)used += nreturn selected
The core method is greedy selection. It does not guarantee a global optimum, but it is simple to implement and usually sufficient for production needs. Relevance scores can come from vector retrieval, keyword matching, or a hybrid of both.
Result Caching
When the same question is asked repeatedly, returning a cached result avoids duplicate billing. The cache key should include the model version, prompt template version, and a hash of the input content; otherwise, updating the template may return stale results. For semantically similar questions with different wording, consider semantic caching, but set a similarity threshold to prevent incorrect hits.
Task-Based Model Routing
The example below shows a simple routing logic. The model names are placeholders and should be replaced with the model identifiers of the selected service in actual use.
def pick_model(task_type: str, prompt_tokens: int) -> str:if task_type in {"classification", "extraction"} and prompt_tokens < 4000:return "small-model" # placeholder nameif prompt_tokens > 200_000:return "long-context-model" # placeholder namereturn "standard-model" # placeholder name
Routing rules should be based on evaluation results, not intuition. Build an evaluation set for each task type, record the accuracy of different models, and then define the routing strategy.
Usage Monitoring and Budget Alerts
Every call should record input tokens, output tokens, model identifier, business tag, and latency. Aggregating by project, user, or feature module helps identify cost anomalies. Set daily and weekly budget thresholds and trigger alerts when they are exceeded to avoid unexpected spending caused by program defects or looped calls. When deploying these services on a cloud platform, you can combine billing and usage data to break costs down by project for attribution and review.
Evaluation Framework for Model Selection
Model selection should not rely on unit price alone. Evaluate candidates across the following dimensions:
- Unit cost: input, output, and cache prices, plus average token consumption for typical tasks.
- Task quality: accuracy, format compliance, and hallucination rate on your own evaluation set.
- Context length: whether the model can accommodate the input size of the target scenario, and whether performance remains stable with long inputs.
- Response latency: time to first token and overall generation time, which affect interactive experience and batch throughput.
- Deployment model: whether public cloud API access is supported, whether open-weight models are available, and whether private deployment is possible.
- Data compliance: whether data storage location, retention period, and access controls meet enterprise requirements.
- Service stability: rate-limit policies, availability metrics, and compatibility across version iterations.
Among these dimensions, the most practical metric is effective unit cost: total cost divided by the number of tasks that pass quality evaluation. A model with a low unit price but a low pass rate may cost more overall because of repeated retries. Therefore, use real task samples for end-to-end testing and calculate each model’s effective unit cost before making a decision.
Recommended Rollout Steps
- Map business scenarios, divide workloads by task type, and estimate input and output sizes for each task category.
- Build a small evaluation set covering major tasks and edge cases, and record quality metrics for each candidate model.
- Use the estimation formula and evaluation results to calculate effective unit cost and shortlist candidates.
- Implement context trimming, result caching, and output constraints, and connect usage monitoring.
- Roll out gradually, observe cost curves and quality fluctuations, and adjust routing rules and budget thresholds based on data.
- Re-evaluate regularly. Model prices, capabilities, and service terms change, so selection conclusions should have a fixed review cycle.
Common Pitfalls
- Comparing only unit prices while ignoring the impact of output length and retry count on total cost.
- Stuffing an entire knowledge base into the context without relevance filtering.
- Using the strongest model for every request without task-based tiering.
- Lacking usage records, making cost anomalies difficult to locate.
- Changing prompts frequently, which prevents prefix caching from hitting.
The core of LLM cost management is turning token consumption into a measurable, predictable, and optimizable metric. With estimation formulas, context trimming, result caching, model tiering, and usage monitoring, development teams can keep costs within budget while maintaining output quality.
