# A credit sold is not cost incurred: a per-call AI cost ledger behind credit pricing

By Farhad Rezaei (https://farhad-rezaei.com) · Published 2026-12-01
Canonical: https://farhad-rezaei.com/blog/a-credit-sold-is-not-cost-incurred
Product: MrPicasso (https://mrpicasso.ir)

> Customers pay in credits but providers bill in tokens, seconds and searches, so MrPicasso writes one cost row per model call: the model that actually answered, every unit the provider bills, a dated price and a reference to the image, thread or job. Unknown prices are recorded as unknown, failed attempts are counted, and an unreadable search allowance is treated as used up. The same rows give cost per image and per video job, plus a labelled estimate of what unused credits will cost.

MrPicasso (https://mrpicasso.ir) is the AI advertising studio where I lead engineering. People buy credit packages and spend credits on ad images and videos, made by image, text, search and video models from several providers. Providers bill in tokens, seconds and searches; customers pay in credits.

One detail shows how easily they drift. When a Gemini call grounds itself in Google Search, the results it reads back are billed as input, but the API reports them in a separate field, `toolUsePromptTokenCount`. In one of our test fixtures, a 1,000-token prompt reads 4,000 tokens of results, so billed input is 5,000 tokens. A meter reading only the prompt count sees a fifth. For people buying packages, accurate cost is what keeps a price fair: set from undercounted spend, a package either can't last or has to change suddenly.

## A prepaid coffee card

A café sells a card for ten coffees. The money arrives on day one, but the coffees haven't been made, and each cup's cost moves: beans get dearer, a spilled cup gets remade. An owner who counts every card sold as profit is wrong about what a cup costs and about the cups still owed. MrPicasso's credits are that card. This is how the backend counts the cups.

## One call, followed into the ledger

A user asks for an ad image. The model's response comes back with a usage block, and `meterGemini` or `meterOpenai` first asks which model answered: `servedModel` reads the response's own `modelVersion`, because the model requested isn't always the model billed. Then it reads every billed unit: prompt, cached and tool-use input, text and image output, thinking tokens, search queries.

`priceUsd` looks up that model's rate on the day of the call. The rate table holds dated periods, so a price change or a promotion's end is a new period with a `since` date, not an edit that rewrites history. It also holds long-context tiers, where the whole request moves to the higher rate, the way Gemini 2.5 Pro's public input price goes from $1.25 to $2.50 per million tokens above 200,000.

`recordAiCost` then writes one `ai_costs` row: surface, served model, a `refId` pointing at the generation or video job, dollars and every token count.

![A single model call moving through servedModel, the dated rate table and recordAiCost into one ai_costs row, which is then summed per generation, per editing thread, per video job and per provider wallet in the twice-daily report.](https://farhad-rezaei.com/images/blog/a-credit-sold-is-not-cost-incurred/ledger.svg)

## Where the counts were wrong

In July I added token counts beside every metered cost, "so a charged price can be re-derived and reconciled against a provider invoice," as the commit puts it.

In October I fixed two places where the meter read less than the provider bills. Grounded Gemini calls ignored `toolUsePromptTokenCount`, the case above. Transcription audio was priced at the text rate, although OpenAI bills `gpt-4o-mini-transcribe` audio input at a higher rate than text input. Both erred the same way: the ledger looked cheaper than the invoice.

![Recorded cost before and after the October fix, from the pricing tests' own fixtures: a grounded Gemini 2.5 Pro call rises from $0.00225 to $0.00725, and a short transcription from $0.001625 to $0.003375.](https://farhad-rezaei.com/images/blog/a-credit-sold-is-not-cost-incurred/undercount.svg)

## Rules that keep the next gap visible

An unknown model isn't free. If a model has no rate, `priceUsd` logs a warning and returns zero, but the row is still written with `priced: false`:

```ts
const priced = entry.priced ?? true;
const used = (entry.inputTokens ?? 0) + (entry.outputTokens ?? 0) + (entry.searchQueries ?? 0);
if (!(entry.costUsd > 0) && priced && used === 0) return;
```

Only a call that used nothing, cost nothing and was priced is skipped. A zero-dollar row with real tokens is a hole I can query, not spend that vanished.

Failed attempts count. In the blog pipeline, a JSON call that fails to parse and retries throws a `MeteredError` carrying every attempt's spend, because the provider billed all of them. A video job's `costUsd` is summed from the ledger by `refId` when it finishes, so failed stages count too; it first awaits `aiCostWritesSettled()`, since the writes are fire-and-forget.

Free allowances fail toward cost. Gemini 3 models get 5,000 free grounded searches a month, then $14 per thousand. A monthly Redis counter with a 500 ms timeout tracks them, and if Redis can't answer, every search is billed. That overstates cost for a while, which is the side I'd rather be wrong on.

## From rows to pricing numbers

Because every row carries a `refId`, one table answers several questions. `ledgerCostsByRef` sums one image's calls; `ledgerCostsByThread` adds every version in an editing thread, which is often what a user's "one ad" really costs.

The twice-daily finance report groups spend by the provider wallet that pays it and estimates the coffees still owed: `creditLiability` multiplies outstanding image credits by spend per delivered image, with blog spend carved out because no customer credit pays for an article. The report labels the result an estimate, and it is one: an average over changing models, retries and mixed outputs, not an accounting figure.

## How I verified it

The `pricingHistory` tests pin each rule, under names like "bills the search results Gemini feeds back to itself as input", "prices the model that answered, not the one asked for", "keeps an unpriced call instead of dropping it as free" and "bills every search when the counter cannot be read". `meteredSpend` covers failed attempts, `ledgerCost` the per-ref and per-thread sums, `costReport` the liability lines.

They prove the arithmetic and fallbacks against mocked Prisma and Redis. They don't prove every call site records its cost, and a failed ledger write is logged, not retried. The rate table is kept by hand against public price lists, so the invoice stays the authority.

## What carries over

- Store usage units next to the cost, so any price can be recomputed when a rate turns out wrong.
- Price the model that answered and the day it answered, not the model you asked for today.
- Record unknown prices as unknown, not as zero.
- Count failed and retried calls; the provider does.
- When a free allowance can't be checked, assume it's used up.

Someone buying a credit pack sees one price and expects it to hold. Behind it is a ledger where each model call leaves a row with its served model, units and dated price, and where uncertain cases land on the expensive side. The estimate still isn't exact, but the price is set against spend traceable call by call, and a wrong rate can be corrected from rows already stored.

## Further reading

- Gemini API pricing: https://ai.google.dev/gemini-api/docs/pricing
- Grounding with Google Search in the Gemini API: https://ai.google.dev/gemini-api/docs/google-search
- OpenAI API pricing: https://openai.com/api/pricing/
- Prisma aggregation, grouping and summarizing: https://www.prisma.io/docs/orm/prisma-client/queries/aggregation-grouping-summarizing
