Token Usage Accounting and Cost Planning for LLM Applications
This article explains how to measure large language model usage and plan costs. It covers how tokens, credits, and monetary cost relate to each other, shows how to estimate token counts for common tasks, and describes five ways to reduce usage: trimming prompts, controlling context length, caching results, routing tasks to different models, and batching requests. It also covers budget alerts and compliant use of free quotas.
1. Background: Why Usage Becomes a Bottleneck
When people use AI office tools every day, they often run out of quota or see tasks stop partway through. The cause is usually not the tool itself. Most people lack a systematic view of their usage. They see a remaining credit balance in the interface, but they do not know how much a single chat, document generation, or automated task actually consumes.
Quota exhaustion usually has three causes. First, the input is too long, for example when a full document is pasted into a conversation again and again. Second, the output is excessive, with the model generating far more than the task requires. Third, calls are repeated, with the same question submitted several times across different sessions. Once these three sources of consumption are quantified, costs can be controlled in a targeted way.
The first step in cost management is therefore to understand the units of measurement.
2. Units of Measurement: Converting Between Tokens, Credits, and Money
Large language models usually measure usage in tokens. A token is the smallest unit of text a model processes. It may correspond to a character, part of an English word, or a punctuation mark. Different models use different tokenization methods, so the same text can produce different token counts across models.
Many tools add another layer on top of tokens, in the form of “credits” or “points.” The provider sets the conversion between credits and tokens. The rate often varies by model, feature, or plan, which means multipliers apply. As a result, the same number of credits does not buy the same amount of usage across different features.
When budgeting, build a conversion table that puts all three units on the same basis:
- Credits consumed per call, taken from the provider’s billing statement or usage details;
- Tokens per call, taken from the usage fields returned by the API or estimated locally;
- Cost per call, equal to the token count divided by 1,000, then multiplied by the unit price. Input and output tokens are usually priced separately.
The formula is as follows:
def estimate_cost(input_tokens: int, output_tokens: int,price_in_per_k: float, price_out_per_k: float) -> float:"""Estimate the cost of a single call from per-1,000-token prices. Prices must come from the provider's official price list."""return (input_tokens / 1000) * price_in_per_k + (output_tokens / 1000) * price_out_per_k
The price parameters in this example must come from the official price list. This article does not provide any specific price data.
3. Estimating Daily Usage
An accurate budget depends on breaking down the work into tasks. Take a common document processing workload as an example. You can estimate its usage with the following steps:
- List the task types, such as summarization, rewriting, translation, data extraction, and code generation.
- Measure the average input length and expected output length for each task type.
- Multiply by the number of tasks per week or per month to get the total.
The ratio of input to output often varies widely. Summarization tasks usually have much longer inputs than outputs, while creative writing tasks may generate a large share of output. If input and output are priced differently, that difference will directly affect the total cost.
Chinese and English text also convert to tokens differently. In general, Chinese is counted by character, and each Chinese character may consume about one token. English words average about four characters per token. The function below gives a rough estimate that suits budget planning. Actual billing should always rely on the usage returned by the server.
def estimate_tokens(text: str) -> int:"""Roughly estimate the token count of a text. Use only for budget planning."""cjk_chars = sum(1 for ch in text if '\u4e00' <= ch <= '\u9fff')other_chars = len(text) - cjk_charsreturn cjk_chars + other_chars // 4 + 1
The error in this method depends on the specific tokenizer and the content of the text, so calibrate it regularly against real usage data. To calibrate, record the estimated and actual token counts for each call over a period of time, calculate the average deviation, and use that deviation factor to correct future estimates.
4. Engineering Methods for Reducing Usage
After estimating usage, the next step is to reduce the consumption per task. The following five methods work well in most scenarios.
4.1 Trimming Prompts
Common sources of redundancy in prompts include repeated background explanations, unnecessary politeness, and constraints that repeat the model’s default behavior. Compressing instructions into three parts, a clear task description, the input format, and the output format, usually reduces input tokens and makes the output more consistent.
4.2 Controlling Context Length
In a multi-turn conversation, the history keeps growing and is sent with every request. The cost of a long conversation rises with each turn. There are two common approaches. One is to keep only the most recent few turns that relate to the current question. The other is to periodically compress the history into a summary and use the summary in place of the original record.
4.3 Caching Repeated Results
Results from the same question with the same parameters can be cached and reused. The example below uses an in-memory dictionary for the simplest form of caching and uses a hash of the prompt as the key:
import hashlib_cache: dict[str, str] = {}def cached_call(prompt: str, call_fn) -> str:"""Return the cached result for identical prompts to avoid repeated charges."""key = hashlib.sha256(prompt.encode("utf-8")).hexdigest()if key not in _cache:_cache[key] = call_fn(prompt)return _cache[key]
Caching suits scenarios where results are deterministic and freshness matters little, such as classification labels or fixed-format extraction results. It does not suit creative tasks that need new output every time.
4.4 Routing Tasks by Model Tier
Not every task needs the strongest model. Simple tasks such as classification, keyword extraction, and format conversion can go to a smaller model. Complex reasoning and long-form writing can go to a larger model. A routing rule can start with a simple heuristic:
def choose_model(task_type: str, prompt_tokens: int) -> str:"""Use a lightweight model for simple tasks with short inputs. Use a high-capability model for everything else."""simple_tasks = {"classify", "extract", "format"}if task_type in simple_tasks and prompt_tokens < 500:return "light-model"return "strong-model"
In a real project, replace the model names with the identifiers of the service you use, and manage them through a configuration file instead of hardcoding them.
4.5 Batch Processing
If a task can tolerate delay, combine several short requests into one batch request. This reduces the overhead of repeating the system prompt. When merging requests, keep the total input length within the upper limit for a single request, and design a separator format that makes each result easy to tell apart.
5. Usage Monitoring and Budget Alerts
Estimation alone is not enough. Without monitoring, a budget can still get out of control. Record the token count and cost of every call at the application level, and set threshold alerts. The class below implements a simple monthly budget tracker:
from dataclasses import dataclass@dataclassclass UsageBudget:monthly_limit: float # Monthly budget, in the same unit as the costspent: float = 0.0alert_ratio: float = 0.8 # Trigger a warning when this ratio is reacheddef record(self, cost: float) -> str:"""Record one charge and return the current status: ok, warning, or limit_reached."""self.spent += costratio = self.spent / self.monthly_limitif ratio >= 1:return "limit_reached"if ratio >= self.alert_ratio:return "warning"return "ok"
In a production system, the warning status can trigger a notification. The limit_reached status should pause non-critical tasks until someone confirms them or the budget resets next month. Keep a log of each call’s time, task type, token count, and cost. This makes it easier to see which steps consume the most.
6. Using Free Quotas in Compliance With the Rules
Many services offer free quotas, new-user benefits, or promotional rewards. Making good use of these resources is a legitimate way to manage costs, provided you follow these principles:
- Follow the provider’s terms of service and the rules of each promotion, and pay attention to the validity period and scope of the quota;
- Use the official APIs or clients for all operations. Do not automate by scraping, copying, or sharing login credentials;
- Each account should be held by its actual user. Do not bypass quota limits through bulk registration or by rotating accounts;
- Do not write scripts that simulate human actions to claim rewards. Such practices may violate the terms of service and lead to account suspension.
Compliance comes down to making sure the way you obtain resources matches the way the provider intends them to be used. If you rely on prohibited methods, the account risk may erase any savings.
7. Summary and Checklist
Cost management for LLM applications comes down to four steps: standardize the units of measurement, estimate task usage, reduce consumption per unit of work, and monitor the budget continuously. When you implement this approach, you can use the following checklist:
- Have you calibrated the conversion rates against the official price list and your usage statements?
- Have you measured the input and output lengths of high-frequency tasks?
- Have you trimmed your prompts and context?
- Have you enabled caching for repeated requests with stable results?
- Have you assigned lightweight models to simple tasks?
- Have you set budget thresholds and alerts?
- Do all of your quota acquisition methods comply with the terms of service?
Following this approach, you can spend your limited quota on the steps that matter most, without adding unnecessary consumption.
