How to track LLM API costs by API key and model
Match requests to billed usage, group LLM API costs by key and model, and reconcile client subtotals with an auditable CSV example.
To track LLM API costs by API key and model, start with billed usage rows. Map each key to a customer or project, sum the posted USD amounts by customer and model, and keep an explicit unassigned subtotal. The report is ready to hand off when customer subtotals plus unassigned usage equal the gateway usage total for the same team, dates, time zone, currency and charge types. Keep a wallet top-up on a separate funding line.
1. Make a key-to-customer map
Use a separate key for each billing owner when possible. Keep the key’s internal ID or stable alias, customer, environment and effective dates in a restricted mapping table. Use the identifiers in your usage data and never copy the credential itself. During a key rotation, keep the old ID in the map until its last billing period has closed. If projects share a key and you did not record an authorized attribution identifier at call time, leave those rows unassigned until you have evidence to split them.
Pick a closed reporting window, such as December 1 at 00:00 through the start of December 2 in your console’s time zone. Reuse the same boundaries for your usage total and every customer subtotal. For a long-lived customer or key mapping, apply the ownership in force at the time of the request.
2. Match a request to a billed usage row
In Ofox, open Activity, then filter by date, API Key and Model. Use the documented Activity fields to read the request’s Cost. In Analytics, use the same scope and compare the totals under usage by API key and usage by model. These two views help locate differences but can overlap. Sum the underlying rows once.
To build your own cross-check, send a short synthetic request with the Ofox key you control and one model you can access. Save the start and end times with a time zone. Keep the reported model, request identifier when available and token counts from the Chat Completions response. Match by a shared identifier if you have one. If it is unavailable, use a narrow window and accept a match only when the model and token counts point to one usage row. Pairing on time alone is risky when concurrent calls look alike.
On December 3, 2026, we sent two synthetic requests through one Ofox key. Each returned HTTP 200 and the exact short text we requested. The reported models and token counts matched the following Activity rows.
| Activity time (UTC+8) | Model | Input tokens | Output tokens | Activity cost (USD) |
|---|---|---|---|---|
| 11:20:00 | z-ai/glm-5.3-flash | 29 | 148 | $0.00007835 |
| 11:20:07 | google/gemini-3.5-flash | 18 | 168 | $0.00153900 |
The observed total for this key was $0.00161735 across these two requests. Each model contributes its own row to that total. This check establishes how two real entries matched. The rows reflect these requests, and a new run can produce different usage and charges.
3. Reconcile a CSV before rebilling
The synthetic exercise below works without an API key. Save it as usage.csv. Amounts are posted USD entries. The second execution a2 has its own ledger ID, then appears again in an overlapping pull. Entry a3 is a posted credit. The key legacy does not yet have an owner.
row_id,key_alias,model,amount_usd
a1,alpha,model-x,0.004
a2,alpha,model-x,0.006
a2,alpha,model-x,0.006
a3,alpha,model-x,-0.001
b1,beta,model-y,0.002
c1,legacy,model-y,0.003
Run the following as python3 reconcile.py in the same directory. For your own ledger, normalize the key names, model and posted amounts into these columns. Use the provider’s immutable ledger ID when available. A request ID alone may be shared by a debit and its later adjustment.
import csv
from collections import defaultdict
from decimal import Decimal
owners = {"alpha": "Client A", "beta": "Client B"}
seen = {}
totals = defaultdict(Decimal)
with open("usage.csv", newline="", encoding="utf-8") as source:
for row in csv.DictReader(source):
row_id = row["row_id"].strip()
key = row["key_alias"].strip()
model = row["model"].strip()
amount = Decimal(row["amount_usd"])
if not row_id or not model or not amount.is_finite():
raise ValueError("Missing row ID, model, or valid amount")
entry = (key, model, amount)
if row_id in seen:
if seen[row_id] != entry:
raise ValueError(f"Conflicting entries for {row_id}")
continue
seen[row_id] = entry
totals[(owners.get(key, "Unassigned"), model)] += amount
for (owner, model), amount in sorted(totals.items()):
print(f"{owner} | {model} | {amount:f}")
print(f"Total USD | {sum(totals.values(), Decimal('0')):f}")
Expected output is Client A / model-x $0.009, Client B / model-y $0.002, and Unassigned / model-y $0.003. The total is $0.014. Match it to the independently obtained gateway usage total for the same window. The exercise deduplicates overlapping extracts, keeps individually posted retries and applies a credit only when it exists as a separate entry. Sum exact decimals and round only at the reporting boundary.
4. Explain any difference before closing the period
| Symptom | What to check |
|---|---|
| One app task has several records | Keep every distinct attempt that posted a charge. An app retry can issue a separate request. A provider-internal fallback may have different billing semantics. Use the ledger, and see how to tell when a fallback actually ran. |
| Your client timed out | Check Activity for a matching record and final cost. Keep uncertain outcomes open until they settle. For repeated requests, diagnose the rate-limit code before retrying. |
| Some usage has no owner | Inspect retired and shared keys, the effective dates and the team filter. Carry unmatched rows into the handoff as a separate line with a next check. |
| Usage and invoice show different totals | Compare the same window and basis first. Identify separately listed taxes, funding, credits and adjustments. Ask for a line-item explanation when the provider does not expose enough detail to reconcile the difference. |
Create a handoff with the team, window and time zone, the reported usage total, customer-and-model subtotals, the unassigned subtotal and its causes. Record what you have independently reconciled. A console summary, exported usage data and a tax invoice serve different tasks. Check what export or invoice the provider actually offers before relying on either. For a first-time gateway trial, use the model, routing and billing verification checklist alongside this ledger.


