A $900 Billion Inference Bill: Breaking Down AI Costs in Python
When inference spend reaches extreme scale, the real risk is usually a broken cost structure—not the headline model price. This article shows how to normalize usage, price, and adjustment factors in Python, attribute costs from request logs, reconcile estimates with actual invoices, and close the loop with budgets, alerts, and depth-tier routing.
When AI inference bills reach hundreds of billions, the real danger is often not the unit price of a model. It is a cost structure that has slipped out of control: overuse of high reasoning-depth tiers, unbounded context growth, repeated retries, falling cache hit rates, failed requests that still generate charges, and multiple product lines sharing one invoice with no attribution. Once a service bills by “thinking depth,” prices can differ by several times. One bad routing decision can send a cheap task into an expensive tier. Cost control then has to move from after-the-fact finance into architecture, logs, routing, and budget enforcement.
This article has one goal: use Python to make an AI inference bill understandable. The core idea is to normalize every charge into usage × unit price × adjustment factor, attribute spend from unified request logs, then feed the results into budgets, alerts, and routing so cost governance can iterate.
1. Start with a general cost model, not a single price
Vendors may bill on input units, output units, tier multipliers, internal reasoning units, call counts, or a mix. Do not hard-code one billing style into application code. Abstract a price table and multiply it by usage records.
A single request can be written as:
C_req = fixed_fee+ input_units × P_input(plan, tier)+ output_units × P_output(plan, tier)+ extra_units × P_extra(plan, tier)× cache_factor+ retry_overhead
plan is the model or service plan; tier is the reasoning-depth band; cache_factor is the billed fraction after a cache hit; retry_overhead is extra cost from retries. If a vendor does not expose “reasoning usage,” treat the tier as a multiplier and calibrate it from real invoices.
Total cost:
C_total = Σ C_req + storage and log allocation + monitoring and ops allocation + network and gateway allocation
At extreme bill scale, infrastructure allocation matters, but first split the inference calls that run away fastest. Record at least:
- Request and tracing:
request_id,trace_id - Business attribution:
tenant_id,scene,prompt_version - Billing dimensions:
plan_name,depth_tier,input_tokens,output_tokens - Quality and failure:
status,error_type,attempt - Cache and retry:
cache_hit,retry_of - Time and region:
timestamp,region
Do not keep only totals. Without request-level detail you cannot answer which tenant, scene, prompt version, or tier drove the bill.
2. Price tables and a per-request cost function in Python
The sample uses the Python standard library and Decimal to avoid float error. Prices are placeholders; production must load them from contracts and real invoices.
from dataclasses import dataclassfrom decimal import Decimal, ROUND_HALF_UPfrom typing import MappingM = Decimal("1000000")@dataclass(frozen=True)class PricePlan:name: strinput_per_million: Decimaloutput_per_million: Decimaltier_multiplier: Decimal = Decimal("1.0")fixed_per_call: Decimal = Decimal("0")cache_read_ratio: Decimal = Decimal("1.0") # billed fraction after cache hit; calibrate from invoices@dataclassclass UsageRecord:request_id: strtenant: strscene: strplan_name: strtier: strinput_tokens: intoutput_tokens: intcache_hit: bool = Falseretries: int = 0success: bool = Truedef quant(value: Decimal) -> Decimal:return value.quantize(Decimal("0.000001"), rounding=ROUND_HALF_UP)def tier_factor(tier: str,plan: PricePlan,multiplier_table: Mapping[str, Decimal] | None = None,) -> Decimal:if multiplier_table and tier in multiplier_table:return multiplier_table[tier]return plan.tier_multiplierdef request_cost(u: UsageRecord,plan: PricePlan,multiplier_table: Mapping[str, Decimal] | None = None,) -> Decimal:k = tier_factor(u.tier, plan, multiplier_table)input_cost = Decimal(u.input_tokens) / M * plan.input_per_millionoutput_cost = Decimal(u.output_tokens) / M * plan.output_per_millionvariable_cost = (input_cost + output_cost) * kif u.cache_hit:variable_cost *= plan.cache_read_ratiofixed_cost = plan.fixed_per_call * (Decimal("1") + Decimal(u.retries))return quant(fixed_cost + variable_cost)
Three engineering constraints matter more than syntax:
- Keep the price table separate from business logic. Model prices, tier multipliers, and cache ratios should be configurable so a price change does not require code changes.
- Store only the metadata you need. Do not keep full prompts or user privacy in cost logs; keep meters, versions, and de-identified business IDs.
- Record retries separately. The sample folds retries into a fixed fee. Production should write each attempt as its own record and link it with
retry_of, so failed retries are distinct from normal multi-call workflows.
3. From logs to a monthly bill: attribution in Python
With a per-request function, aggregate by tenant, scene, tier, and time. The sample reads line-delimited JSON and computes total cost, tenant cost, scene cost, tier cost, and average cost per successful request by scene.
from collections import defaultdictimport jsondef aggregate_costs(path, prices, multiplier_table):total = Decimal("0")by_tenant = defaultdict(Decimal)by_scene = defaultdict(Decimal)by_tier = defaultdict(Decimal)scene_success = defaultdict(int)scene_cost = defaultdict(Decimal)with open(path, "r", encoding="utf-8") as f:for line in f:raw = json.loads(line)plan = prices[raw["plan_name"]]u = UsageRecord(request_id=raw["request_id"],tenant=raw["tenant_id"],scene=raw["scene"],plan_name=raw["plan_name"],tier=raw["depth_tier"],input_tokens=int(raw["input_tokens"]),output_tokens=int(raw["output_tokens"]),cache_hit=bool(raw.get("cache_hit", False)),retries=int(raw.get("retries", 0)),success=raw.get("status") == "ok",)c = request_cost(u, plan, multiplier_table)total += cby_tenant[u.tenant] += cby_scene[u.scene] += cby_tier[u.tier] += cscene_cost[u.scene] += cif u.success:scene_success[u.scene] += 1scene_unit_cost = {}for scene, cost in scene_cost.items():ok = scene_success[scene]scene_unit_cost[scene] = (quant(cost / Decimal(ok)) if ok > 0 else None)return {"total": total,"by_tenant": dict(by_tenant),"by_scene": dict(by_scene),"by_tier": dict(by_tier),"scene_unit_cost": scene_unit_cost,}
Use this for daily reports. In production, add three views:
- Trend: daily total cost, per-call cost, successful-request cost, and tier mix
- Anomaly: high-cost tenants, scenes with unusual high-depth share, rising retry rates
- Reconciliation: estimated cost vs. actual invoice by day and service, to locate gaps
4. Reconcile estimates against the real invoice
The model will not be exact at first. Cache billing, free quotas, volume tiers, failed-request charges, tax, currency, settlement windows, and discounts all create drift. Treat the invoice as ground truth and calibrate coefficients by price line and tier, for example:
effective_multiplier(tier) = actual_billed_cost(tier) / estimated_base_cost(tier)
Compute estimated_base_cost from base unit prices and usage, then let effective_multiplier absorb tier multipliers, discounts, and unmodeled factors. Keep the time window and version; do not freeze one month of data forever. Recalibrate after price changes, mix shifts, or cache-policy changes.
Watch whether variance concentrates in certain tiers; whether it comes from free quota, volume pricing, or cache hits; whether failures and timeouts are billed; whether retries are double-counted; whether cross-day requests land in the right settlement period; and whether business logs have unknown scene values or empty tenants.
5. Attribute attention to cost per successful request and tier-uplift cost
A total bill only says “this month was higher.” More useful metrics:
- Average cost per request: total cost / request count
- Cost per successful request: total cost / successful requests (failures and retries become a quality factor)
- Cost per business unit: total cost / business events (ticket processed, RAG completion, reviewable summary)
- Tier-uplift cost: high-depth cost / equivalent low-depth cost (did extra reasoning buy quality?)
- Retry cost share: retry cost / total cost
- Cache savings rate: theoretical savings vs. misses, always checked against real billing rules
Watch silent upgrades under tiered pricing. A simple extraction job routed to a high-depth tier can cost several times a low tier. If those requests dominate volume, the bill is structurally inflated. Cross-tab scene × tier finds this quickly.
6. Budgets, alerts, and forecasts: daily control, not month-end surprise
At this scale, monthly reports are too late. You need daily budget burn, daily anomaly alerts, and rolling forecasts.
A simple forecast:
forecast_30d = (7-day average daily cost × 0.7 + 28-day average daily cost × 0.3)× 30× growth_adjustment
Growth adjustment comes from request-volume forecasts, campaigns, and history. If you cannot forecast, use budget burn: month-to-date cost / monthly budget. Alert when burn is well ahead of calendar time.
Suggested alerts: daily cost above a budget baseline; tenant or scene cost jumping vs. the prior period; high-depth cost share over a threshold; rising cost per successful request; retry rate spikes; sudden cache-hit drops; input/output length drift; reconciliation error beyond tolerance.
Do not leave budgets only in finance systems. Put quotas, hard caps, and degrade paths at the call entry or gateway: per-tenant daily quotas, overflow into a low-frequency queue, non-critical work demoted to a cheaper tier, or a required temporary budget request. Every degrade needs a quality check; cutting cost must not blindly damage outcomes.
7. Routing under depth-tier pricing: the cheapest sufficient tier
Depth-based pricing ties cost to reasoning complexity. When prices differ by several times, every request should not use the same tier. The goal is the lowest-cost tier that still meets a quality floor:
choose tierthat minimizes cost(tier)subject to quality(tier, task) >= quality_floorand cost_total <= budget
Quality cannot be guessed. Calibrate with offline eval sets, online A/B tests, and human sampling.
def choose_tier(task, tiers, quality_floor, budget_left, expected_units):feasible = []for tier in tiers:predicted_quality = estimate_quality(task, tier)predicted_cost = estimate_cost(task, tier, expected_units)if predicted_quality >= quality_floor and predicted_cost <= budget_left:feasible.append((tier, predicted_cost))if feasible:return min(feasible, key=lambda item: item[1])[0]# No feasible option: pick cheapest tier; upper layers queue, degrade, or rejectreturn min(tiers, key=lambda t: estimate_cost(task, t, expected_units))
Principles: classification, extraction, and format conversion prefer low depth; multi-step reasoning, planning, and code review may use high depth; new policies start on shadow traffic, then gradual rollout; keep an eval set per scene; reserve budget for high-value tenants and scenes; cap timeout and failure retries so retries do not explode the bill.
8. Cost-reduction checklist: input, output, depth, retries, and cache
Do not rely only on switching to a cheaper model. Govern the full request lifecycle.
Input: compress context, drop duplicate system prompts, trim unused retrieval chunks, keep necessary conversation summaries; cap very long inputs and ask users to shorten descriptions. For stable reusable prefixes, evaluate cache savings under real billing rules.
Output: set max length, stop conditions, and structured-output constraints; specify fields and length for summaries and classification.
Depth: scene-level tier policy; compare quality and cost on small traffic, then expand. Treat high-depth as a budgeted resource, not the default.
Retries: retry only transient errors, with backoff and a max count; idempotency keys for non-idempotent calls; include retry cost in cost-per-success, not hide it in call volume.
Cache: cache stable Q&A, knowledge items, and repeated queries with sensible TTLs; keys must include tenant, permission scope, and version. Whether cache saves money depends on billing; verify with invoice reconciliation.
Scheduling: move non-real-time work to async queues in cheaper windows; batch where possible; give low-priority jobs a delay window.
9. A minimal loop you can run in a week
First, complete request-level metering: tenant, scene, plan, tier, input/output usage, cache hits, retries. Start with line-delimited JSON, then plug into log services, object storage, and monitoring.
Second, configure the price table and tier multipliers. A first version can use public or contract prices, then calibrate from invoices.
Third, run aggregation daily: tenant, scene, and tier reports, plus budget burn and cost per successful request.
Fourth, pick two or three expensive scenes for routing experiments. Use an offline eval set for a quality floor; compare accuracy, latency, and cost across tiers; then set a rollout fraction.
Fifth, wire alerts and hard quotas into the call path. On abnormal growth, throttle non-critical traffic first, then inspect logs and billing definitions so you do not harm core product with a blunt cutoff.
The result is not a static spreadsheet. It is a system that can keep running: request records explain the bill, the price table absorbs rule changes, Python aggregation gives daily attribution, budget alerts surface risk early, and tier routing keeps spend in range. The larger the bill, the more that engineering breakdown is worth.
