Building a Cost Model for LLM Usage: Cost Accounting and Multi-Model Collaboration Optimization
This article explains how to move beyond per-call price comparisons and build a verifiable cost model for large language model (LLM) workloads. It covers unifying billing measurement conventions, capturing reliable call logs, using linear regression to infer input/output token coefficients, converting those coefficients into token budgets, and accounting for cache-hit economics. It also outlines a risk-tiered multi-model collaboration workflow, methods for correcting "cheapest model" judgments with success rate and rework costs, and in-execution budget controls. Readers will learn how to connect per-request consumption to business value and turn cost analysis into actionable engineering decisions.
1. From Comparing Model Prices to Building a Cost Model
In intelligent programming, document processing, and automation tasks, LLM consumption is rarely determined by the number of API calls alone. It is driven by input length, output length, how context is reused, and the overall task execution path.
A single request that looks cheap does not mean the whole task is cheap. One model might need multiple retries to complete a job, while another with a higher per-call cost reduces rework. Long-context tasks may resubmit historical content in every round, causing input consumption to grow continuously.
Cost analysis should therefore operate at three levels:
- Request level: How many billable units a single call consumed.
- Process level: How many calls, retries, and reviews it took to complete the task.
- Business level: How many qualified results were ultimately produced, and the average cost per qualified result.
Raw call records help establish the request-level cost model, but the real optimization target should be the business level: completing effective tasks with less total consumption under quality, latency, and budget constraints.
2. Unify Measurement Conventions Before Comparing Consumption
2.1 Text length is not billing length
Models typically charge based on token counts produced by tokenizing the text, not on character counts. The ratio between tokens and characters is not fixed; it varies with text type, language, and tokenization method.
Code, natural language, and structured data can have similar character counts but very different token counts. Cost statistics should prioritize the actual usage fields returned by the service rather than rough conversions based on character count.
You should also check whether other billable items exist, such as additional generated output or special input types billed separately. Cross-request comparisons are only meaningful when the billing basis is consistent.
2.2 Credits are not cash costs
Credits, quotas, and actual payment amounts are different concepts. Credit consumption reflects a resource-deduction rule; cash cost may also be affected by package pricing, validity periods, quota utilization, and additional payment options. Even if two types of requests differ greatly in credit consumption, you cannot conclude that their cash outlays differ by the same proportion.
For fixed-fee packages, you can calculate after each cycle:
Unit effective task cost = Attributable cost within the cycle ÷ Number of qualified tasks
When comparing different resource plans, use a consistent statistical period and account for utilization losses from unused quota.
3. Build Auditable Call Logs
To reverse-engineer consumption patterns, you first need sufficiently complete raw records. For each call, save at least the following:
- Request timestamp and task identifier
- Internal model category and billing rule version
- Actual input token count
- Actual output token count
- Explicitly reported cache-hit token count
- Quota actually deducted for this request
- Whether the request succeeded, failed, or timed out
- Retry count and final task acceptance result
If the service provides a per-request deduction breakdown, use it. If you can only infer consumption from balance changes, you must exclude confounding factors such as concurrent requests, quota restoration, other account operations, and billing delays.
Cache fields are especially easy to misinterpret. Some usage records include cached-hit tokens within total input, while others report them separately. Adding or subtracting without confirming the convention can cause double counting.
Also, logs should not store full prompts and source documents by default. For tasks involving privacy-sensitive or business-confidential data, prefer recording lengths, digest identifiers, and necessary summary statistics to reduce sensitive-information exposure risk.
4. Use Linear Models to Infer Consumption Coefficients
4.1 Basic model without caching
If billing is mainly determined by input and output usage, start with:
C = a × I / 1,000,000 + b × O / 1,000,000 + d
Where:
- C is the actual consumption for the call
- I is the input token count
- O is the output token count
- a is the consumption coefficient per million input tokens
- b is the consumption coefficient per million output tokens
- d is a possible fixed per-request cost
The fixed term is not guaranteed to exist. Whether to keep it should be decided based on the published rules and sample validation, not added arbitrarily just to improve fit statistics.
4.2 Extended model with cache hits
When cache hits are billed separately:
C = a × Iu / 1,000,000
- h × Ic / 1,000,000
- b × O / 1,000,000
- d
Here Iu is the non-hit input amount, Ic is the hit input amount, and h is the consumption coefficient for the cache-hit portion.
This model applies when total input can be clearly split into hit and non-hit portions. If there are cache-write fees, other billable items, or tiered rates, the model needs further extension; do not attribute all differences to input or output.
4.3 Sample design matters more than fitting method
If all requests have roughly the same input-to-output ratio, even an accurate prediction of total consumption may not reliably distinguish the input coefficient from the output coefficient.
For example, if input and output always grow together, the two variables can be highly correlated. Different combinations of coefficients may then produce similarly good fits.
A better sample should cover:
- Long input, short output
- Short input, long output
- Long input, long output
- With and without caching
- Different length ranges
- Different dates or billing rule versions
Test requests should also have budget caps to avoid generating large unnecessary consumption just to validate billing rules.
5. Why a Near-Perfect Fit Still Does Not Prove the Rules
A coefficient of determination near 1 and near-zero residuals only show that the model explains the current sample well. They do not prove that future requests will follow the same rules.
Possible issues include:
- The sample is too small; parameters merely happen to fit
- Insufficient variation in input/output ratios makes parameters unidentifiable
- Records are rounded, hiding small errors
- Long-context or special input scenarios are not yet covered
- Billing rules change later
For actual validation, hold out part of the requests as an independent test set that does not participate in parameter estimation, then check the deviation between predicted and actual consumption.
Beyond R², examine absolute error, relative error, and whether error systematically changes with input length, cache ratio, or time. For requests with very small consumption, relative error can be magnified, so combine it with absolute error.
If residuals grow noticeably with context length, check for tiered billing instead of continuing to use a single linear coefficient.
6. Convert Consumption Coefficients into Token Budgets
Let p be the proportion of total tokens that are input, 1 − p the output proportion, and ignore caching and fixed per-request costs for now. The average consumption per million tokens is:
r = p × a + (1 − p) × b
Given budget B, the estimated total token limit is:
T = B ÷ r × 1,000,000
The following numbers are for illustrating the calculation method only and do not represent any actual service’s rules.
Assume an input coefficient of 12,000 units per million tokens, an output coefficient of 48,000 units, and an input proportion of 80%:
r = 0.8 × 12,000 + 0.2 × 48,000
= 19,200
With an available budget of 60,000 units, this corresponds to approximately 3.125 million tokens in theory.
But this is not a stable guarantee. A rising output proportion, fixed per-request costs, retries, or billing rule changes can all reduce the actually available amount.
Therefore, budget estimates should provide low, medium, and high scenarios, and update the input/output ratio based on recent task logs rather than relying indefinitely on a fixed assumption.
7. Evaluate Cache Optimization on Overall Benefit
Let the cache-hit coefficient be q times the normal input coefficient, and let k be the proportion of input tokens that hit the cache. The effective input coefficient is:
a_effective = a × [(1 − k) + q × k]
If hits are billed at 2% of normal input cost and the hit ratio is 70%, the effective input coefficient is:
0.3 + 0.02 × 0.7 = 0.314
That is, input consumption drops by about 68.6% — but this does not mean the entire task cost falls by the same proportion, because output consumption must still be accounted for separately.
In engineering, you can try to keep repeated context content and ordering stable, avoiding unnecessary timestamps, random fields, or format variations. But whether these practices actually improve hit rates depends on the actual caching rules and must be verified with logs.
At the same time, do not retain irrelevant history just to trigger cache hits. Repeatedly sending large amounts of low-value content — even at a lower hit price — can increase latency, crowd out context space, and interfere with model judgment.
8. Layered Collaboration by Task Difficulty
The key to multi-model orchestration is not a simplistic rule like “expensive model for thinking, cheap model for execution,” but allocating resources according to task risk and acceptance requirements.
8.1 Planning and high-risk review
Steps involving architecture selection, complex constraints, critical changes, and final risk judgment should be assigned to model categories that are validated and more reliable.
Such calls should receive curated requirements and evidence, not an indiscriminate dump of all historical information. High-quality input is often more valuable than endlessly expanding context.
8.2 Standardized execution
Work with clear goals, decomposable steps, and automatically checkable results — such as field extraction, format conversion, template-based generation, and local text processing — can be assigned to lower-cost model categories.
Execution tasks should specify inputs, output structure, constraints, and acceptance criteria explicitly, reducing the model’s room for free interpretation.
8.3 Failure escalation
When a first attempt fails validation, analyze the failure cause before deciding whether to retry or escalate.
Format errors can often be fixed locally; knowledge or reasoning errors may require stronger capability; environment problems such as insufficient permissions or missing files should not be solved by repeatedly calling the model.
When escalating, pass a failure summary and key evidence rather than resending all repeated content.
9. Correct the “Cheaper Model” Judgment with Success Rate and Rework Cost
Under the simplified conditions of a stable success probability, approximately independent attempts, and similar per-attempt cost, you can roughly estimate:
Expected consumption per successful result ≈ Per-call cost ÷ Per-call success rate
However, real workflows also include review, repair, manual intervention, and escalation costs. A more practical metric is:
Unit qualified-task cost = Total end-to-end consumption ÷ Number of qualified tasks
Model evaluation should use the same representative task set and consistent acceptance criteria, while observing quality, latency, and cost together. For high-risk tasks, do not reduce necessary review intensity merely because the average cost is low.
10. Put Budget Control into the Execution Path
Cost governance should not consist only of reviewing month-end summaries; it should be enforced before tasks start and while they run:
- Set a maximum spend and maximum call count per task
- Limit concurrency and long outputs based on remaining quota
- Pause on consecutive failures or abnormal retries
- Require confirmation for tasks projected to exceed budget
- Periodically check whether consumption coefficients have drifted
- Distinguish between insufficient quota, concurrency limits, and model execution failures
When short-period and long-period quotas coexist, the available budget is constrained by multiple limits simultaneously. Whether the mechanism is a rolling window, fixed reset, or another recovery scheme must be confirmed from the actual rules; do not simply add short-period quotas together into a long-period allowance.
Conclusion
LLM cost optimization is ongoing engineering work: first unify measurement conventions, then build reliable logs, derive a verifiable consumption model through fitting, and finally optimize execution with caching, task tiering, and budget controls.
What is truly worth tracking is not “which model is cheapest per call,” but “which execution path can produce qualified results at the lowest cost, with acceptable quality and latency.” Only by connecting per-request consumption to task value does cost analysis turn from static price comparison into actionable engineering decisions.
