How to Calculate AI Inference Costs with Python

    A practical guide to building a reproducible AI inference cost model in Python. Learn how to model tiered pricing with immutable data structures, count input, output, and cached tokens accurately, derive per-call costs, aggregate spending by business dimension, and apply budget guardrails to avoid runaway bills.

    1. Why Inference Bills Get Out of Control

    When enterprises move large workloads to online inference services, the cost structure changes fundamentally. Spending that used to be dominated by fixed resource packages becomes a variable cost that grows linearly with request volume.

    Bills rarely spiral because the unit price is high. They spiral because of three overlooked multipliers: context length, output length, and call volume. Multiply the three together, then add retries, failed-request replays, and debugging traffic, and you get a large bill that is hard to attribute to any single source.

    Pricing models make this worse. Mainstream usage-based billing generally uses tiered input/output pricing, where input tokens and output tokens have different unit prices, with output usually costing significantly more. Prices are also split into tiers by model capability, and higher tiers cost more. A tiny prompt change can push a request into a higher tier and cause the cost to jump.

    So the first step in cost governance is not to cut the budget. It is to build a reproducible metering model: every call can be broken down into an explainable token composition, and every charge can be traced back to a specific business scenario.

    2. Modeling Approach: Treat Pricing as Immutable Data Structures

    To make the model testable and auditable, use immutable data classes to describe tiers and pricing rules. The example below expresses generic billing semantics only and contains no vendor-specific parameters:

    1. from dataclasses import dataclass
    2. from typing import Iterable
    3. @dataclass(frozen=True)
    4. class Tier:
    5. name: str
    6. input_price: float # price per million input tokens
    7. output_price: float # price per million output tokens
    8. @dataclass(frozen=True)
    9. class Quote:
    10. tiers: tuple[Tier, ...]
    11. cache_read_discount: float = 0.0 # discount for cache-hit reads; 0 means no discount
    12. batch_discount: float = 0.0 # discount for offline batch processing
    13. free_quota: int = 0 # free quota (in tokens)

    Three design choices matter here. First, frozen=True keeps the pricing table from being modified accidentally at runtime, preventing the situation where “the live price is silently changed by code.” Second, separating discounts and free quota from tiers makes sensitivity analysis easier. Third, standardizing all prices to “per million tokens” removes unit ambiguity, which is the source of most cost estimation errors.

    3. The Metering Layer: How to Actually Count Tokens

    The accuracy of a cost model is capped by the accuracy of its metering. In practice, distinguish three token categories:

    • Input tokens: system prompts, conversation history, and document chunks injected by retrieval augmentation.
    • Output tokens: content generated by the model.
    • Cache-related tokens: reused prefix portions, usually billed at a lower price.

    A common mistake is to count only user-visible text. In retrieval-augmented scenarios, the real cost driver is often the document blocks stitched into the context. Record a structured metering object for every call:

    1. @dataclass(frozen=True)
    2. class Usage:
    3. tier: str
    4. input_tokens: int
    5. output_tokens: int
    6. cached_input_tokens: int = 0
    7. is_batch: bool = False

    With a unified metering object, you can aggregate and attribute costs. If the business side cannot get exact token counts, estimate them with “character count divided by an empirical factor,” but always annotate the error range and never treat estimates as a basis for settlement.

    4. The Pricing Core: From One Call to One Charge

    Let a tier have input price p_in, output price p_out, cache read discount d_cache, and batch discount d_batch. The cost of a single call can be written as:

    1. billable_in = max(0, input_tokens - cached_input_tokens) + cached_input_tokens * (1 - d_cache)
    2. cost = (billable_in * p_in + output_tokens * p_out) / 1_000_000 * (1 - d_batch if is_batch else 1)

    The corresponding implementation:

    1. def estimate(u: Usage, q: Quote) -> float:
    2. t = next(t for t in q.tiers if t.name == u.tier)
    3. cached = min(u.cached_input_tokens, u.input_tokens)
    4. fresh = u.input_tokens - cached
    5. billable_in = fresh + cached * (1 - q.cache_read_discount)
    6. cost = (billable_in * t.input_price + u.output_tokens * t.output_price) / 1e6
    7. if u.is_batch:
    8. cost *= (1 - q.batch_discount)
    9. return max(0.0, cost - 0) # free quota is deducted at the aggregation layer

    The free quota is applied at the aggregation layer rather than per call because quotas are usually settled monthly or per account cycle. Deducting them call by call would make the accounting inconsistent.

    5. From One Call to Scale: Aggregation, Attribution, and Budget Guardrails

    A real bill is the sum of massive numbers of calls. Build aggregation keys along three dimensions: business line / scenario / model tier, and output a cost heatmap:

    1. from collections import defaultdict
    2. def aggregate(usages: Iterable[Usage], q: Quote) -> dict:
    3. agg = defaultdict(lambda: [0, 0, 0, 0.0]) # in, out, cached, cost
    4. for u in usages:
    5. k = (u.tier, u.is_batch)
    6. a = agg[k]
    7. a[0] += u.input_tokens
    8. a[1] += u.output_tokens
    9. a[2] += u.cached_input_tokens
    10. a[3] += estimate(u, q)
    11. remaining = q.free_quota
    12. for a in agg.values():
    13. used = min(remaining, a[0])
    14. a[0] -= used
    15. remaining -= used
    16. return dict(agg)

    For guardrails, mature teams usually do three things: set a monthly token budget per scenario with monitoring and alerts; enforce hard limits on requests with overly long contexts; and route non-critical paths to the offline batch channel by default. Together, these three can cut a meaningful share of spending without changing business logic.

    6. Common Cost Traps and Optimization Levers

    1. Context bloat: Multi-turn conversations concatenate history without trimming, so input tokens grow quadratically. The fix is a sliding window plus summary compression.
    2. Runaway output: Without a maximum output length constraint, the model can generate thousands of tokens in abnormal cases. The fix is to set a cap and add business fallback for truncation.
    3. Retry amplification: Timeout retries without backoff and deduplication double costs during incidents. The fix is tracing and idempotency keys.
    4. Tier misuse: Simple tasks run on the highest tier. The fix is a “task difficulty to tier” routing layer that sends high-frequency simple requests to lighter tiers.
    5. Cache misses: Frequent changes to the prompt prefix break reuse. The fix is to put stable instructions first and variables last.

    7. Implementation Recommendations

    Wire the model into CI and run cost regression tests by replaying historical traffic. Every time you adjust a prompt or routing policy, you can see how much the cost curve moves. Keep version records of the pricing table so any historical bill can be recalculated precisely. Once metering, pricing, attribution, and guardrails form a closed loop, the bill stops being a month-end surprise and becomes an engineering metric you can tune at any time. If an organization already uses relevant Baidu AI Cloud products, it can combine this model with general monitoring, alerting, and logging services to bring cost data into a unified observability system, shifting from passive payment to active cost management.