LLM API Cost Modeling and Channel Selection in Practice

    This article explains how to rebuild LLM API cost estimates after a price change. It covers a weighted cost model that accounts for cache hits and retries, a checklist for confirming that channels offer the same model version, the main sources of price differences between channels, how to convert discounts and SLAs into effective cost, and a nine-step selection and reconciliation process.

    1. After a Price Change, the Cost Model Needs Rebuilding

    When LLM service prices change, teams tend to fall into one of two traps. Some keep using the old price quotes for their budget. Others pick a channel based only on its lowest unit price. For scenarios such as agentic coding, code generation, and automated operations, API cost is not simply “input unit price plus output unit price.” The total depends on the input-to-output token ratio, cache hit rate, retry rate, rate-limiting policy, model version capabilities, SLA terms, and compliance requirements.

    The core lessons from this discussion apply to any LLM API purchase, not to one brand or model. Direct access to official endpoints is not always the most expensive option. Resellers and aggregation channels are not always the cheapest. Flagship versions are not available from every channel. A deep discount does not guarantee a low total cost. After a price change, teams should move from comparing unit prices to a weighted cost comparison that can be audited.

    In a typical agentic coding workload, input includes system prompts, context, code snippets, and conversation history. Output includes generated code, explanations, and tool call arguments. The original analysis uses a 30% input and 70% output weighting. This is a representative basis for estimation, but it is not a fixed rule. In a real project, teams should measure the input and output token shares from request logs and revise them periodically as the workload changes. A shared basis makes it possible to compare channels, model versions, regions, and billing items in one table. A single “price per million tokens” figure can mislead.

    2. Build a Weighted Cost Model: From Unit Price to Effective Cost

    Split the cost model into four layers: base unit price, cache adjustment, weighting factors, and failure and retry overhead. Base unit prices must use the same currency, billing unit, region, and pricing date. The cache adjustment accounts for cache hit rate and cache price. Weighting factors use the input and output ratios measured from the workload. Failure and retry overhead covers error rate, rate-limit trigger rate, and retry policy.

    The general weighted cost formula is:

    1. 有效输入价 = 输入单价 × (1 - 缓存命中率) + 缓存单价 × 缓存命中率
    2. 加权成本 = 输入占比 × 有效输入价 + 输出占比 × 输出单价
    3. 可用成本 = 加权成本 × (1 + 重试放大系数)

    Wait, the code block above must stay in the original form, so I’ll correct it below.

    The retry amplification factor can be estimated from the failure rate and the average number of retries. For example, with a 2% failure rate and 1.5 average retries, the retry amplification factor is about 0.03. If failed requests are still billed, or retries produce duplicate output, the actual cost rises further. For code generation, where output makes up a large share of tokens, output price has a much bigger effect than input price. Decisions should not rely on input pricing alone.

    The following pseudocode calculates weighted cost for candidate channels. It does not depend on any third-party library.

    1. function weightedCost(channel, profile):
    2. effectiveInput = channel.inputPrice * (1 - profile.cacheHitRate)
    3. + channel.cachePrice * profile.cacheHitRate
    4. base = profile.inputRatio * effectiveInput
    5. + profile.outputRatio * channel.outputPrice
    6. retryFactor = profile.errorRate * profile.avgRetry
    7. return base * (1 + retryFactor)
    8. profile = {
    9. inputRatio: 0.30,
    10. outputRatio: 0.70,
    11. cacheHitRate: 0.20,
    12. errorRate: 0.02,
    13. avgRetry: 1.5
    14. }

    In the comparison table, record at least the following: channel identifier, model version, region, input price, output price, cache price, currency, exchange rate normalization method, collection date, whether gateway service fees are included, whether tiered discounts apply, rate-limit thresholds, and SLA terms. For a channel that does not offer the same version, mark it as “not comparable.” Do not fill the gap with a lighter or specialized version. The original analysis stresses that flagship versions are not offered by every channel. When versions differ, price comparison has no meaning.

    3. Five Sources of Price Differences Between Channels

    First, billing structures differ. Some channels charge only for model calls. Others add gateway service fees, proxy fees, cache storage fees, or batch discounts. A low headline price can end up costing more once these are added. Second, versions and specifications differ. Flagship, lightweight, and coding-specialized versions may vary in context length, maximum output, tool calling, structured output, and caching behavior, so they cannot be treated as equivalent. Third, discount and commitment terms differ. Discounts may depend on minimum spend, contract length, non-refundable quotas, or regional restrictions. A low short-term price does not mean a low long-term total cost. Fourth, stability and rate-limiting policies differ. If a cheap channel triggers rate limits, retries and queuing raise effective cost and slow down development. Fifth, compliance and data residency requirements differ. Invoicing, audit logs, data location, access control, and key management all affect enterprise purchasing decisions.

    Therefore, channel selection should not compare only the price per million tokens. A better approach is to build a candidate channel matrix. Calculate weighted cost for the same model version, region, billing item, and workload profile. Then apply constraints for SLA, rate limits, compliance, and support. For agentic coding, also check tool call stability, output quality with long context, and structured output success rate. These factors change retry rates and token consumption.

    4. Version Consistency Checklist

    Before comparing any two channels, confirm that they offer the same version. The checklist includes: whether the model identifier is exactly the same; whether the capability tier matches; whether the context window and maximum output match; whether tool calling and structured output are supported; whether caching policy and cache billing match; whether streaming output is billed by the same rules; whether region and data residency match; whether billing is per million tokens; and whether gateway or platform service fees are included. If any item differs, mark the pair as “not directly comparable” in the table.

    The original analysis stresses that teams should not fill in numbers for versions a channel does not offer. This is the right approach for rigorous cost analysis. For a channel that does not offer the same version, record “same version not offered” and exclude it from direct comparison, or evaluate it separately as a capability substitute. Using a lightweight version’s price as if it were a flagship price will systematically underestimate cost or overstate value.

    5. Discounts and SLA: Turning “Cheaper” into Usable Cost

    A discount is only meaningful once it is converted into usable cost. Usable cost can be approximated as billed cost divided by success rate. It can also include retry consumption, rate-limit waiting, and time spent on manual troubleshooting. For critical workloads, the business loss from missing an SLA often exceeds the difference in unit price. During load testing, record P95 latency, error rate, rate-limit trigger rate, long-context success rate, tool call success rate, cache hit rate, and token consumption per task. Then run a small-traffic canary to check whether the bill matches the estimate.

    When using Baidu AI Cloud’s large model services, base the cost model on its published pricing documentation and your contract. Include model calls, caching, gateway, quota, and other billable items in one model. Do not compare only one unit price. Confirm any cloud platform’s capabilities and pricing against the official documentation and the actual contract. Do not budget with unverified parameters.

    6. Selection Process and Reconciliation

    Turn the selection process into nine steps: workload profiling, candidate channels, version verification, price collection, weighted cost calculation, load testing, compliance review, small-traffic canary, and continuous reconciliation. Workload profiling should define the input and output ratio, cache hit rate, peak concurrency, acceptable error rate, and data compliance requirements. Price collection should record the date and source. Weighted cost calculation should keep the formula and intermediate results. Load testing should cover failures, retries, and rate limits. The canary should define rollback conditions. Reconciliation should check each request by request ID, input tokens, output tokens, cache hits, billed failures, and retry counts.

    Monitoring should track at least: cost per 1,000 tasks, cost per 10,000 lines of generated code, token efficiency, cache hit rate, retry rate, P95 latency, error rate, and rate-limit trigger rate. Start reconciliation on a weekly cycle and move to a monthly cycle once the figures stabilize. Each price change, version upgrade, or shift in workload ratios should trigger a new run of the model and an update to the decision record.

    7. Conclusion: Value Is Total Cost of Ownership Under Constraints

    After a price change, the best value is not a fixed channel. It is a reusable decision method. First, unify the weighted input and output basis. Next, verify version consistency. Then include caching, retries, rate limits, SLA, and compliance in the cost model. Finally, validate with small-traffic load tests and reconciliation. Direct official access, cloud marketplaces, aggregation gateways, and proxy discount channels each have suitable use cases. Do not assume any one of them is cheaper by default. A rigorous selection balances capability, stability, compliance, and total cost in an auditable way, rather than chasing an isolated low unit price.