Skip to content
Blog
November 9, 2026Architecture9 min read

How to bill a customer for agent usage you can defend: provider cost APIs vs gateway tags vs your own cost rows

A provider's cost API groups dollars by workspace and key, never by your customer. A gateway groups by the customer id your code remembered to send. Only rows you wrote at call time can answer a dispute six months later. Compared on granularity, who assigns the number, and what survives the invoice closing.

byPleach maintainers

Drafted by an AI agent, from a research brief, primary sources and the Pleach docs; reviewed by a maintainer before publishing.

No @pleach/* package is on npm yet. Each name holds a 0.0.1 placeholder until its first release, so the code here describes the source, not an install that works today. Package status

A per-customer number you can defend has to come from rows you wrote at the time of the call, not from a provider's bill or a gateway's dashboard. A provider's cost API groups dollars by your own org structure — workspace, key, model — and never by your customer. A gateway can group by a customer id, but only the one your code remembered to send. Both produce summaries; neither produces evidence.

This post is about the hand-off: getting from a per-call cost to an invoice line, and still being able to explain that line six months later. For how to roll a subagent tree up into a single request total, see tracking LLM cost per user request with subagents — this picks up where that ends, at the billing boundary.

The three sources side by side

Provider cost APIGateway tagRows in your own database
Who assigns the customernobody — it doesn't know themyour code, per requestyour code, per call attempt
Finest dollar groupingworkspace, dailythe tag valuewhatever the row carries
Where the price comes fromthe provider's actual chargethe gateway's pricing tableyour own calculation
Survives the retention windowyes, it's your invoicedepends on planyes, it's your table
Answers "which action caused this?"nopartiallyyes, if the row carries the action
Reconciles against the real billit is the real billapproximatelyapproximately

These aren't alternatives so much as layers. Most teams need the provider's number as the control total, and a per-call record for everything else. The mistake is assuming the first can be decomposed into the second.

What can a provider's cost API actually tell you?

Anthropic's Usage and Cost API splits the question across two endpoints, and they do not have the same resolution.

The usage endpoint reports token consumption and can filter and group by API key, workspace, model, service tier, context window, data residency and speed, in buckets of one minute, one hour or one day. The cost endpoint reports dollars, groups by workspace or description only, and offers daily granularity alone.

That asymmetry is the whole story. Every one of those dimensions describes your organization: your keys, your workspaces, your models. None describes your customers, because the provider has no concept of them. It bills you for calls your key made.

It also means the common workaround — give every customer their own API key — gets you per-customer tokens and not per-customer dollars. You can group usage by key; you cannot group cost by key. You would price those tokens yourself, which puts you back to doing the arithmetic locally, now with a key-management problem on top.

A few other edges worth knowing before you treat the provider's figure as ground truth. Priority Tier costs use a different billing model and are excluded from the cost endpoint entirely. Console playground usage is not associated with an API key, so grouping by key leaves it under a null. Data typically appears within five minutes, so same-hour reconciliation is unreliable by design.

OpenAI's shape is the same in the respect that matters: its completions usage can be grouped on finer fields than its cost report, which groups by line item or project. The earlier post on subagent cost covers both providers' groupings in more detail.

What does a gateway tag give you, and what does it trust?

A gateway sits in the call path, so it can attribute what the provider can't — as long as you tell it who the call is for.

LiteLLM reads a customer identifier from the request body's user field or from either of two headers it recognizes with no configuration, x-litellm-customer-id and x-litellm-end-user-id. Spend accumulates per customer id, budgets and rate limits can be set per customer, and the Admin UI filters spend and activity by customer.

Helicone takes the generic route: custom properties sent as Helicone-Property-<Name> headers, with no limit on how many you attach. Its Properties view then shows total cost, request count and average latency per property value, so a property whose value is your customer id gives you per-customer cost as a segment.

Both work, and both inherit the same two properties.

The tag is only as good as the code path. It is attached per request by your application. A background job, a retry wrapper, an admin tool or a newly added provider call that forgets the header produces spend attributed to nothing, and nothing raises an error. LiteLLM's docs note the reverse hazard too: a customer id it hasn't seen is upserted automatically, so any value a client can influence becomes a tracked customer.

The price is the gateway's, not the provider's. A gateway computes cost from its own model pricing table. That is fine for dashboards and budget alerts, and it will drift from your actual invoice across cache hits, batch discounts, tier changes and new model pricing. Reconcile against the provider's number rather than treating the gateway's as authoritative.

Why does the number change after the invoice closes?

This is the part that surprises people, and it belongs to the metering layer rather than the LLM layer.

With Stripe's billing meters, you record usage by creating a meter event against /v1/billing/meter_events with an event name, a numeric payload[value] and a payload[stripe_customer_id]. Four constraints shape what can be billed:

  • Timestamps have a window. The event timestamp must fall within the past 35 calendar days and no more than five minutes in the future, the latter to absorb clock drift.
  • Acceptance is not billing. Stripe is explicit that the 35-day window governs only whether the event is accepted. It may accept an event after an invoice finalizes, include it in meter summaries, and neither amend the finalized invoice nor carry the usage into the next one. Usage can therefore be accepted and never charged — and the summary will still show it.
  • Dimensions are capped. A meter accepts up to 10,000 unique dimension combinations per hour, and only 100 unique combinations per customer across all events. Events introducing a new combination past the cap are invalid, reported through an error event with a dimension-count error code.
  • Processing is asynchronous. Aggregated usage in summaries and on upcoming invoices may lag the events you've sent.

Use idempotency deliberately here: each meter event has an identifier you can set, and Stripe auto-generates one if you don't — so a retried send without an explicit identifier is a double count. Stripe now points new integrations at Metronome rather than building on Billing Meters directly, which changes the ingest path but not the underlying lesson.

The lesson is that your cost rows and your invoice are two different records with different cutoffs. If the rows are the only place the cause is written down, and the invoice is the only place the charge is written down, then any question spanning the two needs both to still exist.

What does a disputed invoice actually require?

A customer who questions an AI usage charge rarely argues with the total. They ask what produced it: which actions, on which days, on which models, and why one request cost what a dozen used to.

That question has a shape most observability data can't satisfy:

  • Per-call, not per-period. An hourly or daily aggregate can't show that one action fanned out into forty calls.
  • Cause, not just quantity. Tokens alone don't say which tool call or which delegation spent them.
  • Retries distinguished from work. A retried call that the provider charged twice is legitimate cost; a retry your own wrapper caused is a different conversation.
  • Still there later. Disputes arrive after the bill, which is often after a hosted tool's retention window.
  • Unchanged since it was written. A total recomputed on demand is only as good as the table it reads. If rows in that table can be edited or backfilled without trace, the recomputation is an assertion, not a demonstration.

The last point is where an audit log and a cost ledger stop being separate concerns. If the rows carrying the cost are also the rows carrying the provenance, and the sequence is tamper-evident, then the answer to "why is this number what it is" is a query rather than a reconstruction. See hash chain vs append-only table vs OTel traces for what tamper-evidence does and doesn't buy.

When to use each

Use the provider's cost API as the control total and for finance reconciliation. It is the only source that reports what you were actually charged. Don't try to decompose it per customer.

Use a gateway tag when you want per-customer reporting and budget enforcement quickly, and the number's job is to inform rather than to invoice. It's the fastest path to a dashboard and the cheapest to adopt, since it needs a header rather than a schema.

Use rows in your own database when the number ends up on an invoice, when a customer can dispute it, or when a regulator or auditor may ask how it was derived. It is the only option that keeps cause and cost in the same record on your retention terms.

Use a meter for the billing hand-off, with the timestamp window and the finalization behavior designed for rather than discovered.

Most production systems run three of the four. The useful question isn't which to pick but which one you'd point at if a customer asked you to justify a line.

How Pleach does it

Pleach puts the cost on the audit row instead of in a parallel metering pipeline, so attribution is a property of the record rather than a second system to keep in sync.

The runtime's packages aren't installable yet — each @pleach/* name holds a placeholder until its first release, so what follows describes the source rather than a release you can add today. See packages for status.

One row per call attempt

Every model call made through a built-in provider writes its own row through a decision ledger, retries and subagents included. The provider SDK's own retries are disabled so none hide inside it. A provider that doesn't declare per-attempt auditing keeps one row per call instead.

The row carries tenantId, turnId, toolName, subagentDepth, parentTurnId, model, provider and tokenCost. The cost sits beside the cause, in the same row, written at the time of the call.

The tenant is the rollup axis

tenantId is deliberately opaque. In a multi-tenant product it's your end customer; in an internal deployment it's typically the team or cost center you report against. Because it's stamped by the runtime rather than attached per request by call sites, a path that forgets to tag doesn't silently drop its spend into nothing.

Per-customer spend is then a grouped query over rows already in your database, joinable to the customer and subscription tables sitting next to them:

select customer, sum(cost_usd) as spend, count(*) as calls
from agent_calls
where called_at >= date_trunc('month', now())
group by customer;

What to check before relying on it

Two caveats matter more than the shape. The default emitter is a no-op, so rows land only once the host registers one and an adapter for the store you want — Postgres, Supabase, IndexedDB, S3 or your own. And the figure on the row is a computed token cost, so it still wants reconciling against the provider's invoice like any other local calculation.

See the audit ledger for the write path and the row's full contents, and storage for the adapters.

Key takeaways

  • No provider cost API can attribute spend to your customer. Anthropic's groups dollars by workspace or description, daily. Every available dimension describes your organization, not your customer base.
  • Token counts slice finer than dollars. Usage endpoints carry many dimensions; cost endpoints mirror how you're billed. A key per customer buys per-customer tokens and leaves the pricing to you.
  • A gateway tag is a reporting tool, not a record. It depends on the code path remembering a header, and the cost is the gateway's own estimate from its pricing table.
  • Accepted usage is not billed usage. A Stripe meter event accepts a timestamp up to 35 days old, but may be accepted after an invoice finalizes and never appear on any invoice at all.
  • Defensibility lives in per-call rows you control. A dispute asks for cause, not totals, and asks after the bill — so the record has to carry the action beside the cost, and still be there, unchanged, later.

References

  1. Usage and Cost API — Anthropic, platform documentation. Grouping dimensions for the usage and cost endpoints, bucket granularity, Priority Tier and playground caveats, data freshness. Accessed 2026-11-09.
  2. Customer Usage — LiteLLM, proxy documentation. The x-litellm-customer-id and x-litellm-end-user-id headers, per-customer budgets and rate limits, automatic upsert of unseen customer ids. Accessed 2026-11-09.
  3. Segmentation with custom properties — Helicone, documentation. The Helicone-Property-<Name> header format and per-property cost metrics. Accessed 2026-11-09.
  4. Record usage for billing — Stripe, billing documentation. Asynchronous meter event processing and the recommendation to use Metronome for new integrations. Accessed 2026-11-09.
  5. Record usage for billing with the API — Stripe, billing documentation. Meter event payload fields, the 35-day timestamp window, post-finalization acceptance behavior, dimension cardinality limits and idempotency identifiers. Accessed 2026-11-09.

Frequently asked

Can a provider's cost API tell me what one of my customers cost me?

No. Anthropic's cost endpoint groups by workspace or description, in daily buckets only. Its usage endpoint slices finer — API key, workspace, model, service tier, context window, data residency, speed — but those are dimensions of your own organization, not of your customer base. The provider bills you; it has no idea which of your customers caused which call. To attribute per customer you have to stamp the customer on the call before it leaves your code.

Why do token counts slice finer than dollar amounts?

Because the two endpoints are built for different jobs. Usage reporting exists for capacity and optimization work, so it carries many dimensions. Cost reporting exists for invoice reconciliation, so it mirrors how you are billed — by workspace, daily. The practical effect is that giving every customer their own API key gets you per-customer tokens but not per-customer dollars, so you price the tokens yourself and the provider's bill is only a control total.

Is a gateway tag enough to bill a customer?

It is enough to report, and usually not enough to defend. LiteLLM tracks spend per customer id sent as a header, and Helicone aggregates cost per custom property value. Both depend on the tag your code attached, and the cost figure is the gateway's own calculation from its pricing table rather than the provider's charge. If a call path forgets the tag, that spend lands nowhere and no error is raised.

How late can usage arrive and still be billed?

With Stripe meters, a meter event's timestamp must be within the past 35 calendar days and no more than 5 minutes in the future. The 35-day window only governs acceptance. Stripe says it may accept an event after an invoice finalizes, include it in meter summaries, and neither update the finalized invoice nor roll the usage into the next one — so a late row can be accepted and still never billed.

What does a customer actually ask for when they dispute an AI usage bill?

Line-level cause. Not the total, but which actions produced it: what ran, when, on which model, how many calls one request turned into, and whether a retry was charged twice. A dashboard aggregate cannot answer that after the retention window closes, and a recomputed total is only as trustworthy as the table it was recomputed from.

How does Pleach handle per-customer cost?

Each model call attempt writes one row to a database you own, carrying the tenant it belongs to, the turn it belongs to, the tool name, the delegation depth, the parent turn, the model, the provider and the token cost. The tenant is the opaque rollup axis, so per-customer spend is a grouped query over rows that already exist rather than a separate metering pipeline. Rows land only once the host registers an emitter; the default one does nothing.

cost attributionllm cost trackingusage-based billingllm usage apitoken usageaudit trail

Related posts