Spend API

Exact, frozen spend reports with a provisioning key, the same numbers the dashboard shows.

Access

The Spend API is the reporting store behind the dashboard's Usage page, under https://api.experientiallabs.ai/api/orgs/{org_id}/spend. Reports are free and make no model call.

Rule
KeyA provisioning xpl_ key (Authentication). An inference key gets 403
OrganizationFrom GET /api/whoami; another org's id is 404
ScopeKeys use scope: "org"; self needs a signed-in member
MoneyInteger nano-USD as decimal strings (1,000,000,000 = $1)

For per-request cost and billing sync use Usage and spend instead: those reads take an ordinary key.

curl https://api.experientiallabs.ai/api/orgs/ORG_ID/spend/analytics \
  -H "Authorization: Bearer <YOUR_API_KEY>" -H "Content-Type: application/json" \
  -d '{"refresh": false, "query": {
        "start": "2026-11-01T00:00:00Z", "end": "2026-11-08T00:00:00Z",
        "time_zone": "UTC", "scope": "org", "basis": "requests",
        "group_by": "model", "grain": "day", "filters": [], "tags": []}}'
# {"id": "...", "status": "loading", "report": null, ...}

Load once, then poll

  1. POST /analytics with an unpinned query and refresh: false. Add comparison: "previous_elapsed" only if you need the prior period.
  2. On loading, keep id and poll GET /analytics/{id}. Never POST again: a timeout is an unknown outcome, not permission to repost.
  3. On ready, use report.query for every later read. The id stays readable for 30 minutes.
  4. On failed, read error_code (for example analytics_deadline). Starting again is a deliberate new load.

The server deadline is 60 seconds from issue; polling does not extend it. refresh: false reuses a completed result of the same query from the last 30 minutes; refresh: true forces a new snapshot.

POST/api/orgs/{org_id}/spend/analyticsGET/api/orgs/{org_id}/spend/analytics/{analysis_id}POST/api/orgs/{org_id}/spend/latest
statusDo
loadingSave id, poll the GET
readyRead report; reuse report.query
failedRead error_code; no report is present

POST /latest returns the newest completed report for a query, or null, without starting work.

One snapshot for every view

A ready report carries query.as_of (the read fence) and query.snapshot_id. Send both back unchanged on every later read (table pages, other groupings, charts, facets, activity, CSV) so every panel shows the same numbers. coverage.projected_through is the data cutoff: it trails settled usage and can be earlier than as_of.

NeedCall
Next table pagePOST /query with the frozen query and offset: next_offset (stop at null)
Another grouping, same snapshotPOST /view
Freeze a query without loading itPOST /snapshot

Snapshots and prepared builds expire after 24 hours (409 snapshot_expired); refresh replaces every panel together, never mixed. A build belongs to one grouping: do not reuse a model-grouped build as a key-grouped report.

POST/api/orgs/{org_id}/spend/queryPOST/api/orgs/{org_id}/spend/viewPOST/api/orgs/{org_id}/spend/snapshot
{
  "as_of": "2026-11-08T00:00:00Z",
  "projected_through": "2026-11-07T23:58:41Z",
  "complete": true,
  "pending_requests": 0,
  "includes_pre_admission_rejections": false
}

The query

FieldValues
start, endTimezone-aware ISO; start inclusive, end exclusive; at most 3,660 days
time_zoneIANA zone for day and month buckets (default UTC)
basisrequests (default) or attempts (each provider dispatch, retries included)
grainhour (UTC, range at most 7 days), day (default), month
group_bymodel (default), key, member, end_user, provider, funding, surface, outcome, error, app, prompt, tag (with tag_key), source
filtersUp to 12 dimensions, each {dimension, values, missing, exclude?}, up to 50 values
tagsUp to 16 keys, each {key, values, missing, exclude?}, exact case-sensitive values
sort, directionspend (default), requests, tokens, errors, cache_rate, name; desc or asc
offset, limit0 to 100,000; 1 to 200 (default 50)

Values in one predicate are OR; separate predicates are AND. missing: true adds the unattributed bucket; exclude: true negates the predicate. app is the calling agent classified from request headers (claude_code, codex, ...). Totals cover the whole slice, not the page.

Limit
Groups per report100,000
Chart368 buckets; 7 leaders by spend plus exact Other
CSV10,000 groups, 16 MiB, nine decimals in dollar columns
Snapshot and build lifetime24 hours

Nothing is sampled or silently shortened: an oversized slice is refused (422).

The eleven figures

Totals, each group, each bucket and each series cell carry the same figures.

FieldMeaning
countSettled requests (or attempts on basis: attempts); not a success count
rejected_countFailed or expired requests with no provider attempt; always 0 on attempts
errorsEvery outcome except completed, rejections included; do not add rejected_count
input_tokens, output_tokensCached input is inside input; reasoning is inside output
cached_input_tokens, reasoning_tokensSubsets, not extra tokens
paid_nano_usdCharged credits
byok_nano_usdYour own key's usage at list rates; an estimate, never charged
free_nano_usdFree promotional usage at list value; not a debit
unknown_usage_countUsage a provider never reported; nonzero makes the money provisional

