Workspace/Coding labs
Loading progress

Reconcile a deduplicated token-cost ledger

Advanced60 min

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

  1. Require exact row keys, nonempty string IDs and model names, nonnegative integer token counts excluding booleans, and cached <= input.
  2. Rates must contain three nonnegative finite numeric values for every referenced model; missing or invalid rates raise ValueError.
  3. An identical duplicate ID represents redelivered telemetry and is counted once. The same ID with any changed row field raises ValueError.
  4. Calculate cost as ((input - cached) * ordinary_rate + cached * cached_rate + output * output_rate) / 1_000_000.
  5. 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.
  6. 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}

Rates are invented for this exercise.
solution.pyPython 3.12