OpenRouter Analytics API: Agent Cost Ledger
Build an OpenRouter cost ledger by linking application runs to generation IDs, querying analytics dimensions, and reconciling costs without double counting.
A monthly total can tell you that model spending increased. It cannot tell you whether one agent became less efficient, a new customer used more capacity, or a retry loop paid for the same task several times. To answer those questions, connect provider usage to the work your application attempted. OpenRouter’s Analytics API supplies an aggregate view; your application still needs a reliable relationship between its runs and the underlying generations.
This guide separates those two records and proposes a reconciliation workflow. It uses OpenRouter documentation checked on November 14, 2026. No customer account analytics were accessed, and no claimed savings or performance results are based on a live accounting experiment.
Key takeaway
- Analytics queries require a management key; keep it in a controlled server process.
- Discover supported metrics and dimensions before constructing queries.
- Maintain an application-owned mapping from runs to generation identifiers.
- Deduplicate provider rows and keep unknown cost separate from confirmed zero cost.
Use aggregates and request detail for different questions
OpenRouter’s Activity announcement describes dashboards and analytics for examining usage across agents, models, and requests. It also describes moving from a chart into filtered request logs. That is useful for identifying where a change occurred and then inspecting the contributing requests.
OpenRouter’s announcement captured November 14, 2026. The page documents the product workflow; it is not a screenshot of our spending or a customer’s account.
An application ledger answers another question: what did a completed business task cost? One task may call the model multiple times, perform non-model work, stop at approval, or be abandoned after a successful generation. Preserve those distinctions. The provider can report an inference charge without knowing whether your customer considered the overall task successful.
Choose a stable application run_id before the first model call. Record each attempt and attach the provider generation identifier when it becomes available. If the task fans out, retain the parent relationship. These are application conventions proposed here; do not assume a provider dashboard automatically reconstructs your internal task graph.
Start with the metadata endpoint
The analytics metadata reference documents GET /api/v1/analytics/meta for discovering metrics, dimensions, operators, and granularities. It requires a management key. The query reference documents POST /api/v1/analytics/query for the requested aggregates.
The following is a documentation-derived request, not an executed account query:
curl --fail-with-body --request GET \
'https://openrouter.ai/api/v1/analytics/meta' \
--header "Authorization: Bearer ${OPENROUTER_MANAGEMENT_KEY}"Run it from a trusted server environment with the authorized key supplied through your secret-management process. Do not place a management key in a browser dashboard or paste it into a saved report. A regular inference key is not equivalent: OpenRouter documents a 403 for using that key type with analytics operations.
The metadata endpoint reference captured November 14, 2026. It documents the authorization requirement and discovery operation; displayed examples are documentation, not observed account data.
Save a dated copy of the metadata your collector actually receives. Build the query against those supported names and preserve the query specification alongside the result. If a field is unavailable, fail visibly or mark the report incomplete. Silently dropping a grouping dimension can turn a per-agent report into an organization-wide total without changing its title.
Keep application attribution under application control
A run record should identify the business operation, agent implementation, environment, and completion state. A generation record should identify the provider request and the evidence retrieved about its usage. Keep the relationship explicit so the same generation cannot accidentally appear in several independent totals.
| Record | Suggested fields | Purpose |
|---|---|---|
| Application run | run_id, agent, environment, start, end, outcome | Define the work being evaluated |
| Attempt | attempt_id, run_id, requested model, generation ID | Preserve retries and routing attempts |
| Generation evidence | Generation ID, retrieved time, raw cost fields | Retain the provider accounting evidence |
| Allocation | Generation ID, cost center, allocation rule | Make intentional shared-cost attribution visible |
These names are a suggested schema, not required OpenRouter request parameters. If you use a provider-supported attribution field, verify its current contract and keep the application mapping anyway. A later change in dashboards should not make historical business runs impossible to interpret.
Shared work requires a deliberate rule. If one cached result serves several application runs, decide whether the cost belongs to its original producer, is allocated across consumers, or is reported as shared infrastructure. Do not duplicate the full provider charge into every consuming run and then present the sum as the account bill.
Retrieve generation detail without manufacturing certainty
OpenRouter’s generation metadata endpoint accepts a generation ID and documents request-level usage and cost fields. The documented example includes total_cost, usage, and upstream_inference_cost. Their presence does not mean that adding them produces the amount your application should report.
The generation metadata reference captured November 14, 2026. The response shown is an official example, not a measured charge from this article.
Choose one defined accounting basis and label it. Retain the other raw fields for investigation rather than combining them speculatively. Likewise, a token count is not itself a monetary charge, and an estimated cache saving is not an additional billed cost. Document unit, currency, and interpretation wherever your report converts or compares values.
Make ingestion idempotent. A collector that fetches the same generation twice should update or confirm one record, not insert a second charge. If a response is missing, preserve the state as pending or unresolved. Converting a missing cost to zero makes an incomplete report look cheaper and more precise than the available evidence allows.
Use decimal arithmetic or an explicitly chosen fixed monetary representation for reconciliation. Avoid binary floating-point accumulation as the source of truth for many small amounts. Keep the original response value so that rounding for display does not destroy the evidence used to calculate the total.
Reconcile like-for-like windows
A discrepancy between the application ledger and an analytics chart can come from scope rather than an incorrect charge. Compare the same workspace, time boundaries, model filters, grouping, and accounting basis. Record these parameters in the report itself. “Yesterday” is not a reproducible interval when two systems use different time zones.
Start with a small closed interval. List the generations mapped to application runs in that interval, identify unresolved rows, and compare the appropriate total with the matching analytics query. Do not compare a partial ingestion run with a complete provider chart and classify the difference as savings.
Use an explicit reconciliation status: complete, incomplete, or needs investigation. Keep the observed difference and the reason separately. A rounding difference, a missing mapping, and a changed filter are different problems with different owners. The status should become complete only when the declared scope is supported by the available records.
Avoid treating every dashboard discrepancy as a defect in the provider. First check the collection job’s success, deduplication key, time-zone conversion, and exclusion rules. It is easy to omit failed application runs even though they generated paid model requests. Those costs still belong somewhere in the report.
Retries are separate attempts, not duplicate rows
Two ingestion attempts for one generation should produce one ledger entry. Two model generations caused by a retry may represent two real charges. The application needs enough identity to distinguish those situations. Deduplicating solely by the user’s task ID would hide legitimate spending on repeated attempts.
Keep the attempt sequence with its reason: timeout, model rejection, application validation failure, or operator retry. This lets the team determine whether increased cost comes from higher task volume or additional work per task. It also provides a practical optimization target without claiming that a different model will automatically reduce the bill.
For cost per successful task, define the denominator. A task completed by the application is different from a generation returning HTTP 200. Include the costs of failed attempts in the numerator if the metric is intended to represent the cost of delivering successful work. State the treatment of abandoned and partially completed tasks rather than excluding them silently.
Cost evidence does not require retaining every prompt
The Activity announcement notes that prompt and completion details are available only when the relevant logging was enabled at request time; enabling it later does not recover historical content. A cost collector should not depend on prompt availability to perform basic attribution.
Keep operational identifiers and usage evidence separate from sensitive text. If an investigation needs a prompt, access it through the approved content-review path. Do not copy prompts into financial reports merely because the same generation detail view offers them. Different readers need different access to these records.
Also distinguish recorded usage from a visualization estimate. A chart or prompt breakdown can help explain behavior, but its displayed breakdown may have a different basis from the generation’s accounting values. The report should name the source of each value instead of using a generic “tokens” column for unlike measurements.
Test the collector before relying on the report
The following are proposed acceptance cases, not results of a test run performed for this article:
| Case | Expected ledger behavior |
|---|---|
| Same generation fetched twice | One charge record with updated retrieval evidence |
| Same task triggers two generations | Two attempts linked to one run |
| Generation metadata unavailable | Unresolved status, not fabricated zero cost |
| Unsupported analytics dimension | Query/report fails visibly |
| Run crosses a reporting boundary | Documented time-allocation rule applies |
| Application fails after model success | Provider charge remains in the ledger |
| Shared result has several consumers | Declared allocation rule prevents duplicate billing totals |
Add bounded retry behavior and a visible collection watermark indicating the interval actually processed. Operators should be able to tell the difference between “no spending” and “collector has stopped.” An empty dashboard without ingestion status cannot make that distinction.
Where another model catalog fits
The SandBase task directory can help explore model and API options after the ledger identifies a workload to evaluate. It does not replace OpenRouter’s Analytics API, and this article does not claim the two services share account data or a billing record.
For a broader view of the costs surrounding model calls, see API cost per call and agent pricing. Evaluate an alternative against completed tasks, including retries and other services, rather than comparing a single attractive per-token number with a complete workflow cost.
A ledger becomes useful when another engineer can reproduce its scope and explain an individual row. Preserve the run mapping, raw evidence, accounting basis, and unresolved states. The aggregate chart then becomes a way to navigate trustworthy records instead of a total that nobody can reconcile.
Found this useful? Share it