Reconcile a deduplicated token-cost ledger
Implement bill_usage(rows, rates). Each row has id, model, input, cached, output. Input includes the cached subset. Rates maps model to ordinary-input, cached-input, and output prices per million tokens. Return total, by_model, and unique_calls.
Your task
- Require exact row keys, nonempty string IDs and model names, nonnegative integer token counts excluding booleans, and cached <= input.
- Rates must contain three nonnegative finite numeric values for every referenced model; missing or invalid rates raise ValueError.
- An identical duplicate ID represents redelivered telemetry and is counted once. The same ID with any changed row field raises ValueError.
- Calculate cost as ((input - cached) * ordinary_rate + cached * cached_rate + output * output_rate) / 1_000_000.
- Use Decimal from string-converted rates for intermediate arithmetic and return floats for total and by_model. Empty rows return total 0.0, empty by_model, and unique_calls zero.
- Do not invent missing usage or deduplicate separate retry attempts with different IDs.
Examples
EXAMPLE 1
Inputbill_usage([{"id":"a","model":"small","input":12000,"cached":9000,"output":1000}], {"small":(2,0.2,8)})
Output{"total": 0.0158, "by_model": {"small": 0.0158}, "unique_calls": 1}
Implement the function, then run the tests.
Ctrl / ⌘ + Enter to test · Shift + Tab leaves editor