ノート / 10

Per-request LLM cost accounting in micro-dollars

2026-11-17Modelry のノート

Token pricing is a three-part formula with a time-dependent multiplier, and the obvious implementation — floats, rounded per term — drifts far enough to break reconciliation by the end of a month. This article builds a ledger that works the way a metering service does: rates as Decimal, a single ceiling to the nearest micro-dollar per request, integers accumulated in the database, and the rate chosen by the moment the request *arrived* rather than the moment it finished. It includes the peak-window test in UTC, a check against a published worked example, and the three arithmetic mistakes that make your dashboard disagree with your usage statement.

The formula, and why micro-dollars

Cost is uncached_input × in_rate + cached_input × cached_rate + output × out_rate, each term divided by one million. Rounding happens once, upward, to one micro-dollar ($0.000001) — no per-request minimum fee, no rounding to cents. That last property is what makes micro-dollars the right unit: a single small request can genuinely cost three thousandths of a cent, and a ledger that stores cents loses 99% of its information.

There is a neat consequence worth knowing. Rates are quoted in USD per million tokens, and micro-dollars are millionths of a dollar, so tokens × rate is already in micro-dollars. No division, no scale factor, no place to lose a factor of a thousand:

#!/usr/bin/env python3
"""ledger.py — per-request cost accounting in integer micro-dollars."""
from dataclasses import dataclass, field
from datetime import datetime, timezone
from decimal import Decimal, ROUND_CEILING

# USD per 1M tokens, off-peak. Verify against the provider's live pricing page
# before trusting any number in a report: rates change, and a stale constant is
# the most common cause of a ledger that disagrees with a usage statement.
RATES: dict[str, dict[str, Decimal]] = {
    "deepseek-chat":     {"in": Decimal("0.25"), "cached": Decimal("0.006"), "out": Decimal("1.45")},
    "deepseek-reasoner": {"in": Decimal("1.10"), "cached": Decimal("0.044"), "out": Decimal("4.75")},
}

# Peak windows, UTC, Monday to Friday. Peak is exactly 2x off-peak.
PEAK_WINDOWS = ((60, 240), (360, 600))     # 01:00-04:00 and 06:00-10:00

def is_peak(started: datetime) -> bool:
    """The rate applied is the one in effect when the request arrives."""
    ts = started.astimezone(timezone.utc)
    if ts.weekday() >= 5:                  # Saturday, Sunday
        return False
    minutes = ts.hour * 60 + ts.minute
    return any(lo <= minutes < hi for lo, hi in PEAK_WINDOWS)

def cost_micro(model: str, prompt_tokens: int, cached_tokens: int,
               completion_tokens: int, peak: bool) -> int:
    rates = RATES[model]
    multiplier = Decimal(2) if peak else Decimal(1)
    uncached = max(prompt_tokens - cached_tokens, 0)     # cached is a SUBSET
    total = (
        Decimal(uncached) * rates["in"]
        + Decimal(cached_tokens) * rates["cached"]
        + Decimal(completion_tokens) * rates["out"]
    ) * multiplier
    return int(total.to_integral_value(rounding=ROUND_CEILING))

@dataclass
class Ledger:
    rows: list[dict] = field(default_factory=list)

    def record(self, *, model: str, started: datetime, usage: dict,
               request_id: str | None = None) -> int:
        prompt = int(usage.get("prompt_tokens", 0))
        details = usage.get("prompt_tokens_details") or {}
        cached = int(details.get("cached_tokens")
                     or usage.get("prompt_cache_hit_tokens") or 0)
        completion = int(usage.get("completion_tokens", 0))
        peak = is_peak(started)
        micro = cost_micro(model, prompt, cached, completion, peak)
        self.rows.append({
            "request_id": request_id, "model": model, "peak": peak,
            "prompt": prompt, "cached": cached, "completion": completion,
            "micro": micro, "usd": micro / 1_000_000,
        })
        return micro

    def total_micro(self) -> int:
        return sum(r["micro"] for r in self.rows)