All-in spend is paid + byok + free. Requests and attempts are alternative counts, never added together. Requests refused before admission are outside Spend; failures after admission count.

totals = report["totals"]
all_in = sum(int(totals[k]) for k in
             ("paid_nano_usd", "byok_nano_usd", "free_nano_usd"))
print(all_in / 1_000_000_000, "USD")

Sum the strings as integers (Python int, JavaScript BigInt), never floats.

Other reads

All take the frozen query. /series and /model-series return chart data; /facets searches filter values (kind: dimension, tag_keys, tag_values); /activity lists content-free rows behind a slice with a {time, id} cursor. /export returns the grouped CSV: one row per group, not per request. /builds prepares a large report in the background, free.

POST/api/orgs/{org_id}/spend/seriesPOST/api/orgs/{org_id}/spend/model-seriesPOST/api/orgs/{org_id}/spend/facetsPOST/api/orgs/{org_id}/spend/activityPOST/api/orgs/{org_id}/spend/exportPOST/api/orgs/{org_id}/spend/buildsGET/api/orgs/{org_id}/spend/builds/{build_id}GET/api/orgs/{org_id}/spend/builds/{build_id}/reportGET/api/orgs/{org_id}/spend/builds/{build_id}/seriesGET/api/orgs/{org_id}/spend/builds/{build_id}/export
Build statusMeaning
runningWaiting for history in its range; poll its id
completedRead /report, /series, /export
failed, expiredStart a new build

Request-basis activity rows carry detail.usage_evidence.cache_write_input_tokens: tokens written to a new provider cache, separate from cached_input_tokens (read from cache).

Previous-period comparison

Send comparison: "previous_elapsed" on the POST and on its polls. The primary report is usable while comparison.status is pending. The prior period is the same length as the observed interval (start to the earlier of end and the data cutoff), ending at start. Without a ready comparison there are no totals: never show zero or a percentage.

DELETE/api/orgs/{org_id}/spend/analytics/{analysis_id}/comparison
Unavailable reason
not_prepared, coverageNot enough history yet
capacity, deadlineBusy or timed out
cancelled, invalidated, errorStopped or failed

The DELETE cancels the comparison only (204); the primary report stays.

Quick summaries per key and identity

usage/by-key and usage/by-identity are live, bounded summaries (window=24h|7d|30d, default 7d) for a provisioning key. They are not a frozen report: no snapshot, no coverage, and unknown usage is not reported. Past 10,000 key and model cells they answer 422 usage_summary_too_large; use /analytics then.

GET/api/orgs/{org_id}/usage/by-keyGET/api/orgs/{org_id}/usage/by-identity
{
  "report_kind": "live_usage_summary",
  "window": "7d",
  "keys": [{"api_key_id": "...", "key_label": "support-bot",
            "models": [...], "totals": {"request_count": 812,
            "paid_nano_usd": "1840000000", "spend_nano_usd": "1840000000"},
            "last_used_at": "2026-11-07T22:10:04Z"}]
}

Errors

Business errors are {error, code?}; schema errors use a detail array. A 200 analytics response can still be status: "failed". Never read an error as zero usage.

StatusMeaning
400 / 422Bad query, range or timezone (invalid_spend_query)
403Inference key; use a provisioning key
404Other org, or unknown analytics_not_found / build_not_found
409snapshot_expired, snapshot_invalidated, build_not_ready
410build_expired: refresh
422report_too_large, series_too_large, export_too_large, usage_summary_too_large: narrow the slice
429analytics_capacity, build_capacity: keep the last result, retry later by choice
503reporting_initializing, report_timeout: not empty data; resume by id

Never put secrets, prompt text, emails or personal data in tags or end-user labels: they are metadata shown in reports. A privacy erasure removes attribution but keeps anonymous amounts.

In the app

The Usage page reads the same store. It needs Pro for 30 days and every view; admins see the workspace, members their own usage.

TermMeans
RequestsSettled customer calls, not successes
Provider attemptsEvery dispatch, retries and fallbacks; never add to requests
Non-completedFailed, cancelled, incomplete, expired, or unknown after interruption
RejectedThe non-completed calls that never reached a provider
System promptGroups by a SHA-256 of system and developer messages plus tool declarations, shown as 12 characters; not a session id
CSVOne row per group, up to 10,000 groups, for the whole filtered snapshot

A failed call can carry a charge and a completed one can charge zero. A result older than 15 minutes is marked as an older snapshot; Refresh keeps it visible while a new one loads. View activity opens the request log with the same dates and filters.

Spend figureHover shows
All-inPaid, bring your own key, free
Cache read %Cached input divided by input tokens
Period changeAgainst the equally long period just before