LLM API costs cannot be summarized by a single phrase such as 'charged by token.' They are determined by four layers: token metering, separate pricing for input and output, prompt cache hit rate, and call strategies such as retries and fallbacks. This article provides directly applicable formulas and examples, a cost-structure comparison by task type, a billing anomaly diagnosis table, and an explanation of why unit prices must follow the real-time display in the model library instead of being hardcoded in the article.
Models in this articlestep-5
Models in this article

Key takeaways
- 1. Single-call cost = (input tokens × input unit price + output tokens × output unit price) / 1,000,000, plus cache discounts and repeated charges from failed retries.
- 2. Retrieval Q&A and long-form generation have opposite cost structures: the former is mainly driven by the input segment, while the latter is mainly driven by the output segment; total tokens alone are not enough.
- 3. Cache hit rate depends on whether the prompt structure is stable; placing fixed instructions first and changing content last is the lowest-cost pattern.
- 4. Unlimited retries multiply costs; according to the Step-5 launch announcement released by AGTCloud on December 1, 2026, reducing output tokens by about 38% can translate into a 36% reduction in API costs.
- 5. Unit prices and context parameters should uniformly follow the real-time display in the AGTCloud model library; the article does not hardcode prices to avoid inconsistency with the official source after publication.
What is the formula for calculating LLM API costs?
The cost per API call for a large model = (input token count × input unit price + output token count × output unit price) / 1,000,000, plus prompt cache discounts and duplicate billing caused by failed retries. Among the four variables, token count and monthly calls are determined by the business, while unit prices and cache rules are determined by the model service. Breaking the bill into four layers—token metering / input-output pricing / cache hits / call strategy—tells you whether to change the engineering implementation or the model selection. The information in this article is as of December 2, 2026, and prices are based on the AGTCloud Model Library’s real-time display.
单次调用成本 = (输入Token数 × 输入单价 + 输出Token数 × 输出单价) / 1,000,000
月度成本 = 单次调用成本 × 月调用次数 × (1 + 失败重试放大系数)
单位 : 单价 元/百万 Token ; Token 数 次 ; 成本 元
说明 : 输入单价 P_in 与输出单价 P_out 通常不相等,缓存命中部分按服务规则折算Variable | Meaning | Determined by | Optimization method |
Input token count | Total tokens after splitting prompts, retrieval context, and history messages | Business side | Compress context, stabilize prefixes, and control the number of retrieved items |
Output token count | Total tokens generated by the model | Business side + model | Set max_output_tokens and constrain the output format |
Input unit price P_in | Price per million input tokens | Model service | Model selection; subject to real-time display at /models |
Output unit price P_out | Price per million output tokens | Model service | Model selection; subject to real-time display at /models |
Monthly calls | Total valid calls within the period | Business side | Merge duplicate requests and add result caching |
Retry amplification factor | Additional billing ratio caused by failed retries | Engineering implementation | Retry limits, backoff, and retrying only retryable errors |
The value of this formula is not in calculating a specific amount, but in breaking the vague judgment “the bill got more expensive” into six separately measurable quantities. As long as the usage field and call logs are kept complete, any cost fluctuation can be traced to a specific column.
Why input tokens and output tokens must be calculated separately
Input and output are usually priced separately, and their unit prices are not the same. This means total cost is very sensitive to task shape: a retrieval Q&A with 4,000 input tokens and 200 output tokens versus long-form generation with 200 input tokens and 4,000 output tokens may differ several-fold in cost even if total tokens are close. If a budget table records only total_tokens, it erases the most critical unit-price difference, making later optimization impossible to attribute.
Therefore, at least three fields should be persisted separately in call logs: prompt_tokens, completion_tokens, and total_tokens. When aggregating by day, sum them separately and multiply each by the corresponding unit price to reconcile with the bill; looking only at the total is the most common mistake in cost analysis.
Cost example for one call: walking through the formula with example assumptions
The following uses a set of example assumptions to demonstrate the calculation process. Token counts, call counts, and multiplier relationships are for demonstration only, and P_in / P_out are symbols rather than quotes; they do not represent actual unit prices of any model. Assume an application uses 1,500 input tokens and 500 output tokens per call, with 200,000 calls per month; let P_in be a yuan per million tokens and P_out = 4a yuan per million tokens.
单次成本 = (1500 × a + 500 × 4a) / 1,000,000
= (1500a + 2000a) / 1,000,000
= 3500a / 1,000,000 元
输出段占比 = 2000a / 3500a ≈ 57.1% ← 输出只占 25% 的 Token,却占过半成本
月度成本 = 3500a / 1,000,000 × 200,000 = 700a 元
若把输出压到 300 Token:输出段占比降至 ≈ 44.4%,月度成本降至 540a 元(约 -22.9%)This example illustrates two things: first, although the output segment accounts for only 25% of token volume, it may contribute more than 50% of the cost; second, optimizing output length is easier to show results than optimizing input length. Replacing a with the actual unit prices in the model library gives the real amount, but the formula and proportional relationships do not change with unit prices. This is the division of labor: keep prices in /models and keep methods in the article.
Why token metering cannot be converted by word count
Models meter by tokens, not by characters or word count. A token is the basic unit after a tokenizer splits text; Chinese, English, code, punctuation, and numbers are split differently, and the same text may have different token counts on different models. Therefore, “word count × empirical coefficient” can only be used for order-of-magnitude estimates, not for budgeting or reconciliation.
Content type | Common splitting characteristics | Impact on cost estimation | Verification method |
Chinese text | In common cases, one Chinese character corresponds to about 1–2 tokens | Estimating by word count tends to underestimate | Read usage.prompt_tokens |
English text | Common words are often one token, and long words are split into multiple segments | The coefficient is unstable in mixed Chinese-English text | Aggregate separately by actual requests |
Code and JSON | Indentation, symbols, and identifiers are split separately | Structured output is often significantly higher than plain text with the same word count | Measure with sample requests |
Punctuation and whitespace | Also counted as tokens | Redundant blank lines in templates accumulate cost | Streamline prompt templates |
Retrieval context | Multiple document segments are concatenated and then split as a whole | The number of retrieved items linearly increases the input segment | Monitor the distribution of input tokens per call |
The “one Chinese character corresponds to about 1–2 tokens” in the table is an empirical order of magnitude, not an exact conversion rate; the specific result must be based on the actual output of each model’s tokenizer. To obtain reliable numbers, the easiest way is to use the AGTCloud console to send a sample request, directly read the returned usage statistics, and then write this ratio into your team’s estimation table.
Verify actual usage using the usage field
Whether it is an OpenAI-compatible API or an aggregation platform, responses usually include a usage object. Persisting it to the database is the first step from “estimation” to “reconciliation”:
resp = client.chat.completions.create(model=model, messages=messages)
u = resp.usage
record = {
"input_tokens": u.prompt_tokens,
"output_tokens": u.completion_tokens,
"total_tokens": u.total_tokens,
"model": model,
}
# 分别累加 input_tokens / output_tokens,再各自乘对应单价
usage_log.append(record)Unit prices are intentionally omitted here: prices change, and hard-coding them will eventually mismatch the bill. Decoupling usage from pricing and reading prices from the model catalog is the engineering counterpart of Section 4.4 in the PRD, “/models is the single source of truth”.
How separate input/output pricing changes the cost structure of different tasks
Even for the same large-model API calls, different task shapes have different primary cost sources. The table below compares three typical task types by the token share of the input segment / output segment (the ratios are illustrative assumptions used to explain sensitivity and do not represent any measured business values), and lists the most effective optimization action for each.
Task type | Input : Output (example) | Primary cost source | Priority optimization action | Least worthwhile approach |
Retrieval-augmented QA (RAG) | 4,000 : 200 | Long input segment | Control the number of retrieved chunks, compress context, and stabilize prefixes to improve cache hits | Simply shortening answers |
Long-form generation | 200 : 4,000 | Long output segment | Set max_output_tokens, constrain output format, and generate in segments | Repeatedly compressing prompts |
Batch classification / extraction | 300 : 30 | Number of calls | Batch merging, result caching, and choosing a lighter model | Creating a separate session for each record |
Multi-turn conversation | Accumulates with turns | Repeated billing of history messages | Summarizing history and using a sliding window | Carrying the full history every turn |
This table can be used directly as a cost review checklist: first determine which row your task falls into, then execute the optimization actions for that row. Attributing RAG cost issues to “output is too long” or long-form generation cost issues to “prompt is too long” is a directional error—both appear on the bill as a high total token count, but the causes are completely different.
How prompt cache hit rate affects the bill
When a request contains content that is repeatedly used, services supporting prompt caching can reuse previously computed results, and the billing method for the repeated portion changes accordingly. Whether a cache hit occurs depends on whether the prompt structure is stable, not on whether a switch is enabled. Placing fixed instructions first and variable content last is the lowest-cost and easiest-to-verify approach.
[固定段] 角色设定 / 输出格式 / 业务规则 ← 每次调用完全一致,可被缓存复用
[半固定段] 检索召回的文档片段 ← 按查询变化,放在固定段之后
[变化段] 用户本轮输入 ← 每次都不同,放最后
反例:把用户输入或时间戳放在提示词第一行,会让前缀持续变化,命中率趋近于 0To decide whether a refactor is worthwhile, compare the “cached-hit tokens / total input tokens” ratio before and after the change. If this ratio stays below a certain threshold for a long time, it means the fixed segment is too short or the prefix is unstable, and adjusting the structure will bring larger benefits than switching models. Also note that caching usually has minimum cacheable length and validity-period constraints; low-frequency calls may not benefit, and cache discounts should not be written into budgets as a universal assumption.
Why stable prefixes determine cache hit rate
Prompt pattern | Is the prefix stable? | Expected cache hit | Recommended use |
Fixed system instructions + variable content placed last | Stable | High | Recommended: most online services |
Prepending user input every time | Unstable | Low | Avoid |
Inserting the current timestamp into system instructions | Changes every time | Low | Move the timestamp to the variable segment or request parameters |
Using retrieval results at the beginning of the fixed segment | Changes with each query | Low | Move retrieval results later |
Randomly rotating among multiple templates | Partially stable | Medium | Group by template and ensure consistent prefixes within each group |
Enforcing these rules in code review is more effective than adjusting prices after the fact: once a prompt template allows dynamic variables to be inserted at the beginning, caching changes from “available” to “almost unusable,” and such changes often do not appear immediately in the bill; they only become visible after call volume rises.
Why retries and fallbacks are hidden cost amplifiers
The number of retries, timeout settings, failure fallbacks, whether streaming output is used, and whether batch submission is used all change the final bill. If a failed request is retried without a cap, costs multiply; more subtly, output tokens already generated during a timeout retry may still be billed, so “failure” does not mean “no cost.” According to the Step-5 launch announcement released by AGTCloud on December 1, 2026, the model increased its comprehensive intelligence index by 11 points to 40 while reducing total evaluation output tokens by about 38% and reducing the weighted average per task by 53%, equivalent to a 36% API cost reduction—this shows that inference efficiency itself is a cost variable comparable to model selection, not merely a performance metric.
retry:
max_attempts: 3 # 首次 + 2 次重试
backoff: exponential # 1s → 2s → 4s
timeout_seconds: 30
retry_on: [timeout, 429, 5xx] # 参数错误与业务校验失败不重试
budget:
max_output_tokens: 800
max_input_tokens: 4000
monthly_call_limit: 200000
fallback:
on_budget_exceeded: downgrade_model
on_timeout: return_cached_or_degradeRetry policy | Call amplification in the worst case | Cost risk | Recommendation |
No retry | 1× | Poor availability, but predictable billing | Use only for tasks insensitive to failure |
Fixed 3 attempts + backoff | 3× | Controllable | Recommended default |
Unlimited retries | Uncontrollable | Bills multiply during upstream instability | Prohibited |
Retrying all errors (including parameter errors) | Continuously amplifying | Invalid requests are repeatedly billed | Use an error-type allowlist |
Retry on timeout without a usage cap | Multiple stacking | Already generated portions are still billed | Use with max_output_tokens |
The key is to make the retry count, backoff interval, and per-call usage cap explicit configuration and include them in monitoring, rather than scattering them across business code. As long as these three items have a unified entry point, cost anomalies can be detected within minutes; otherwise, by the time the monthly bill arrives, you are already a full cycle late.
How to use the four-layer comparison table to locate billing anomalies
Consolidate the previous four layers into an actionable troubleshooting table. When using it, first locate the corresponding row by symptom, then verify the check items for that row, and finally execute the action; do not jump to 'switch to a cheaper model', because most anomalies originate from the engineering side.
Billing symptom | Priority layer to check | Specific check items | Action to take |
Estimate differs significantly from the bill | Token metering | Whether character counts are used for conversion; whether only total_tokens is recorded | Record input/output tokens separately instead |
Long-text scenarios have high cost | Input/output pricing | Output-token share and the P_out/P_in multiplier | Set max_output_tokens and constrain the format |
Repeated calls do not become cheaper | Cache hit | Cache-hit token share; whether the prefix contains dynamic variables | Keep a stable prefix and place changing content later |
Cost fluctuates in sync with the failure rate | Call strategy | Retry count, timeout, and whether parameter errors are retried | Add allowlists and usage limits |
RAG cost grows with the knowledge base | Token metering | Number of items retrieved per call and context concatenation length | Control the number of items and summarize history |
Monthly cost spikes while call volume remains stable | Call strategy + metering | Whether requests are downgraded to more expensive models; whether prompt templates changed | Compare templates and model distribution before and after release |
This table is also suitable for directly placing in the team's operations handbook: each row has explicit observation fields, does not rely on subjective judgment, and does not require knowing specific unit prices in advance.
What order should cost optimization follow?
First add observability: Store input tokens, output tokens, model, retry count, and cache-hit tokens separately in call logs, and aggregate them by day. Without this step, none of the subsequent optimizations can be proven effective.
Then control amplification: Set max_attempts=3, exponential backoff, a 30-second timeout, and max_output_tokens, and retry only on timeout / 429 / 5xx. This step usually takes effect fastest and does not require changing business logic.
Then change the structure: Place fixed prompt sections first and changing sections later, control the number of retrieved items and the length of multi-turn history, and increase the cache-hit share.
Next tune tasks: According to the cost structure table above, set output constraints and batching strategies separately for different tasks, avoiding using the same parameters for all scenarios.
Only evaluate model selection last: In AGTCloud Model Library compare unit prices, context, and inference efficiency, and place model switching last because it triggers effectiveness regression testing and has the highest change cost.
The significance of this order lies in 'controllability': the first four steps are all on the engineering side, can be gray-released, rolled back, and measured; model switching changes both effectiveness and cost at the same time, and once the earlier attribution is skipped, it is impossible to determine where the bill changes actually come from.
Common misconceptions about large-model API costs
Common claim | Why it is inaccurate | More accurate statement |
'Billing is based on character count, so controlling character count is enough' | Billing is metered by tokens, and input/output unit prices differ | Control input tokens and output tokens separately, and pay attention to the difference in their unit prices |
'If total tokens decrease, cost must decrease' | The output unit price is usually higher; when total volume decreases but the structure worsens, cost may not decrease | Look at segmented tokens and weighted cost together |
'Enabling cache will make it cheaper' | Cache depends on a stable prefix and hit share | Measure the cache-hit token share first before judging |
'Failed requests are not billed' | When retrying after a timeout, already generated parts may be billed, and duplicate requests are billed separately | Include the retry amplification factor in the budget |
'Switching to a cheaper model is the preferred solution' | It bypasses engineering-side amplification and triggers effectiveness regression | First control retries and output, then evaluate model selection |
'Writing current unit prices into documentation makes estimation easier' | After price changes, documentation becomes distorted and conflicts with official figures | Write formulas into documentation, and read unit prices in real time from /models |
The last item deserves special emphasis: once content is published, it can be indexed long-term by search engines and AI engines; hardcoded prices will mislead readers and, after price adjustments, form outdated information that contradicts official figures. This is also why this article uses symbolic unit prices throughout and keeps specific unit prices in the model library.
How to continuously verify costs on AGTCloud
When implementing, it is recommended to connect the formulas in the article with usage data from the Console. In AGTCloud Model Library you can view each model's context length, unit price, and capability differences; in Console you can view calls and usage by model and time period; before publishing, use a sample request to verify whether the segmented token records in this article match the actual returns. After models are associated in the article, the parameter table on the detail page automatically reads from the model data source and updates synchronously when prices change, without needing to edit the body text again.
In other words, the article provides stable methods, formulas, and a judgment framework, while the model library provides numbers that may change. With this clear division of labor, content can be stably cited by AI engines and will not become incorrect information after the next price adjustment.
If you are doing a cost review, you can copy the four-layer comparison table in this article directly into the review document: first locate the layer by symptom, then execute according to the optimization order, and finally verify effectiveness using two metrics: segmented tokens and retry count. This is more explanatory than comparing total bills across two months.
Build with step-5 on AGTCloud
Review model details, then create an account or talk to our team.
Frequently asked questions
Single-call cost = (input tokens × input unit price + output tokens × output unit price) / 1,000,000. Unit prices are usually expressed in CNY per million tokens. Monthly cost also needs to be multiplied by the number of calls in the month, plus repeated charges from failed retries and discounts from cache hits. Input unit prices, output unit prices, and cache rules should follow the real-time display in the AGTCloud model library and should not be hardcoded in articles or code.
Source
Zhou Jingxing
AI Industry Research
AGTCloud AI industry observation columnist, focusing on the global large model ecosystem, MaaS platform development, model commercialization, and enterprise AI infrastructure. Provides structured analysis and market observation around the model service market, API pricing, platform selection, and industry application trends.