The direct answer
If you cannot answer three questions from the same billing period, you are not yet operating the AI product:
- Which customer or workspace generated the spend?
- Which feature, model, or agent loop caused it?
- Was the spend caused by normal usage, retries, or excessive iteration?
Do not wait for a provider invoice to answer these questions. Generate a cost event when the model call finishes, attach it to the customer request that triggered it, and calculate cost from the usage actually returned by the provider. Keep retries and individual agent steps as separate events linked to the original operation.
This creates a simple commercial feedback loop: you can see which customers are expensive, whether a feature has viable unit economics, and which model or orchestration behavior is consuming the margin you expected.
Why request counts are not enough
Two AI requests can use very different amounts of inference. One may contain a short prompt and return a brief classification. Another may include a large document, generate a long answer, and run through several planning, tool, and validation steps.
A request-count dashboard can therefore look healthy while a single workflow destroys your gross margin. The bill tells you that money was spent. Cost attribution tells you where the decision belongs: pricing, context limits, model selection, retry policy, caching, or agent termination.
For a founder, the useful unit is not simply “an API call.” It is the billable operation and the chain of work that created it:
- A customer request may invoke several model calls.
- Each model call may be retried or fail.
- A model call may belong to an agent step, tool step, or fallback path.
- One logical agent run may cost more than the final answer suggests.
Track that hierarchy rather than flattening everything into a monthly total.
Start with a cost ledger, not another dashboard
A useful implementation is an append-only ledger of model-call events. Each event should describe the work, the usage, and the context needed to attribute the cost.
Use a stable internal identifier for each event. A practical JSON shape looks like this:
{
"event_id": "evt_01J...",
"occurred_at": "2026-07-10T14:32:18Z",
"customer_id": "cus_123",
"workspace_id": "ws_456",
"request_id": "req_789",
"feature": "document_review",
"operation": "chat",
"provider": "example_provider",
"requested_model": "example-model",
"served_model": "example-model",
"agent_run_id": "run_abc",
"agent_step": 3,
"attempt": 1,
"retry_of_event_id": null,
"status": "success",
"input_tokens": 8200,
"output_tokens": 950,
"cached_input_tokens": 0,
"cost_usd": 0.041,
"pricing_version": "pricing_2026_07_10",
"trace_id": "4bf92f..."
}
The fields deserve explicit decisions.
Identity and commercial context
customer_id and workspace_id answer who consumed the work. request_id connects all calls made for one external request. feature provides a stable product label such as document_review or support_reply, rather than a mutable UI name.
Do not make the feature field the sole basis for attribution. A shared background worker may serve several features, and manual labels can drift. Ideally, the application passes a billing context through its own request and job boundaries.
Model identity
Store both the requested model and the served model. A provider may route, alias, or return a different model identifier. requested_model tells you what your product asked for; served_model tells you what the provider reported. That distinction can explain a cost change without requiring you to speculate.
Retry and attempt context
Give every provider attempt its own event. Keep attempt, retry_of_event_id, and failure status on that event.
There is an accounting choice here: a retry creates another charge, so it must not disappear from the raw ledger. The dashboard can then show both:
- gross provider spend, including every charge;
- productive spend, excluding attempts that failed or were explicitly discarded.
That distinction is more useful than hiding retries under an “effective token” total. It preserves evidence of waste while allowing product and finance views to answer different questions.
Agent-loop context
Record the logical agent_run_id and the agent_step on each model call. Tool calls can use separate events or spans, but they should share the run and request identifiers.
Do not guess an agent’s step after the fact from timestamps. Increment it in the orchestration code where the step actually begins. If a workflow can branch, also record a branch or plan identifier when that distinction affects cost.
Usage and calculated cost
Store input and output token counts from the provider response. If the provider reports cached or reasoning-token categories, store them in separate fields rather than folding everything into an undifferentiated token count.
Calculate cost from the provider’s applicable input, output, and cached-token rates. Keep a pricing_version so historical events remain reproducible when prices change.
Do not use one blended “cost per token” number if the provider charges different categories differently. It hides exactly the cost behavior you are trying to control.
If the provider does not return a usage count, mark the event as estimated and preserve the estimation method separately. Never silently mix measured and estimated costs in a total labeled as actual spend.
Use OpenTelemetry names for model telemetry
Use the gen_ai.* namespace for model telemetry. Relevant attributes include:
gen_ai.operation.namegen_ai.request.modelgen_ai.response.modelgen_ai.usage.input_tokensgen_ai.usage.output_tokens
The older gen_ai.usage.prompt_tokens and gen_ai.usage.completion_tokens attributes are deprecated in favor of gen_ai.usage.input_tokens and gen_ai.usage.output_tokens.
There is no official llm.* namespace in the current conventions described by the research. A framework-specific llm.* field may exist as a custom attribute, but do not build a cross-service cost dashboard around it as though it were standardized.
One caution: the GenAI conventions are still marked Development, and their repository and attribute set can evolve. Pin the semantic-conventions version used by your instrumentation and test migrations when you upgrade. OpenTelemetry gives you a shared vocabulary and transport model; it does not calculate prices, assign customers, or guarantee that every provider field was captured.
Use standard attributes for interoperability, then add your own commercial fields in a clearly defined namespace, such as app.billing.* or cost.*. Keep those custom fields stable even while upstream conventions change.
Connect the ledger to the provider bill
The internal ledger is useful only if it reconciles with what you are charged. Establish a weekly or monthly control process:
- Aggregate billable events by provider, model, usage category, and day.
- Compare that total with the provider invoice or usage report.
- Investigate missing events, duplicate events, and mismatched model or price versions.
- Adjust the pricing configuration, but do not rewrite historical usage records.
The aim is not to create artificial precision. Some provider charges may include features that do not map cleanly to one model call. Treat unmapped charges as a separate reconciliation category instead of forcing them onto an arbitrary customer.
Also account for costs outside the model API, such as vector storage, retrieval infrastructure, tool execution, or observability ingestion. Attribute those separately. A dashboard labeled “AI COGS” should state whether it includes only model inference or the full delivery cost.
Build four dashboard views
A single “spend by day” chart will not expose the leaks. Start with four views.
1. Customer and feature economics
Show total cost, successful logical runs, average cost per run, and cost per successful customer outcome for each customer or segment.
The last measure matters. If a feature generates hundreds of model calls but rarely completes, its low apparent request price may hide poor delivery economics.
For pricing decisions, calculate the customer’s total cost, including retries and failed runs. Also show usage concentration: a small number of heavy customers can make a broadly unprofitable product appear viable.
2. Model and operation mix
Group cost by provider, served model, operation, and feature. Add input, output, and cached-token volume as separate series.
This view answers practical questions:
- Did spend rise because traffic grew or because the model mix changed?
- Are long-context features consuming disproportionate cost?
- Is a fallback model absorbing failures at a higher unit price?
- Did a provider-side model alias change the effective cost?
3. Failure, retry, and fallback leakage
Show gross spend by attempt number and failure category. Include the proportion of requests that eventually succeeded.
Do not set a universal retry target. A low retry rate may indicate resilience; it may also indicate that requests are failing before reaching the model and being handled elsewhere. Define categories that map to operational action: timeout, rate limit, provider error, invalid response, policy rejection, or user cancellation.
4. Agent-run efficiency
Show model calls per logical run, tool calls per run, total cost per run, and the distribution of agent steps. Include outcomes so expensive successful runs are not confused with expensive broken loops.
A useful alert is not “cost exceeded a number.” It is “cost per successful run changed materially for a specific feature and model mix.” Otherwise, normal traffic growth creates noisy alerts while a small, expensive runaway loop remains hidden.
A practical implementation sequence
Step 1: Instrument the billable boundary
Place event creation immediately after each provider response or terminal failure. This is the point where you know the actual model, usage, and status. Do not estimate from the prompt before the call if the provider returns usage.
Emit one event per provider attempt. Add a unique event_id and make ingestion idempotent so retries of your telemetry pipeline cannot create duplicate charges.
Step 2: Propagate billing context
Create a request context containing customer, workspace, feature, request, trace, and agent identifiers. Pass it through queues, workers, and tool calls. Background jobs need a durable way to retain this context.
If a job is intentionally unattributable, use an explicit value such as internal or unallocated. Missing context should be visible in a data-quality view, not silently treated as zero cost.
Step 3: Version prices and calculate cost
Store provider, model, category, effective date, unit rate, and pricing version in a price table. Calculate cost at ingestion time and preserve both inputs and result.
This gives you a reproducible calculation and lets you explain a historical charge after rates change.
Step 4: Reconcile before building elaborate forecasts
Start with monthly reconciliation. Once event totals are close to provider totals, move to weekly reconciliation and daily alerts. A forecast built on incomplete attribution is only a polished estimate of the wrong number.
Step 5: Turn findings into operating decisions
Only then choose interventions:
- Reduce context assembled before model calls.
- Use a smaller model for a bounded step.
- Cap agent iterations and tool-loop budgets.
- Add a safe cache path for repeated stable context.
- Change fallback behavior.
- Adjust pricing or customer limits.
Measure each change by cost per successful outcome, not by token reduction alone. A cheaper model that causes more retries or downstream support work may not improve the product.
The founder’s decision checklist
Before approving an AI feature or changing its pricing, ask:
- Can we identify the customer behind every model-call event?
- Can we separate requested and served models?
- Can we identify retries and fallback calls?
- Can we group model calls by agent run and step?
- Do actual and estimated costs remain distinguishable?
- Can we reconcile our event totals with provider charges?
- Do we measure cost per successful outcome?
- Can we set a model, token, tool-call, or step budget without stopping the whole product?
- Are prompt and response contents excluded from routine cost telemetry unless retention is explicitly required?
The final question matters because cost telemetry can contain sensitive customer data. Capture metadata, tokens, and identifiers by default; treat prompts and outputs as separately governed data. If you retain content for debugging, define its access and deletion rules separately from your cost ledger. A practical policy foundation is covered in A Practical AI Data Retention Policy Framework for Indie Developers.
If your main concern is asynchronous inference work rather than attribution, the Practical Cost-Control Framework for Asynchronous AI Workloads covers queueing, concurrency, and spend controls for background jobs.
Frequently asked questions
Should retries count as customer usage?
Record retries in the raw ledger because they can create provider charges. In customer economics, show whether the customer ultimately received a successful result and include the retry cost in the delivery cost. If you offer usage-based billing, define whether the customer is charged for the successful operation or the provider attempts, and make that policy explicit.
Should I store prompts to understand why costs changed?
Usually, start with metadata and token categories. Content can help explain a specific anomaly, but retaining every prompt creates privacy, storage, and access-control obligations. Add content capture selectively for defined debugging windows or sampled investigations.
Is OpenTelemetry enough to build this dashboard?\n
No. OpenTelemetry supplies consistent telemetry names and transport. You still need business identifiers, a price table, a cost ledger, reconciliation, and dashboard logic. It is a useful foundation, not a complete accounting system.
How should I attribute a call made by a background worker?
Carry the original request, customer, workspace, feature, and trace identifiers into the job envelope. If the job serves many customers, define the allocation rule explicitly, such as charging only calls caused by that customer’s submitted work.
The bottom line
Treat AI API spend as an operational ledger tied to customer value, not as a provider bill detached from your product.
The minimum useful system is modest: one event per provider attempt, stable request and agent identifiers, versioned prices, and dashboards that distinguish customers, features, models, retries, and agent runs. Start there. Once the numbers reconcile, you can make defensible decisions about pricing, model selection, context budgets, and agent limits—and catch expensive behavior long before it becomes an alarming invoice.