if __name__ == "__main__":
    # Published worked example: chat, off-peak, 12,000 prompt of which 8,000 cached,
    # 800 output -> $0.002208, i.e. 2,208 micro-dollars.
    assert cost_micro("deepseek-chat", 12_000, 8_000, 800, peak=False) == 2_208
    assert cost_micro("deepseek-chat", 12_000, 8_000, 800, peak=True) == 4_416

    led = Ledger()
    example = {"prompt_tokens": 12_000, "completion_tokens": 800,
               "prompt_tokens_details": {"cached_tokens": 8_000}}
    started = datetime(2026, 11, 17, 3, 10, tzinfo=timezone.utc)     # inside peak 1
    micro = led.record(model="deepseek-chat", started=started,
                       usage=example, request_id="req_demo")
    print(f"request cost: {micro} micro-dollars = ${micro / 1_000_000:.6f}")
    print(f"ledger total: {led.total_micro()} micro-dollars")

Wrap the real client so a ledger row is written from the response's own usage and the timestamp you captured *before* sending:

started = datetime.now(timezone.utc)
resp = client.chat.completions.create(...)
ledger.record(model="deepseek-chat", started=started,
              usage=resp.usage.model_dump(), request_id=resp.id)

Reconciling against the usage statement

Two numbers must agree at month end: sum(micro)/1e6 from your ledger, and the platform's usage log. When they do not, the difference is almost always one of three things — a request whose usage was omitted upstream and settled from an estimate, a peak/off-peak boundary you classified differently, or a discount applied at settlement that your ledger does not model. Keep x-request-id on every row so a disagreement can be traced to a specific request instead of argued about in aggregate.

Failure 1: floats, and rounding the wrong thing

0.25/1_000_000 * 4000 is not exactly 0.001, and summing ten thousand such values accumulates visible error. Worse is rounding each term to cents: an individual request can cost less than a cent, so per-term rounding loses the entire charge. Do the arithmetic in Decimal, round once per request with ROUND_CEILING, and store int micro-dollars. Never store float dollars in a ledger table; convert for display only.

Failure 2: applying the peak rate at the wrong moment

The rate applied is the one in effect when the request arrives at the gateway, not when the stream finishes. A request that starts at 03:59 UTC and streams for two minutes is billed at the peak rate from its arrival; a request that starts at 00:59 is billed off-peak even though it finishes inside the window. If you timestamp at completion, a batch job that straddles a boundary produces a systematic mismatch that grows with latency — the least debuggable kind of error, because both numbers look plausible.

Failure 3: counting cached tokens twice

prompt_tokens already includes the cached tokens. Computing prompt × in_rate + cached × cached_rate bills the cached portion at the full input rate and then again at the cached rate, inflating cost by roughly the cached share. Split first — uncached = prompt - cached — then price the two halves separately. And read the cached count from *either* field name, because providers differ: prompt_tokens_details.cached_tokens and prompt_cache_hit_tokens both appear in the wild.

What to watch when you speak to a gateway instead of OpenAI

Metering is where a prepaid gateway differs most from a postpaid one. Pre-authorisation: the gateway freezes an estimate (prompt size plus max_tokens, plus a cushion) before the request reaches a provider, and a 402 means the freeze failed, not that the price was wrong — model that in your own capacity planning, because your effective ceiling is balance − frozen. Estimated rows: when a provider omits usage, the request settles from the estimate and the platform flags it; if a model reports estimated habitually, your ledger will drift in one direction, so count those rows and alert on the ratio. Discounts: subscription usage discounts are applied at settlement on top of the peak/off-peak rate, which means the statement total can be below your sum-of-list-prices by design — keep list price in the ledger, record the payable amount separately, and reconcile the two lines rather than blending them.

The columns that make a ledger useful

Store the request id, the model id, the arrival timestamp in UTC, the three token counts, the peak flag, the micro-dollar amount and a boolean for whether the usage was reported or estimated. That is enough to answer every question a finance review actually asks — which workload spends the most, how much of the spend is cacheable, whether a cost jump came from traffic or from a rate window — without storing anything about the content, which is the part you would rather not keep.

Run the ledger against a real key from https://tokenaimodels.com and compare one day of sum(micro) with your usage page — agreeing to the micro-dollar on a day that includes a peak boundary is the sign the accounting is actually right.

Modelry は、1つの HTTP endpoint の背後で DeepSeek モデルを提供するプラットフォームを運営しています。前払いクレジットと税務は購入時に merchant of record が処理し、データ保持方針も文書で公開しています。$0.50 分のトライアルクレジットから始められます: キーを作成する。

すべてのノート

Per-request LLM cost accounting in micro-dollars — Modelry