Stats API
The Stats API exposes aggregated request metrics. Use GET /stats for the dashboard summary view (today, yesterday, last 7 days, last hour, last minute) and GET /stats/timeseries for time-bucketed data suitable for charts. GET /stats/growth reports the self-serve funnel (signups, activation, paid) across all tenants.
Base URL: https://<your-gateway-host>/admin/v1
GET /stats
Returns a snapshot of request counts, token usage, cost, and latency across several time windows. Also includes a per-tenant breakdown and the most recent log entries.
Every caller below admin/tenant_admin (member, viewer, ki_manager, demouser) is scoped to their own data. Non-admin callers are pinned to their own tenant server-side (a spoofed tenant_id is ignored); a caller with no tenant is refused 403 { "error": "forbidden" } (the query never runs). A platform admin may target one tenant with ?tenant_id= or omit it (and an empty value) for the global, all-tenant view. The global view's window totals exclude synthetic fixture tenants and the traffic of deleted tenants — the same scope as Cost analytics (GET /stats/analytics) and the per-tenant rows, so the totals reconcile; a tenant-scoped view keeps a deleted tenant's own rows.
The calendar-day windows (today, yesterday) are computed in the viewer's timezone, supplied by the tz_offset query parameter — so "today" means the viewer's local calendar day, not a UTC day. The rolling windows (last_7d, hour, last_min) are relative to the current instant and are timezone-independent: last_7d is exactly the last 7 × 24 hours — the same window as the Last 7 days period of GET /stats/analytics in Cost analytics (which takes its since from the browser clock, so the two agree up to the device's clock skew). Every window that is still open ends at the current instant: a row whose timestamp lies in the future (clock skew) is not counted.
If any part of the snapshot cannot be read (a database fault on the window totals, the per-tenant rows, or the recent / recent-blocked tails), the endpoint answers 503 { "error": "temporarily unavailable; retry later" } — never an all-zero response that would look like an idle account, nor empty lists shown as fact. (A failed spend-cap read marks only the capped rows budget_remaining_unknown; a failed credit read marks every row.)
Query parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
tenant_id |
string (UUID) | caller's tenant | Platform admin only: target one tenant, or omit / empty for the global view. Ignored (server-pinned) for every other role. Rejected → 400 {"code": "bad_param"} (admin): a value that is not one canonical tenant UUID — junk, a repeated parameter, a bare ?tenant_id. The same rule applies to GET /stats/timeseries, GET /stats/analytics, GET /logs and every /cogs/* route. The UUID-shape part of it (a non-UUID string → 400 bad_param) is enforced by the one shared tenant-scope resolver, so it also holds on the per-tenant routes (compliance, governance templates and dashboard, tenant knowledge, prompt library, groups, projects) — but those routes have no global view (an omitted tenant_id is 400 {"error": "tenant_id required", "code": "tenant_id_required"}) and answer a repeated or bare parameter with 400 {"error": "tenant_id must be a single value", "code": "bad_param"}; see each page. |
compare |
string | — | 1 adds previous — the comparison windows for today, yesterday and last_7d (see Previous-period comparison below). Accepted: absent (no comparison) or exactly 1. Rejected → 400: any other value, including 0, true, an empty value, a bare ?compare and a repeated parameter. |
tz_offset |
integer | 0 (UTC) |
The viewer's UTC offset in minutes, in the JavaScript Date.getTimezoneOffset() convention: UTC − local, so Central European Summer Time (UTC+2) is -120 and US Eastern Standard Time (UTC−5) is 300. Used only to anchor the today / yesterday calendar-day boundaries to the viewer's local midnight. Accepted: an integer within [-840, 720] (UTC−14 … UTC+14). Rejected → falls back to UTC (offset 0): any non-numeric, empty, repeated, out-of-range, or missing value (fractional values are floored toward −∞). It never causes an error and never influences authorization — it shifts a display window only. |
The GET /stats/timeseries series that back the dashboard sparkline glyphs accept the same tz_offset parameter and bucket in the viewer's local frame — so the daily (1d) bucket and, for a fractional-hour offset (e.g. India, UTC+5:30), the hourly buckets align with the viewer's local day/hour rather than UTC. For whole-hour offsets (e.g. Central Europe, US) the hourly buckets coincide with local hours either way. Omit tz_offset (or send a rejected value) and buckets fall back to UTC.
Response structure
{
"today": { ...PeriodStats },
"yesterday": { ...PeriodStats },
"last_7d": { ...PeriodStats },
"hour": { ...PeriodStats },
"last_min": { ...PeriodStats },
"by_tenant": [ ...TenantStats ],
"recent": [ ...RecentEntry ],
"recent_blocked": [ ...RecentBlockedEntry ]
}
read_source. Set by the request_log_read_source_dashboard setting: mysql (default), clickhouse, or mysql_fallback (ClickHouse was asked for but could not be proven complete, so MySQL answered). The figures are the same either way, apart from the last digit of money sums (floating-point summation order) and one placement: with clickhouse a request where a guardrail block only withheld a tool result or an agentic fetch in the agent's tool loop (marker guardrail_withheld) counts as blocked, while MySQL (mysql and mysql_fallback) places it by its other columns only, normally as flagged (scrubbed if a masking detector also scrubbed it). A fallback can therefore move such a request from blocked to flagged between two refreshes with no change in the data. With clickhouse the figures cover the newest minutes too (the read ends at the same instant as MySQL's), but the coverage check only counts rows older than 5 minutes, so rows still being shipped in the newest 5 minutes may be missing from last_min, hour and by_tenant. The check also compares the number of requests with detector hits (the source of flagged): after a retention anonymisation or a user erasure MySQL no longer holds those hits, so /stats is answered from MySQL (mysql_fallback) while ClickHouse still holds the original hits. An erasure in the newest 5 minutes is picked up once that window has passed. recent and recent_blocked always come from MySQL.
recent and recent_blocked resemble LogEntry but are not the same shape. recent (up to 10 newest entries) omits id and instead adds the tenant and gateway slugs alongside the IDs; it carries cache_read_tokens and cache_creation_tokens next to input_tokens / output_tokens (input_tokens excludes the prompt cache). recent_blocked (up to 20 newest blocked/scrubbed/flagged entries) is a narrow subset carrying the entry id, the block/guardrail fields and has_content (1/0: whether any prompt or answer content is stored). It no longer carries prompt_scrubbed or response_raw, but keeps payload_expired (boolean) and payload_expired_at (integer unix seconds | null; null also for an unreadable marker), defined in LogEntry; fetch the content with GET /logs/{id} and an X-Read-Reason.
block_reason requires REQUEST_LOGS_VIEW. Both recent and recent_blocked include block_reason only when the caller holds REQUEST_LOGS_VIEW; otherwise the key is absent (not null). Under the same rule each recent_blocked entry also carries meta, the request's protection markers (for example detector_types_fired, the detector types behind the table's Type column, and guardrail_block_where), and upstream_attempts; without the permission neither key is present. A missing or unreadable permission answer gets the narrow shape, and a fault in the permission layer answers 503 ({"error":"temporarily unavailable; retry later"}). For a keyword, regex, custom_pii or jailbreak block the value is redacted:<type>:<12 hex> (see Guardrails); rows written before this change may still hold the raw matched value until request-log retention removes them.
PeriodStats fields
| Field | Type | Description |
|---|---|---|
requests |
integer | Total inference requests in the period. |
cached |
integer | Requests served from cache (no provider call made). |
blocked |
integer | Requests blocked by auth, rate limit, quota, or detectors. With read_source clickhouse this also counts a request where a guardrail block withheld a tool result or an agentic fetch in the agent's tool loop without refusing the request (marker guardrail_withheld), as the Recent guardrail events table shows it; from MySQL such a request is in flagged (or scrubbed). |
rate_limited |
integer | Requests that hit a rate limit in the period. |
scrubbed |
integer | Requests where a guardrail scrubbed PII (personally identifiable information) from the payload but allowed the request through. With read_source clickhouse a scrubbed request where a guardrail block also withheld a tool result in the agent's tool loop counts as blocked instead; from MySQL it stays here. |
flagged |
integer | Requests where a guardrail fired but the request was neither refused nor scrubbed. From MySQL (read_source mysql or mysql_fallback) this includes a request where a guardrail block only withheld a tool result in the agent's tool loop (marker guardrail_withheld), which the Recent guardrail events table shows as Blocked; with clickhouse that request counts as blocked instead. MySQL does not read the marker here: the window query is served from an index alone, and the marker is not in it. |
input_tokens |
integer | Total prompt tokens consumed. |
output_tokens |
integer | Total completion tokens generated. |
cost_usd |
number | Total cost in USD (from model pricing table). |
saved_cost_usd |
number | Cost saved by cache hits (would-have-been cost of cached requests). |
avg_latency_ms |
number | Average end-to-end request latency in milliseconds. |
avg_upstream_latency_ms |
number | Average time waiting for the upstream provider, excluding gateway overhead. |
Previous-period comparison (compare=1)
With compare=1 the response gains previous:
"previous": {
"today": { ...PeriodStats, "from": 1760306400000, "to": 1760338800001, "complete": true },
"yesterday": { ...PeriodStats, "from": 1760220000000, "to": 1760306400000, "complete": true },
"last_7d": { ...PeriodStats, "from": 1759215600001, "to": 1759820400001, "complete": false }
}
Each entry is the comparison window for the window of the same name, with the same metrics (PeriodStats) plus:
| Field | Type | Description |
|---|---|---|
from, to |
integer | The comparison window, unix milliseconds, [from, to). |
complete |
boolean | false when the window cannot be trusted as complete for the caller's scope: the tenant was created after from, its request-log retention has deleted rows after from (rows are deleted at the later of the Löschfrist and 730 days; anonymisation at the Löschfrist does not make a window incomplete because the billing facts are kept), or the coverage could not be determined (lookup failed / unknown tenant). On the global, all-tenant view it is false when any live tenant's retention reaches past from. The check is conservative: it does not consider whether the retention job is switched on, and a tenant that recently raised its retention may already have lost older rows. Clients should show no change figure when complete is false. A tenant retention value that is present but malformed (for example negative) is treated as unknown: the previous windows are reported incomplete and user_attribution on the analytics response is unknown. |
The comparison rule (shared with GET /stats/analytics?compare=1): the comparison window is the same window shifted back by a whole number of days, max(1, ceil(window length / 1 day)) days. So it has the same length, starts and ends at the same time of day, and never overlaps the current window:
today(midnight to now) → the same span yesterday.yesterday→ the day before.last_7d(exactly 7 × 24 h) → shifted 7 days: the 7 × 24 hours directly before it,[from − 7 d, from), with no gap between the two windows. When a daylight-saving change lies between them, the comparison window sits one hour earlier or later on the wall clock.
The day is a fixed 24 h, so on a daylight-saving change day the comparison window is off by one hour — and a window that contains the 25-hour autumn change day and is longer than 24 h ("today" after 23:00 local time on that day, or "yesterday" on the day after) is shifted by two days instead of one. hour and last_min are never compared. Without compare there is no previous key and the query is not widened.
TenantStats fields (GET /stats)
by_tenant in GET /stats is a summary view with the following fields:
| Field | Type | Description |
|---|---|---|
tenant_id |
string | Tenant UUID. |
tenant |
string | Tenant slug. |
requests |
integer | Total requests. |
input_tokens |
integer | Total input tokens. |
output_tokens |
integer | Total output tokens. |
cost_usd |
number | Total cost in USD. |
budget_remaining |
number | Remaining USD for the tenant — the live-monitor "Quota Left" column: the lower of the remaining monthly spend cap (spend_cap_usd minus current-period tenant spend) and the remaining wallet credit. Not clamped: an over-cap tenant reads negative. A tenant whose spend cap is invalid reads 0. Absent only when budget_remaining_unknown is true. |
budget_remaining_bound |
string | Which limit budget_remaining reflects: "wallet" (remaining credit) or "spend_cap" (the monthly cap; also on a tie). Present whenever budget_remaining is. |
balance_fx_pin |
object | Present only when budget_remaining_bound is "wallet" and the tenant's balance is held at a fixed display-currency rate: the currency and rate to show the credit figure at. |
budget_remaining_unknown |
boolean | true when the remaining budget could not be computed (a transient spend-cap or credit read failure) — distinct from "no limit". |
The full TenantStats shape (with blocked, cached, errors, avg_latency_ms, etc.) is returned by GET /stats/analytics. See below.
Example response
{
"today": {
"requests": 1423,
"cached": 82,
"blocked": 14,
"input_tokens": 1840200,
"output_tokens": 312400,
"cost_usd": 9.84,
"saved_cost_usd": 0.41,
"avg_latency_ms": 820,
"avg_upstream_latency_ms": 760
},
"yesterday": {
"requests": 2101,
"cached": 134,
"blocked": 22,
"input_tokens": 2750000,
"output_tokens": 480000,
"cost_usd": 14.30,
"saved_cost_usd": 0.67,
"avg_latency_ms": 905,
"avg_upstream_latency_ms": 850
},
"last_7d": { "requests": 11200, "cost_usd": 68.12, "..." : "..." },
"hour": { "requests": 61, "cost_usd": 0.38, "...": "..." },
"last_min": { "requests": 2, "cost_usd": 0.01, "...": "..." },
"by_tenant": [
{
"tenant_id": "ten_abc123",
"tenant": "myapp",
"requests": 1423,
"input_tokens": 1840200,
"output_tokens": 312400,
"cost_usd": 9.84
}
],
"recent": [ { "...": "LogEntry" } ],
"recent_blocked": [ { "...": "LogEntry" } ]
}
For the related LogEntry field definitions see the Logs API. Note that the recent and recent_blocked rows are not full LogEntry objects (see the field notes above).
GET /stats/analytics
Machine access: a token scoped exactly
["admin_read"]may call this route withAuthorization: Bearer(details). With a bearer,anonymize=0/falseis refused403.
Returns latency percentiles, top-model breakdown, and per-tenant, per-gateway, per-channel, per-agent, and per-user cost summaries, plus activity counters. Used by the analytics dashboard view.
On the global, all-tenant view (a platform admin who omits tenant_id), every grouping and counter excludes synthetic fixture tenants — e.g. the e2e-synthetic monitoring prober — so the platform analytics reflect real usage. A tenant-scoped view (?tenant_id=…) still returns them.
read_source. Every 200 carries a top-level read_source field: mysql (default), clickhouse or mysql_fallback, set by the request_log_read_source_analytics setting. One value covers the whole response: clickhouse only when every part routed to ClickHouse was answered by it; mysql_fallback when ClickHouse was asked for but the coverage check refused it, a read failed, the reply was malformed, or a user id was anonymised in MySQL (retention) but is still present in ClickHouse, so a distinct-user count would read higher (the request then reads MySQL from that point on, never a partial mix). The field is present also without compare and when summary is omitted after a failed read.
Covered parts (read from ClickHouse when the setting is clickhouse): counters.active_users, the summary with compare=1 (the current window and the previous window), percentiles, top_models, by_tenant, by_gateway, by_channel, by_agent, by_agent_series, by_user, unattributed and the request-log figures of cache_efficiency. by_user and unattributed are not read at all while anonymize is on. Always MySQL, whatever the label: user_attribution, by_department, the user e-mail labels of by_user (looked up by user id), the model prices behind cache_efficiency, the per-agent conversations counts inside by_agent (they come from request_log_legs), the other five counters, previous_window.complete (a tenant-table lookup) and the days that the usage_daily rollup supplies.
Percentiles. percentiles uses the nearest-rank definition on both stores: with n non-blocked rows that carry a latency, the value at quantile q is the k-th smallest, k = ceil(n * q / 100). The result is exact (not an estimate) with mysql and clickhouse. Keys are omitted when there are no such rows.
Fallback contract. Any ClickHouse failure in the depth blocks (coverage check refused, read failed, malformed reply, ClickHouse memory limit hit) sends the WHOLE response from MySQL and labels it mysql_fallback; a response never mixes the two stores. A failure of a MySQL-side grouping is not a fallback; it is listed in degraded as before (now also "percentiles" and "cache_efficiency").
Changes that apply to both sources. (1) by_user keys are byte-exact: user ids that differ only by case, accent or trailing spaces are separate rows (they used to merge under the case-insensitive column collation); ties in the top-50 are ordered by the id bytes. (2) cache_efficiency is computed per (provider, model) from the request log and priced from one model_price lookup, identically on both sources; cache_hit_pct is an exact integer division rounded half up to one decimal, so it can differ in the last digit from the former SQL float expression. If the cache figures or the price lookup fail, the response states the failure: "cache_efficiency" is listed in degraded (it used to be an empty object with nothing in degraded); the dashboard card stays hidden as before. (3) An absent email on a by_user row means the user was deleted or the label lookup failed (the failure is logged); the row and its figures are kept, keyed by the user id.
Anonymisation and erasure. When MySQL holds rows in the settled guard window that were anonymised there after they were shipped (the personal_scrubbed flag counted higher in MySQL than in ClickHouse; retention sweep, owner or driver erasure, tenant purge), the response is mysql_fallback, whichever user columns the rows carried and whatever the retention setting is now. A GDPR Art. 17 erasure that has rows in this read's population (owner or driver of a request in the scope and window) also gives mysql_fallback; an erasure elsewhere does not change the source.
Change in groupings (all sources). Grouping keys of top_models, by_tenant, by_gateway, by_channel, by_agent (and by_agent_series, and the conversations counts) are compared byte for byte, and by_agent counts distinct users byte for byte as well: names that differ only by case, an accent or a trailing space are separate rows (formerly merged by MySQL's collation). Days that the usage_daily rollup supplies keep the casing the synchroniser stored. by_agent rows with equal cost are ordered by the root agent id bytes. If the gateway slug or the agent name cannot be looked up under clickhouse, the row is labelled by its id.
Residuals: money sums can differ in the last digit (floating-point summation order). The coverage check only counts rows older than 5 minutes, so rows still being shipped in the newest minutes may be missing with clickhouse. ClickHouse compares user ids byte for byte, MySQL case-insensitively and ignoring trailing spaces: a group view whose member id differs from a stored id only by case, or a user id made only of spaces, can count differently (the gateway writes canonical lowercase UUIDs only, so this does not occur in normal operation). A tenant id that differs only by case makes the request fall back to MySQL.
The settle grace applies to the depth blocks too (the newest 5 minutes may be missing with clickhouse). A latency of NULL occurs only in hand-written rows (the gateway always writes one for a non-blocked request).
Change in counters.active_users (all sources). The count is now byte-exact: user ids that differ only by letter case, accents or trailing spaces count as separate users, on MySQL as on ClickHouse. Previously MySQL merged such variants. For canonical UUIDs the figure is unchanged.
Query parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
since |
integer | 24 hours ago | Start of the analysis window as Unix milliseconds. Accepted: absent, or a string of 1–15 decimal digits. Rejected → 400: anything else — a sign, a decimal point, an exponent (1e12), nan/inf, an empty value, a bare ?since or a repeated parameter. A value older than 400 days is raised to 400 days ago. |
until |
integer | now | Optional upper bound as Unix milliseconds; same accepted / rejected shapes as since. A value in the future is lowered to the current instant, and that same value bounds every part of the response (groupings, counters and summary), so the summary totals and the breakdown tables always cover the same window. Used for closed windows such as "yesterday". A window that would be inverted — a since (after the 400-day floor) not before until, or (with since omitted) an until at or before the default start 24 hours ago — is 400 { "code": "bad_param" }, never an empty window answered as "no activity" (so since=2023-01-01&until=2024-01-01 is a 400). This check uses the until you sent, before it is lowered to now: a correctly ordered window that lies wholly in the future (typically a device clock ahead of the server) is not an error — it is answered 200, and with compare=1 its summary reports comparable: false, reason: "invalid_window" (formerly window_invalid). |
compare |
string | — | 1 adds summary (see Period summary and previous-period comparison below). Accepted: absent or exactly 1. Rejected → 400: any other value, a bare ?compare or a repeated parameter. With compare=1, both since and until are required (400 when either is absent): the comparison is computed from the exact window the client chose. |
tenant_id |
string | — | Filter by tenant. Honoured only for callers with the admin role. Non-admin callers are always scoped to their own tenant (a value they send is ignored). Accepted (admin): absent or empty (= the global, all-tenant view — grants nothing beyond the admin's own rights) or one canonical tenant UUID. Rejected → 400 {"code": "bad_param"}: any other value — a non-UUID string, a repeated parameter, or a bare ?tenant_id without a value. |
anonymize |
boolean | true (anonymized) |
Anonymized by default. Unless the caller explicitly opts out with anonymize=0 (or false), the response omits the per-user grouping (by_user) entirely — no individual identifiers (email/user_id) are returned. Any other value (absent, 1, true, or malformed) keeps the response anonymized (fail-closed). Aggregate groupings (channel, agent, model, gateway, tenant) and counters are always included. The flag is scoped to this endpoint. Note: in a single-user tenant, per-agent/per-model aggregates can still imply one person's usage. |
group_id |
string | — | Restrict the whole response to the members of one user group. For a KI-Manager this must be a group they manage (see below); admin/tenant_admin may narrow to any group in their tenant scope. An unknown or out-of-scope group_id (including a group_id paired with a mismatched tenant_id) returns 404 not found, recorded as one access.denied event (ids of a group you cannot see); A spelling variant of a real group id (another letter case, a trailing space, an invisible or full-width character) counts as unknown, because ids are matched byte-exact; a KI-Manager gets this 404 rather than 403. a KI-Manager requesting a same-tenant group they do not manage returns 403 forbidden. Minimum group size: a group (or a KI-Manager's union of managed groups) with fewer distinct members than the workspace minimum (5 by default) is refused with 403 { "code": "group_below_minimum", "k_min": 5 } (k_min is the workspace's report_min_group_size, 5 by default; an unreadable value is refused 503 {"code": "privacy_policy_unreadable"}) so no individual can be singled out; an empty group still returns the all-zero response, and the tenant-wide view is unaffected. The same rule applies to GET /stats/usage-series. A repeated group_id or a bare ?group_id returns 400 {"code": "bad_param"}; a database fault while looking the group up returns 503 (retry). |
tz_offset |
integer | 0 (UTC) |
The viewer's UTC offset in minutes, in the JavaScript Date.getTimezoneOffset() convention: UTC − local (Central European Summer Time = -120, US Eastern Standard Time = 300). Applies only to the per-agent daily series (by_agent_series), whose buckets are floored in the viewer's local frame so each daily bar starts at the viewer's local midnight — aligning it with the calendar-day window (since/until) the caller computes with the same offset. Accepted: an integer within [-840, 720] (UTC−14 … UTC+14). Rejected → falls back to UTC (offset 0): any non-numeric, empty, repeated, out-of-range, or missing value (fractional values are floored toward −∞). It never causes an error and never influences authorization — it shifts the bucket boundaries only. |
💡 Note:
/stats/analyticsrequires theANALYTICS_VIEWpermission (View analytics dashboards; held byadmin,tenant_adminandki_managerby default, grantable through a custom role); callers without it (by defaultmember,viewer,demouser) receive403 forbidden. Theanonymize=0opt-out is therefore confined to those privileged roles, and only ever reveals users within the caller's authorized scope:admin/tenant_adminsee their own tenant (atenant_adminis pinned to it), while aki_manageris pinned to the members of the groups they manage. Any role that could sendanonymize=0without authorization is already blocked with403before the handler runs; the client value never decides access.💡 Named-person reports policy: a workspace can forbid the reveal altogether (
named_reports_enabled). With the policy off,anonymize=0/falseby a workspace role is refused403{ "code": "named_reports_disabled" }(a missing or unreadable policy is refused the same way; a database fault is503). The anonymized response carriesnamed_reports_allowed(boolean) so a client can lock its control. Every allowed reveal writes ananalytics.named_report_viewedaudit row (tenant-scoped for a workspace,entity_idglobalfor an unscoped platform-administrator view); if that row cannot be written the reveal is refused with a generic500. Platform administrators are not bound by the policy. The finance routeGET /admin/v1/cogs/per-useris not covered by this guard.💡 Requests without a person: a request whose user was erased, or that was made by an agent or a service token, has no person attached. Inside the requested window such requests stay in the totals (requests, cost, tokens, the per-tenant, gateway, provider, model and channel groupings), but they are left out of every per-person figure:
by_user,counters.active_users, the distinct-user counts ofby_agentand the health summary.Requests older than the request-log retention period can no longer be attributed to a person at all: the retention sweep anonymises them and merges their per-user rollup rows into the unattributed total, so
user_attribution.from_msmoves to the next UTC midnight at or after the cutoff and per-person figures stop there. The totals stay complete until the billing record is deleted at the later of the Löschfrist and 730 days.A view scoped to a group (
group_id) counts only requests that can be attributed to a member, so its totals leave the others out. The same holds forGET /admin/v1/stats/usage-seriesand the period summary (compare=1) in a group view.The response says how far this reaches:
unattributed-{ requests, cost_usd, input_tokens, output_tokens }, the requests no person can be named for. Omitted whenanonymizeis on.user_attribution-{ complete, from_ms, scope }.scopeis"all"(no group scope) or"group"(totals exclude unattributed requests).complete: falsewith afrom_msmeans the per-person figures are complete only from that time on;complete: falsewithfrom_ms: nullmeans the coverage could not be determined.
KI-Manager group scoping
A KI-Manager may optionally see the statistics of the groups they manage. Unlike admin/tenant_admin (who see the whole tenant/workspace), a KI-Manager is always scoped to a group's members and can never see tenant-wide or another group's data:
- "Groups they manage" are the groups the KI-Manager created (
user_group.created_by). This is the same boundary as the group-management API (can_manage_group). Limitation: the data model has no separate "group manager" or delegation concept, so a group created by an admin and handed to a KI-Manager to run — or a group whose creator account was later deleted (created_bybecomesNULL) — is not visible to the KI-Manager. Onlyadmin/tenant_adminsee those. - Without
group_id: the response covers the union of the members of all groups the KI-Manager manages. A KI-Manager who manages no (non-empty) groups gets an all-zero response — never a tenant-wide fallback. - With
group_id: the response covers only that group's members, and only if the KI-Manager manages it (else403/404as above). - "A group's statistics" = activity by the group's members. All groupings and counters are filtered to
request_logrows / rows owned by the member set. Becauserequest_logcarries no group dimension, this is the only coherent definition. Consequences to keep in mind:by_agentis filtered on the run-as owner (user_id) — which, because invoke is owner-only, is the real member who invoked. Rows roll up over the clone lineage (see AgentStats), so a KI-Manager sees, for each shared agent, the invocations/conversations/distinct-users contributed by their members' clones of it (the display name is the root agent's, which may be owned outside the group).active_usersis windowed: under a group filter it is the count of the group's members active in the window (distinct members with ≥1 request in the period), not the group's current member count.
Response structure
{
"percentiles": { ...LatencyPercentiles },
"top_models": [ ...TopModelRow ],
"by_tenant": [ ...TenantStats ],
"by_gateway": [ ...GatewayStats ],
"by_channel": [ ...ChannelStats ],
"by_agent": [ ...AgentStats ],
"by_agent_series": [ ...AgentSeries ],
"by_user": [ ...UserStats ],
"by_department": [ ...DepartmentStats ],
"counters": { ...ActivityCounters },
"unattributed": {"requests": 7, "cost_usd": 1.5, "input_tokens": 10, "output_tokens": 20},
"user_attribution": {"complete": false, "from_ms": 1761868800000, "scope": "all"},
"anonymized": true,
"degraded": [],
"cache_efficiency": { ...CacheEfficiency },
"summary": { ...PeriodSummary }
}
anonymized states whether the per-user grouping was withheld for this response; clients should rely on it rather than on what they requested. degraded lists the response keys whose query failed — each entry is the name of a key in this response, and only these can appear: "top_models", "by_tenant", "by_gateway", "by_user", "by_channel", "by_agent" (also when only its per-agent conversations counts could not be loaded), "by_agent_series", "by_department", "unattributed", "percentiles", "cache_efficiency"; each of those is returned empty (unattributed: as zeros; cache_efficiency: as an empty object), so an empty grouping that appears in degraded means "could not be loaded", not "no activity". It is an empty array ([]) when every grouping succeeded.
Every grouping (percentiles, top_models, by_tenant, by_gateway, by_channel, by_agent, by_agent_series, by_user, cache_efficiency) and the summary cover the same scope — the tenant / group filter, and only live tenants: traffic of a deleted (or no longer existing) tenant is excluded, so these totals reconcile. The activity counters are counted separately and are not narrowed this way.
by_department (one object per department) is the chargeback query behind GET /admin/v1/cogs/per-department with bucket=total and its default billable_only=1, collapsed to one row per department. Its totals therefore equal that export for the same window, and it is scoped the same way as the other groupings: tenant filter, group scope (an empty group scope returns []) and global fixture exclusion. Like the export (and unlike the other groupings), it does not drop the spend of a deleted tenant. It reads the per-leg billing ledger, which records time in whole seconds, so since / until are rounded down to the second. Each row has the fields department_id (string, "" = no department), department (name, "" when there is no department or the department was deleted), cost_centre (the department's cost centre, a string such as "0410", "" when none is set), budget_usd (number or null), budget_period ("daily", "weekly", "monthly", "total" or null), period (always "total"), and the numbers users (distinct people), requests, input_tokens, output_tokens, total_tokens and cost_usd. Rows are ordered by cost_usd, highest first. Unlike by_user, it carries no personal identifiers and is returned in anonymized mode too.
Data source. top_models, by_tenant, by_gateway, by_user and by_channel are served from the usage_daily rollup for whole UTC days that are at least two days old and from request_log for the remaining time, then merged per key; the figures (requests, blocked, cached, tokens, cost_usd, saved_cost_usd, avg_latency_ms, errors, client_aborted) are identical to a request-log-only answer. Days whose raw rows were purged by retention stay visible from the rollup. A rollup row written before gateway and channel were part of its grain reports gateway and channel as unknown and cached / errors as 0.
Data-warehouse extractors. Read the view usage_daily_legacy_grain (the previous six-column grain: day, tenant, user, model, provider, API variant; counters summed, updated_at the newest of the folded rows) rather than the table, and reload the whole day range on a change instead of relying on row identity: a re-run of a day replaces its rows.
Period summary and previous-period comparison (compare=1)
"summary": {
"window": { "from": 1759743600000, "to": 1760348400000 },
"comparable": true,
"previous_window": { "from": 1759138800000, "to": 1759743600000, "complete": true },
"current": { "requests": 700, "errors": 5, "cost_usd": 11.7, "saved_cost_usd": 0.6,
"input_tokens": 1000000, "output_tokens": 200000 },
"previous": { "...": "same keys" },
"bucket_ms": 21600000,
"series": [ { "ts": 1759730400000, "requests": 12, "errors": 0, "cost_usd": 0.21,
"saved_cost_usd": 0.01, "tokens": 31000 } ]
}
| Field | Type | Description |
|---|---|---|
window |
object | The window actually used (until lowered to now), unix ms, [from, to). |
comparable |
boolean | false when the window cannot be compared; reason then says why: invalid_window (formerly window_invalid; until ≤ since after lowering until to now — typically a client clock ahead of the server) or span_too_long (longer than 92 days). A window that cannot be compared is not an error: the rest of the response is unaffected. |
previous_window |
object | Only when comparable. The comparison window and complete — false when the previous window is not fully recorded for the caller's scope (see GET /stats → previous; for a group-scoped view the group's tenant is checked). |
current |
object | The window's totals: requests; errors (HTTP status ≥ 400, excluding 499 client aborts); cost_usd; saved_cost_usd; input_tokens (the non-cached input); output_tokens. Cache-read and cache-write tokens are not part of the summary (see cache_efficiency for them). Same scope as the groupings (the same tenant / group filter, deleted tenants excluded), so current.cost_usd equals the sum of by_tenant[].cost_usd up to their per-row rounding. Absent when reason is invalid_window (no window) or the read failed; present for span_too_long. |
previous |
object | The same totals for previous_window. Absent when not comparable or when its read failed — clients then show no change figure (never treat absent as zero). |
bucket_ms, series |
integer, array | The window bucketed for sparklines (1 h, 6 h or 1 day, chosen from the window length; buckets aligned to the viewer's tz_offset). tokens is input + output. The first bucket can start before window.from and the last can end after window.to (partial buckets; their rows are inside the window). Absent for span_too_long and invalid_window. |
The comparison window uses the same rule as GET /stats: the same window shifted back by max(1, ceil(length / 1 day)) days — 7 days for a 7-day window, the same time span yesterday for "today". This is why until is required with compare=1: without it the window would end at the server's (slightly later) clock, be a few milliseconds longer than 7 days, and be compared with an 8-day-shifted window.
ChannelStats fields (UI vs API vs agent)
Each row is the usage attributed to one access channel. The channel is derived: agent for agent invocations, ui for chat-session (playground) tokens, api otherwise.
| Field | Type | Description |
|---|---|---|
channel |
string | ui, api, or agent. |
requests |
integer | Request count for the channel. |
blocked |
integer | Requests blocked or scrubbed by a guardrail. |
cached |
integer | Requests served from the response cache. |
input_tokens |
integer | Total prompt tokens consumed on the channel. |
output_tokens |
integer | Total completion tokens produced on the channel. |
cost_usd |
number | Total cost. |
saved_cost_usd |
number | Cost avoided by cache hits. |
errors |
integer | HTTP ≥ 400 (excluding client-cancel 499). |
client_aborted |
integer | Requests the client cancelled (HTTP 499). |
avg_latency_ms |
integer | Average latency for non-blocked requests. |
AgentStats fields (per agent, rolled up over the clone lineage)
Each row is one lineage root — a shared/original agent plus every clone made from
it. Rows are keyed by agent_id = the root's id; a clone's usage rolls into its root
(the counting model below). Filtering (tenant, KI-Manager group scope) applies before the
roll-up.
| Field | Type | Description |
|---|---|---|
agent_id |
string | The lineage root agent's id (a shared agent + its clones share one row). |
agent |
string | Root agent name (or slug). A hard-deleted root falls back to the raw id. |
invocations |
integer | Invocations across the lineage in the window. |
conversations |
integer | Distinct chat sessions the lineage was used in. Headless invokes (API/schedule) carry no session id and count as invocations, not conversations — so this is 0 for agents only ever invoked headlessly, and becomes non-zero when an agent is used inside a chat thread. Read from request_log_legs.conversation_id; no per-invoke session id is fabricated. |
distinct_users |
integer | Distinct people who used the lineage — see the counting model below. |
cost_usd |
number | Total cost across the lineage. |
Per-agent "distinct users" — the counting model. A sharee runs a shared agent directly as the caller (
invoker_id= that member), so a single agent's distinct-invoker count can exceed 1. Members who instead use the catalog "clone" action own a distinct clone and invoke it as owner. To cover both paths,COUNT(DISTINCT invoker_id)is taken across the clone lineage (the root and its clones). A clone records its lineage root inagent.source_agent_id(flattened so the tree is one level); every request stampsrequest_log.agent_root_id, so the count survives the clone being deleted. Caveats: lineage is recorded from the release that introduced it — pre-existing clones are not retro-linked; and the lineage pointer is client-declared within the caller's visibility (a member can omit it → undercount, or attribute a clone to any agent they can already see) — so the clone part ofdistinct_usersis best-effort, not server-authoritative. Unattended runs (scheduler/service token) log aNULLinvoker and are excluded from the count.
AgentSeries fields (per-agent calls over time)
One entry per top agent (up to 8, by invocation count) carrying a daily-bucketed
invocation time series. The series is dense and zero-filled across the window, so every
day is present even with no calls. Timestamps are milliseconds since epoch (bucket
start); when the tz_offset query parameter is supplied the bucket start is the viewer's
local midnight rather than UTC midnight (so the bars align with the viewer-local
calendar-day windows). Empty ([]) when there are no agent invocations in the window.
| Field | Type | Description |
|---|---|---|
agent_id |
string | The lineage root agent's id (the same key as by_agent; clone invocations roll into it). |
agent |
string | Agent name (or slug). |
series |
array | Daily points: { "ts": <ms>, "invocations": <integer> }. |
ActivityCounters fields
Counts for the window, scoped to the tenant filter. With no tenant filter (all tenants), active_users counts only users of live tenants, consistent with the groupings; users of deleted tenants are not included. *_created count items created in the window; active_users counts distinct users active in the window — users with at least one logged request (UI or API channel) between since and until. System/unattributed requests (no user_id) are excluded; duplicate requests by one user count once. It is not the provisioned-user headcount, so it can differ from the number of user rows (e.g. a user active in the window then deleted still counts).
Two caveats follow from active_users being derived from request_log:
- No explicit window (as in the tenant export's usage-statistics snapshot) →
active_usersreflects the trailing 24h, consistent with the sibling*_createdcounters, which use the same default. The provisioned headcount remains available separately (e.g. the export'susersarray). - Request logging disabled for a tenant (
request_logging_disabled) → norequest_logrows are written, soactive_usersreads0even whileconversations/messages(sourced from the chat tables) show activity.
| Field | Type |
|---|---|
conversations |
integer |
messages |
integer |
agents_created |
integer |
projects_created |
integer |
documents_created |
integer |
active_users |
integer (distinct users active in the window) |
LatencyPercentiles fields
| Field | Type | Description |
|---|---|---|
p50 |
number | null | Median end-to-end latency in milliseconds. null if no data. |
p95 |
number | null | 95th-percentile latency in milliseconds. |
p99 |
number | null | 99th-percentile latency in milliseconds. |
Percentiles cover only non-blocked requests.
TopModelRow fields
| Field | Type | Description |
|---|---|---|
model |
string | Model name. |
provider |
string | Provider slug (e.g. openai, anthropic). |
requests |
integer | Request count in the window. |
blocked |
integer | Requests blocked or scrubbed by a guardrail. |
cached |
integer | Requests served from the response cache. |
input_tokens |
integer | Total prompt tokens consumed by the model. |
output_tokens |
integer | Total completion tokens produced by the model. |
cost_usd |
number | Total cost in USD. |
saved_cost_usd |
number | Cost avoided by cache hits. |
errors |
integer | HTTP ≥ 400 (excluding client-cancel 499). |
client_aborted |
integer | Requests the client cancelled (HTTP 499). |
avg_latency_ms |
number | null | Average end-to-end latency (ms) over non-blocked requests; null if every request was blocked. |
Up to 10 models are returned, ordered by request count descending.
GatewayStats fields
| Field | Type | Description |
|---|---|---|
gateway_id |
string | Gateway UUID. |
gateway |
string | Gateway slug. |
tenant |
string | Tenant slug (the tenant id when no slug is found). |
requests |
integer | Total requests. |
blocked |
integer | Requests blocked or scrubbed (counts blocked=1 OR scrub_applied=1). |
cached |
integer | Cache hit count. |
input_tokens |
integer | Total input tokens. |
output_tokens |
integer | Total output tokens. |
cost_usd |
number | Total cost in USD. |
saved_cost_usd |
number | Cost saved by cache hits. |
avg_latency_ms |
number | null | Average end-to-end latency (ms) over non-blocked requests; null if every request was blocked. |
errors |
integer | Requests that returned an HTTP status >= 400, excluding 499 client-aborted. |
client_aborted |
integer | Requests the client aborted before response headers (HTTP 499). A stream cancelled after headers (Stop pressed mid-answer) is a status 200 row with aborted 1 in the request log and is not counted here. |
UserStats fields
| Field | Type | Description |
|---|---|---|
user_id |
string | User UUID (from the user_id field of the auth token). |
tenant_id |
string | Tenant UUID the user's requests belong to. |
email |
string | null | User email, if known. |
requests |
integer | Total requests attributed to this user. |
blocked |
integer | Requests blocked or scrubbed (counts blocked=1 OR scrub_applied=1). |
cached |
integer | Cache hit count. |
input_tokens |
integer | Total input tokens. |
output_tokens |
integer | Total output tokens. |
cost_usd |
number | Total cost in USD. |
saved_cost_usd |
number | Cost saved by cache hits. |
avg_latency_ms |
number | null | Average end-to-end latency (ms) over non-blocked requests; null if every request was blocked. |
errors |
integer | Requests that returned an HTTP status >= 400, excluding 499 client-aborted. |
client_aborted |
integer | Requests the client aborted before response headers (HTTP 499). A stream cancelled after headers (Stop pressed mid-answer) is a status 200 row with aborted 1 in the request log and is not counted here. |
by_user is empty by default (anonymized) and is populated only when the caller explicitly opts out with anonymize=0. When populated, it only includes requests made with auth tokens that have a user_id set; anonymous token requests are not included. Up to 50 users are returned, ordered by cost descending. The example below shows the opted-out (identifying) response — the default response has "by_user": [] and "anonymized": true.
CacheEfficiency fields
cache_efficiency summarises input-token caching and input cost over the window (successful requests across all providers). Providers with prompt caching (Anthropic) populate the cache-read/write terms; providers without it (e.g. local models) contribute only their standard input cost at a 0 % hit rate.
| Field | Type | Description |
|---|---|---|
cache_write_tokens |
integer | Prompt-cache write tokens — the total across both TTL tiers (the 1-hour part is counted once; it is a share of the total, not an addition to it). |
cache_read_tokens |
integer | Prompt-cache read tokens. |
standard_input_tokens |
integer | Non-cached input (prompt) tokens. |
uncached_cost_usd |
number | Cost that would have applied without the prompt cache. |
cached_cost_usd |
number | Cost actually incurred reading from the cache. |
cache_hit_pct |
number | null | Share of input tokens read from the provider's prompt cache, as a percentage. null when there is no data. |
compaction_tokens_saved |
integer | Input tokens saved by conversation compaction. |
compaction_cost_saved |
number | Cost saved by conversation compaction in USD. Each request's saving is taken in whole nano-dollars, the nano-dollars are added exactly, and the total is rounded once (half up) to 4 decimals, so the figure is the same whether the response is served from MySQL or ClickHouse. A saving that is out of range (a single request above 10,000 USD, or a total at or above 9.0e6 USD) is not served: cache_efficiency is then listed in degraded and the card is withheld. |
Example response
{
"percentiles": { "p50": 420, "p95": 1840, "p99": 3210 },
"top_models": [
{ "model": "gpt-4o", "provider": "openai", "requests": 842,
"input_tokens": 1120400, "output_tokens": 208900, "cost_usd": 3.14, "avg_latency_ms": 680 }
],
"by_tenant": [
{
"tenant_id": "ten_abc123", "tenant": "myapp",
"requests": 1423, "blocked": 14, "cached": 82,
"input_tokens": 1840200, "output_tokens": 312400,
"cost_usd": 9.84, "saved_cost_usd": 0.41,
"avg_latency_ms": 820, "errors": 3, "client_aborted": 1
}
],
"by_gateway": [
{
"gateway_id": "gw_xyz789", "gateway": "prod", "tenant": "myapp",
"requests": 1423, "blocked": 14, "cached": 82,
"input_tokens": 1840200, "output_tokens": 312400,
"cost_usd": 9.84, "saved_cost_usd": 0.41,
"avg_latency_ms": 820, "errors": 3, "client_aborted": 1
}
],
"by_channel": [
{ "channel": "ui", "requests": 900, "input_tokens": 1200000, "output_tokens": 210000,
"cost_usd": 6.10, "errors": 2, "avg_latency_ms": 610 },
{ "channel": "api", "requests": 400, "input_tokens": 560000, "output_tokens": 92000,
"cost_usd": 3.20, "errors": 1, "avg_latency_ms": 700 },
{ "channel": "agent", "requests": 123, "input_tokens": 80200, "output_tokens": 10400,
"cost_usd": 0.54, "errors": 0, "avg_latency_ms": 540 }
],
"by_agent": [
{ "agent_id": "agt_support", "agent": "Support Bot", "invocations": 90,
"conversations": 12, "distinct_users": 4, "cost_usd": 0.54 }
],
"by_agent_series": [
{ "agent_id": "agt_support", "agent": "Support Bot", "series": [
{ "ts": 1742457600000, "invocations": 12 },
{ "ts": 1742544000000, "invocations": 0 },
{ "ts": 1742630400000, "invocations": 31 }
] }
],
"by_user": [
{
"user_id": "usr_alice", "tenant_id": "ten_abc123", "email": "alice@myapp.example",
"requests": 341, "blocked": 2, "cached": 18,
"input_tokens": 440200, "output_tokens": 74800,
"cost_usd": 2.31, "saved_cost_usd": 0.09,
"avg_latency_ms": 790, "errors": 1, "client_aborted": 0
}
],
"anonymized": false,
"cache_efficiency": {
"cache_write_tokens": 12800, "cache_read_tokens": 90400,
"standard_input_tokens": 1737000,
"uncached_cost_usd": 27.40, "cached_cost_usd": 0.27,
"cache_hit_pct": 4.9,
"compaction_tokens_saved": 0, "compaction_cost_saved": 0
}
}
GET /stats/usage-series
Machine access: a token scoped exactly
["admin_read"]may call this route withAuthorization: Bearer(details).
Usage over time, broken down by the top 5 values of one dimension plus Other — the data behind the Cost analytics charts. Requires the ANALYTICS_VIEW permission (held by admin, tenant_admin, ki_manager, and any custom role it is granted to; without it: 403). Scope is the same as /stats/analytics: a tenant_admin is pinned to their tenant; every other holder — a KI-Manager or a custom role — is pinned to their tenant AND to the members of the groups they manage (group_id narrows further; never tenant-wide); a platform admin may pass tenant_id.
curl "https://<your-gateway-host>/admin/v1/stats/usage-series?since=1759190400000&dimension=model&metric=cost_usd&tz_offset=-120"
Query parameters
Every parameter is validated before any data is read. An absent parameter takes its default; a malformed one is rejected with 400 and a stable code (never silently defaulted).
| Parameter | Default | Accepted | Rejected → 400 |
|---|---|---|---|
since |
until − 30 days |
epoch milliseconds, digits only (≤ 15) | anything else — a sign, a decimal point, an exponent, nan/inf, a repeated or value-less parameter → bad_param |
until |
now | epoch milliseconds, digits only; a value in the future is capped to now | as since → bad_param |
dimension |
model |
model, provider, channel, agent, token_type |
any other value (case-sensitive) → bad_param |
metric |
cost_usd (tokens when dimension=token_type) |
cost_usd, requests, tokens |
any other value; with dimension=token_type any metric other than tokens → bad_param |
tz_offset |
0 (UTC) |
the viewer's UTC offset in minutes, JavaScript getTimezoneOffset() convention (UTC − local), an integer in [-840, 720] |
anything else — it moves the slot boundaries, so a malformed value is rejected, not ignored → bad_param |
tenant_id, group_id |
— | as for /stats/analytics |
as for /stats/analytics → bad_param |
The window is [since, until). After capping until at now:
since≥until→400invalid_window(formerlywindow_invalid; for example a device clock ahead of the server)until−since> 92 days →400span_too_long
The slot size is not a parameter; it follows from the window length: ≤ 25 hours → 1 hour, ≤ 8 days → 6 hours, otherwise 1 day. Slots are aligned to the viewer's local frame with ONE fixed offset per request (the current tz_offset) — slots from before a daylight-saving change inside the window therefore sit one hour off that period's local midnight.
Response
| Field | Type | Description |
|---|---|---|
dimension, metric |
string | The effective values. |
bucket_ms |
integer | The slot size in milliseconds. |
from |
integer | The window start (since, or until − 30 days when since is absent). buckets[0] < from means the first slot is only partly covered. |
until |
integer | The effective window end (exclusive). buckets[last] + bucket_ms > until means the last slot is only partly covered. |
buckets |
integer[] | Slot start times (epoch ms), oldest first, every slot present (zero-filled). |
series |
object[] | At most 5 entries, ordered by total descending (ties broken by the key's parts in byte order — for model: provider, then model). Each: key, label, total, values (one per slot). dimension=model adds provider and model (key is provider/model). dimension=channel keys are ui, api, agent; dimension=agent keys are the agent (lineage root) ids, label its name. dimension=token_type always returns input, cache_write, cache_read, output in that order. |
other |
object | null | { total, values } — everything outside the top 5; null when there is nothing else. |
Notes:
- Series keys are compared byte for byte:
gpt-5andGPT-5(or names differing only by an accent or a trailing space) are separate series. A series is dropped when its total over the window is not above zero. When two series tie ontotal(compared at 6 decimal places), the key's parts in byte order decide. read_source. Every200carries a top-levelread_sourcefield:mysql(default),clickhouseormysql_fallback, set by therequest_log_read_source_analyticssetting (the same switch as/stats/analytics). The body is otherwise identical in both modes. Withclickhousethe answer is served from ClickHouse behind the coverage check; if the check or the read fails, or the reply is not a valid answer (including a negative cost value), MySQL answers and the label ismysql_fallback. Group views anddimension=channeldepend on personal data: when an account erased under GDPR Art. 17 (recently) has requests in the very scope, user list and window being read, or when anonymisation has run (including rows that MySQL anonymised after they were shipped, flaggedpersonal_scrubbed, whatever the user columns held), they are answered by MySQL (mysql_fallback). An erasure of someone with no requests in that population does not change the source. An empty settled window (no traffic in it, or a window younger than the 5-minute settle grace) is also answered by MySQL and labelledmysql_fallback. The newest 5 minutes may be missing withclickhouse, and cost sums can differ from MySQL in the last digit.metric=tokensis input + output + cache-read + cache-write tokens.dimension=agentcounts only requests with an agent id.- A deleted tenant's traffic is excluded, as is synthetic monitoring traffic on the global (no
tenant_id) view. - A database fault returns
503(retry), never an empty200. - Cost values are rounded to 6 decimal places per slot and per total independently, so a series'
valuescan sum to itstotalwithin a few millionths.
GET /stats/timeseries
Returns an array of time-bucketed data points, suitable for rendering sparklines or charts. Buckets with no activity are included as zero-filled entries so the array length is always exactly n.
Scope follows GET /stats: non-admin callers are pinned to their own tenant and own data server-side; a caller with no tenant is refused 403. A platform admin may pass ?tenant_id= to target one tenant, or omit it (empty value included) for the global view. The global series excludes synthetic fixture tenants (e.g. the e2e-synthetic monitoring prober) and the traffic of deleted tenants (the same scope as the GET /stats totals); a tenant-scoped series includes both.
A malformed until — anything but 1–15 decimal digits, e.g. 1e22, inf, abc, a sign, a fraction, an empty or repeated value — is rejected with 400 {"code": "bad_param"}; an absent until means now. An all-digits value that lies far out of range yields an empty array — never a series of nonsense bucket times.
Query parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
bucket |
string | 1h |
Bucket size. One of: 5m, 15m, 30m, 1h, 6h, 1d; anything else is 400 { "code": "bad_param" }. |
n |
integer | 24 |
Number of buckets to return. Range: 1–168 (a larger number is capped, 0 reads as 1); anything but a plain integer of at most 9 digits is 400 { "code": "invalid_n" }. |
until |
integer | now | End of the time range as a Unix timestamp in seconds. Defaults to the current time. Accepted: absent or 1–15 decimal digits. Rejected → 400 { "code": "bad_param" }: anything else. |
tz_offset |
integer | 0 (UTC) |
The viewer's UTC offset in minutes, in the JavaScript Date.getTimezoneOffset() convention: UTC − local (Central European Summer Time = -120, US Eastern Standard Time = 300). Buckets are floored in the viewer's local frame, so the 1d bucket starts at local midnight and a fractional-hour offset (e.g. UTC+5:30) shifts the hourly buckets to local boundaries. Accepted: an integer within [-840, 720] (UTC−14 … UTC+14). Rejected → falls back to UTC (offset 0): any non-numeric, empty, repeated, out-of-range, or missing value (fractional values are floored toward −∞). It never causes an error and never influences authorization — it shifts the bucket boundaries only. |
Read-source header. The body is a bare array, so the read source travels as the response header X-Read-Source: mysql | clickhouse | mysql_fallback (always present; mysql while request_log_read_source_dashboard is off; semantics as read_source on GET /stats). The Admin SPA does not read it; it is an operator / test signal.
TimeseriesPoint fields
| Field | Type | Description |
|---|---|---|
ts |
integer | Bucket start time as Unix milliseconds. |
requests |
integer | Total requests in the bucket. |
blocked |
integer | Requests blocked in the bucket. |
rate_limited |
integer | Requests rate-limited in the bucket. |
errors |
integer | Requests that returned an HTTP status >= 400 (excluding 499 client-aborted) in the bucket. |
client_aborted |
integer | Requests the client aborted before response headers (HTTP 499) in the bucket. Streams cancelled after headers are status 200 rows with aborted 1 in the request log, not counted here. |
cost_usd |
number | Total cost in USD for the bucket. |
💡 Note:
tsis in Unix milliseconds (not seconds) for direct compatibility with charting libraries that expect millisecond-precision timestamps (e.g. Chart.js, Recharts, Grafana).
Example response
[
{"ts": 1742540400000, "requests": 42, "blocked": 1, "rate_limited": 0, "errors": 1, "client_aborted": 0, "cost_usd": 0.0314},
{"ts": 1742544000000, "requests": 67, "blocked": 0, "rate_limited": 0, "errors": 0, "client_aborted": 0, "cost_usd": 0.0521},
{"ts": 1742547600000, "requests": 0, "blocked": 0, "rate_limited": 0, "errors": 0, "client_aborted": 0, "cost_usd": 0.0},
{"ts": 1742551200000, "requests": 18, "blocked": 2, "rate_limited": 1, "errors": 2, "client_aborted": 1, "cost_usd": 0.0119}
]
GET /health/dashboard
GET /admin/v1/health/dashboard
Returns the aggregated operational-health summary that the Health dashboard renders in a single call — the synthetic-probe results, the last-24-hours non-2xx and client-aborted request counts, the phoned-home client errors, and the other failure surfaces shown there.
Requires the HEALTH_VIEW permission; the Health dashboard itself is available to the admin role only. A failed read of the health data returns 503 { "error": "temporarily unavailable; retry later" } (retry).
Read source and failed reads. The summary carries read_source (mysql, clickhouse or mysql_fallback) for its request-log counts (request_log_4xx_5xx, client_aborted_24h, scrub_preview_failures), governed by request_log_read_source_dashboard. Those counts cover the tenants that exist in the tenant table (soft-deleted ones included, fixture tenants excluded): request-log rows whose tenant has been purged (no tenant row any more) are no longer counted, on either source. Every block of the summary (the request counts, client errors, open content reports, needs_human triage items, synthetic probes and their recent runs, provider health, the scrub-preview failure count) is read in one pass and fails closed: if any of these reads fails, including the request-log counts on either source, the whole call answers that 503. A partly read summary is never returned, and a failed read never shows as zero or empty.
Platform web-search key. The summary carries web_search_platform_key_missing (boolean): true when the platform Linkup key (the trial_linkup_api_key setting — applied to every keyless Linkup gateway on every plan) is unset while at least one production gateway of a non-deleted tenant carries a keyless Linkup web_search block — i.e. web search is silently dark for it. false when the key is set, or when nothing depends on it yet. The companion object web_search_platform_key gives the inputs: { "key_set": boolean, "keyless_production_gateways": integer }. If the count could not be read, all three are absent and web_search_platform_key_error (string) is set to the fixed token "read_failed" (the cause is logged server-side, never returned) — a failed read is never reported as healthy; the dashboard renders "unknown". The same condition drives the [platform_alert] signal web_search_platform_key_missing (checked every 10 minutes, ERR-logged each check, notified at most every 6 hours).
Myra fleet token. The summary carries myra_fleet_token_unusable (boolean): true when this environment cannot use its Myra inference-fleet bearer (the encrypted myra_fleet_token setting) — every call to the Myra fleet (chat on the Myra models, OCR, embeddings, speech, images) then fails closed. myra_fleet_token_reason (string, only when true) names why, as a fixed token: absent, undecryptable, not_ciphertext, no_master_key, not_header_safe, or rejected — the value decrypts but the fleet refused it on its last authenticated call (a rotation this environment missed); never the value itself. If the setting could not be read (a transient failure), the flag is absent and myra_fleet_token_error (string) is "read_failed" — never reported as healthy. The same condition drives the [platform_alert] signal myra_fleet_token_unusable (re-checked every 10 minutes, at most one alert per 6 hours).
Audit chain. audit_chain_disabled (boolean): true when the tamper-evident audit-log chain is off because the audit_chain_key setting is absent or unusable — nothing is being sealed. audit_chain_reason (string, only when true) names why as a fixed token: absent, no_master_key, not_ciphertext, undecryptable, not_header_safe, or too_short; never the value. audit_chain_unsealed_over_1h (integer) is the live number of audit rows older than one hour that are still unsealed — a growing backlog means the sealer is stuck; the count is bounded and reported at most 100000, with audit_chain_unsealed_over_1h_capped (boolean) true when the true number is at least that. If the chain state could not be read, those fields are absent and audit_chain_error (string) is "read_failed" — never reported as healthy. The same state is exported on /metrics as the gauges aig_audit_chain_enabled (1/0) and aig_audit_chain_unsealed_over_1h, refreshed on every sealing tick; if the tick stops, the series expire after two hours (absent, not stale-healthy).
Public sub-processor register. The summary carries subprocessor_register_empty (boolean): true when the derived current sub-processor register — exactly the rows the public /trust page and /privacy §5.1 render — has no entry. Myra always engages sub-processors, so an empty register is never a valid production state: both legal pages then show "temporarily unavailable" instead of the list (they never claim there are none). The companion object subprocessor_register gives { "current": integer }. If the register could not be read, both are absent and subprocessor_register_error (string) is set to the fixed token "read_failed" (the cause is logged server-side, never returned) — a failed read is never reported as healthy (nor as empty); the dashboard renders "unknown". The same condition drives the [platform_alert] signal subprocessor_register_empty (checked every 10 minutes, ERR-logged each check, notified at most every 6 hours) and a post-deploy release check.
Plan-aware model copy. The summary carries plan_model_copy_stale (boolean): true when, for at least one offered model set served in the last 7 days, the set's current copy generation was rejected by the validator (or the set's catalog facts could not be read as valid input) — the model picker then shows that set's hand-written seed line, a checked catalog tagline or the model name instead (see Tagline resolution). plan_model_copy_indistinct (boolean) is true when a current set offers two models no fact tells apart (same price rank, context, capabilities, hosting and speed) — a plan-design problem, not a generator fault. The companion object plan_model_copy gives the counts: { "stale_sets": integer, "indistinct_sets": integer }. If the status could not be read, all three are absent and plan_model_copy_error (string) is set to the fixed token "read_failed" (the cause is logged server-side, never returned) — the dashboard renders "unknown", never healthy.
Knowledge vector tier. The summary carries knowledge_vector_tier: { "dedicated": integer, "migrating": integer, "attention": [ { "tenant_id": string, "tier": string, "reason": "promotion_error", "ts": integer } ], "attention_total": integer }. dedicated and migrating count tenants whose knowledge embeddings live in their own table or are moving there. attention lists tenants whose last promotion failed and is backed off for the long error window (next_promote_after more than 300 s ahead; ts is that retry time as a Unix timestamp in seconds); a tenant that is only busy-backed-off (300 s) is not listed. attention is [] when nothing needs attention, is sorted by latest retry first, and is capped at 50 rows; attention_total is the uncapped count (the dashboard shows "+N more"). There is no server-side status field: the dashboard derives the chip from the data - non-empty attention is a warning. Known blind spot: the last ~300 s of an error window drop out of attention before the retry runs. If the roll-up could not be read, knowledge_vector_tier is absent and knowledge_vector_tier_error (string) is the fixed token "read_failed" (the cause is logged server-side, never returned) - the dashboard renders "unknown", never healthy.
Stripe webhook subscription. The summary carries stripe_webhook, the result of the last check of this environment's Stripe webhook endpoint against the events the gateway handles (the check runs at startup and then hourly on each backend instance; see the billing runbook): { "state": string, "outcome": string | null, "missing_events": [string], "checked_at": integer | null, "node": string }. state is one of complete (every handled event is subscribed, also after the gateway added missing events itself), missing (missing_events lists the handled event types the endpoint is not subscribed to, sorted), cannot_check (the check could not compare: outcome names why, one of misconfigured, transient, unauthorized, forbidden, unreadable, no_endpoint, ambiguous, disabled, error) or not_checked (outcome skipped: the environment has no Stripe key; or outcome null: this instance has not run the check since it started). outcome is the check's own word (complete, repaired, missing, or one of the reasons above). missing_events is [] unless state is missing. checked_at is the time of that check as a Unix timestamp in seconds (null when not checked). Each backend instance keeps its own last result in memory (no database); node names the instance that answered, so two calls answered by different instances can differ, and a restarted instance answers not_checked until its first check. If the stored result could not be read, stripe_webhook is absent and stripe_webhook_error (string) is the fixed token "read_failed" - the dashboard renders "unknown", never healthy. The field is part of this endpoint only, so only callers with HEALTH_VIEW see it.
Cost-of-goods (COGS)
The COGS endpoints aggregate the per-leg billing ledger (request_log_legs) into cost breakdowns by model, by tenant, by service, or by API key. A single inference request may produce several legs (the primary call, any fallback, plus side services such as guardrails or web search), so these views give a finer-grained cost picture than the request-level Stats summary.
All four endpoints share the same time-window selection:
Query parameters (all COGS endpoints)
| Parameter | Type | Default | Description |
|---|---|---|---|
range |
string | 30d |
Relative window ending now. Format <n><unit> where unit is d (days), h (hours), or w (weeks) — e.g. 24h, 2w, 90d. Ignored when from/to are given. Any other shape (or a count longer than 6 digits) is 400 { "code": "bad_param" } (never the 30-day default). |
from |
integer | — | Explicit window start as a Unix timestamp in seconds. Must be paired with to. |
to |
integer | — | Explicit window end as a Unix timestamp in seconds. Must be paired with from. A from / to that is not a plain integer of digits (an ISO date, abc), one given without the other, or a from that is not before to, is 400 { "code": "bad_param" }. |
💡 Note: When neither
from/tonorrangeis given, the window defaults to the last 30 days plus one day into the future (the extra day captures in-flight legs still being written).
CSV export (format) — cost-allocation endpoints
The four cost-allocation endpoints — /cogs/per-token, /cogs/per-user, /cogs/per-department, and /cogs/per-agent — accept a format parameter for a machine-readable download:
| Parameter | Type | Default | Description |
|---|---|---|---|
format |
string | json |
Response encoding. json (or absent) returns the JSON array documented per endpoint. csv returns the same rows as text/csv; charset=utf-8 with a fixed header row (the response-field order below), served as a file attachment (Content-Disposition: attachment). Any other value — an unknown string, a repeated ?format= (which arrives as a list), or a bare ?format (no value) — is rejected with 400 { "error": "invalid format (json or csv)" } (fail-closed allowlist), validated before the aggregate query runs. |
Notes on the CSV encoding:
- The column order is fixed and equals the endpoint's response-field order; a missing value renders as an empty cell.
- Cells are RFC-4180 quoted, and any value that begins with
=,+,-,@, TAB, or CR is prefixed with a single quote to neutralize spreadsheet formula injection (CWE-1236) — so a user email or agent name such as=SUM(...)cannot execute when the file is opened in a spreadsheet. - No byte-order mark (BOM) is emitted.
- The download filename is a fixed per-endpoint constant (
cogs-per-token.csv/cogs-per-user.csv/cogs-per-department.csv/cogs-per-agent.csv); the server setsAccess-Control-Expose-Headers: Content-Dispositionso a browser SPA fetching cross-origin can read it. - The
bucket,tenant_id, scope, andbillable_onlyrules are identical to the JSON response;formatonly changes the encoding.
GET /cogs/per-model
Cost and token totals grouped by (provider, model, tier, byok), ordered by cost descending. Required permission: COGS_VIEW (View cost breakdowns; held by admin and tenant_admin by default, grantable through a custom role).
Additional query parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
tenant_id |
string | — | Restrict to one tenant. Honoured only for callers with the admin role; every other caller (including tenant_admin) is scoped to their own tenant server-side, and a caller with no tenant is refused 403. |
billable_only |
string | 1 |
Include only billable legs (any value other than 0 / 1 is 400 { "code": "bad_param" }). Set to 0 to also include non-billable legs (e.g. free-tier or internal). |
Response
Array of rows. Returns 503 { "error": "temporarily unavailable; retry later" } on a storage failure (a failed read; retry).
| Field | Type | Description |
|---|---|---|
provider |
string | Provider that served the leg. |
model |
string | Model used for the leg. |
tier |
string | null | Pricing tier recorded for the leg. |
byok |
integer | 1 if the leg ran on the workspace's own provider key (or its own model endpoint), 0 if Myra paid for it (a Myra-hosted model, the platform key pool, a managed model grant). Recorded from the key the call actually used, fallbacks included. Legs recorded before October 2026 always read 0 (the flag was not captured then). |
call_count |
integer | Number of legs in this group. |
in_t |
integer | Sum of input (prompt) tokens. |
out_t |
integer | Sum of output (completion) tokens. |
cache_read_t |
integer | Sum of prompt-cache read tokens. |
cache_write_t |
integer | Sum of prompt-cache creation (write) tokens. |
cost_usd |
number | Total cost in USD for the group. |
partial_count |
integer | Number of legs flagged partial (interrupted / incomplete). |
[
{
"provider": "anthropic",
"model": "claude-opus-4-6",
"tier": null,
"byok": 0,
"call_count": 412,
"in_t": 1840200,
"out_t": 312400,
"cache_read_t": 90400,
"cache_write_t": 12800,
"cost_usd": 9.84,
"partial_count": 2
}
]
GET /cogs/per-tenant
Cost and token totals grouped by tenant, billable legs only, ordered by cost descending. Required permission: COGS_PER_TENANT_VIEW (a platform permission, platform admin only) — lower-privileged callers receive 403 { "error": "forbidden: platform admin only" }.
Response
Array of rows. Returns 503 { "error": "temporarily unavailable; retry later" } on a storage failure (a failed read; retry).
| Field | Type | Description |
|---|---|---|
tenant_id |
string | Tenant UUID. |
call_count |
integer | Number of billable legs for the tenant. |
cost_usd |
number | Total cost in USD. |
in_t |
integer | Sum of input tokens. |
out_t |
integer | Sum of output tokens. |
[
{ "tenant_id": "ten_abc123", "call_count": 1423, "cost_usd": 14.30, "in_t": 2750000, "out_t": 480000 }
]
GET /cogs/per-service
Per-service usage grouped by (provider, service, unit_kind), ordered by call count descending. Counts only legs that carry a non-null service (e.g. web_search, guardrail). Required permission: COGS_VIEW (View cost breakdowns; held by admin and tenant_admin by default, grantable through a custom role).
Additional query parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
tenant_id |
string | — | Restrict to one tenant. Honoured only for callers with the admin role. Every other caller (including tenant_admin) is scoped to their own tenant server-side; a spoofed tenant_id is ignored, and a caller with no tenant is refused 403. A caller can never read another tenant's — or the global, all-tenant — per-service totals. |
Plus the shared range / from / to window parameters above.
Response
Array of rows. Returns 503 { "error": "temporarily unavailable; retry later" } on a storage failure (a failed read; retry).
| Field | Type | Description |
|---|---|---|
provider |
string | Provider that served the service leg. |
service |
string | Service name (e.g. web_search, guardrail). |
unit_kind |
string | null | Unit the service is metered in (e.g. requests, tokens). |
call_count |
integer | Number of legs in this group. |
units_total |
number | Sum of metered units. |
avg_latency_ms |
number | Average leg latency in milliseconds. |
in_t |
integer | Sum of input tokens (where applicable). |
out_t |
integer | Sum of output tokens (where applicable). |
[
{ "provider": "anthropic", "service": "web_search", "unit_kind": "requests", "call_count": 88, "units_total": 88, "avg_latency_ms": 640, "in_t": 0, "out_t": 0 }
]
GET /cogs/per-token
Cost and usage aggregated per API key (token) × period (Zeitraum) × KI-Modell, ordered by cost descending. This is the billing-disclosure view: it answers "what did each API key spend, on which model, in which period." Required permission: COGS_VIEW (View cost breakdowns; held by admin and tenant_admin by default, grantable through a custom role).
Only genuine LLM legs are counted: legs with a NULL model (non-LLM side services such as PII scrubbing or guardrails) are excluded, so the per-model figures are clean. Customer-paid (BYOK) legs are kept on their own rows via the byok dimension and are never summed into platform cost. A single user request that fans out into several same-model legs (e.g. a tool loop) counts as one request.
Additional query parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
bucket |
string | month |
Period granularity for the period column. One of day, week, month, total. Any other value is rejected with 400 { "error": "invalid bucket" } (fail-closed allowlist — the value is never interpolated into SQL). total collapses the whole window into a single period labelled "total". |
tenant_id |
string | — | Restrict to one tenant. Honoured only for callers with the admin role. Every other caller (including tenant_admin) is scoped to their own tenant server-side; a spoofed tenant_id is ignored, and a caller with no tenant is refused 403. A caller can never read another tenant's cost rows. |
token_id |
string | — | Restrict to a single API key. Must be a single scalar value — a repeated param (?token_id=a&token_id=b) is rejected with 400 { "error": "token_id must be a single value" } (fail-closed; it is never bound into SQL). Combined with the mandatory tenant scope: a token_id belonging to another tenant returns an empty result. |
billable_only |
string | 1 |
Include only billable legs (any value other than 0 / 1 is 400 { "code": "bad_param" }). Set to 0 to also include non-billable legs (e.g. free-tier / self-hosted). Non-billable legs still obey the model IS NOT NULL rule. |
Plus the shared range / from / to window parameters above.
Response
Array of rows. Returns 503 { "error": "temporarily unavailable; retry later" } on a storage failure (a failed read; retry), 400 { "error": "invalid bucket" } on a bad bucket.
| Field | Type | Description |
|---|---|---|
token_id |
string | API-key id the legs were attributed to. Empty string ("") means non-API-key traffic — interactive UI / playground sessions that carry no API key. |
token_label |
string | Human label of the API key (from auth_token.label). Empty string if the key has no label or was deleted. |
period |
string | Period bucket. Format depends on bucket: 2026-07-15 (day), 2026-W29 (ISO year-week), 2026-07 (month), or total. Boundaries are always UTC (a day runs from 00:00 UTC, an ISO week starts on Monday 00:00 UTC), whatever time zone the database server uses. Note: the week bucket uses the ISO week-numbering year, so late-December usage can fall in the following calendar year's W01 (e.g. 2025-12-31 → 2026-W01) — while day/month use the calendar year. Example: a leg at 2026-10-31 23:30 UTC (00:30 on 1 November in Berlin) belongs to the month 2026-10. |
provider |
string | Provider that served the model. |
model |
string | Model id (never null — non-model side-service legs are excluded). |
byok |
integer | 1 if the legs used a bring-your-own-key credential (customer-paid), 0 for platform-paid. Kept as a separate dimension so customer and platform cost never merge. |
requests |
integer | Distinct end-user requests in this group (COUNT(DISTINCT request_log_id)), not the leg count. This is a per-row count and is not additive across rows: a single request that fans out across models (a fallback) or across a period boundary is counted once in each row it touches, so summing the requests column overstates the true request total. |
input_tokens |
integer | Sum of input (prompt) tokens. |
output_tokens |
integer | Sum of output (completion) tokens. |
total_tokens |
integer | input_tokens + output_tokens. |
cost_usd |
number | Total cost in USD for the group, rounded to 6 decimals. |
[
{
"token_id": "8f3c2a10-6b4e-4d21-9a77-1e5c0b9d4a02",
"token_label": "prod-key",
"period": "2026-07",
"provider": "anthropic",
"model": "claude-opus-4-7",
"byok": 0,
"requests": 412,
"input_tokens": 1840200,
"output_tokens": 312400,
"total_tokens": 2152600,
"cost_usd": 9.84
}
]
GET /cogs/per-user
Cost and usage aggregated per user × period (Zeitraum) × KI-Modell, ordered by cost descending. This is the per-user cost-allocation view: it answers "which user spent how much, on which model, in which period." Required permission: COGS_PER_USER_VIEW (View per-user cost; held by admin, tenant_admin and finance by default). It is the exact cost twin of /cogs/per-token — same period buckets, same tenant scoping, same row shape — with the grouping key swapped from the API key to the user.
Only genuine LLM legs are counted: legs with a NULL model (non-LLM side services such as PII scrubbing or guardrails) are excluded, so the per-model figures are clean. Customer-paid (BYOK) legs are kept on their own rows via the byok dimension and are never summed into platform cost. A single user request that fans out into several same-model legs (e.g. a tool loop) counts as one request.
Cost allocation is inherently per-identity: this endpoint returns each user's email within the caller's scope. A tenant_admin can only ever see the users of their own tenant (server-side tenant scope, fail-closed); only an admin may scope to another tenant or read across all tenants.
Additional query parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
bucket |
string | month |
Period granularity for the period column. One of day, week, month, total. Any other value is rejected with 400 { "error": "invalid bucket" } (fail-closed allowlist — the value is never interpolated into SQL). total collapses the whole window into a single period labelled "total". |
tenant_id |
string | — | Restrict to one tenant. Honoured only for callers with the admin role. Every other caller (including tenant_admin) is scoped to their own tenant server-side; a spoofed tenant_id is ignored, and a caller with no tenant is refused 403. A caller can never read another tenant's cost rows. |
user_id |
string | — | Restrict to a single user. Must be a single scalar value — a repeated param (?user_id=a&user_id=b) is rejected with 400 { "error": "user_id must be a single value" } (fail-closed; never bound into SQL). Combined with the mandatory tenant scope: a user_id belonging to another tenant returns an empty result. |
billable_only |
string | 1 |
Include only billable legs (any value other than 0 / 1 is 400 { "code": "bad_param" }). Set to 0 to also include non-billable legs (e.g. free-tier / self-hosted). Non-billable legs still obey the model IS NOT NULL rule. |
Plus the shared range / from / to window parameters above.
Response
Array of rows. Returns 503 { "error": "temporarily unavailable; retry later" } on a storage failure (a failed read; retry), 400 { "error": "invalid bucket" } on a bad bucket.
| Field | Type | Description |
|---|---|---|
user_id |
string | User id the legs were attributed to. Empty string ("") means traffic with no attributed user — e.g. API-key requests that carry no user context. |
user_email |
string | Email of the user (from user.email). Empty string if the user has no email or was deleted. |
department_id |
string | Department the leg was booked to, stamped on the leg when it was written (see /cogs/per-department). Empty string for legs written before the department was stamped, for users without a department, and for API-key traffic. |
department |
string | Current name of that department. Empty string if the department has since been deleted or the leg has none. |
cost_center |
string | The user's current SCIM costCenter (not a snapshot — a later change re-labels past spend). Empty string if none is set or the user was deleted. |
period |
string | Period bucket. Format depends on bucket: 2026-07-15 (day), 2026-W29 (ISO year-week), 2026-07 (month), or total. Boundaries are always UTC (a day runs from 00:00 UTC, an ISO week starts on Monday 00:00 UTC), whatever time zone the database server uses. Note: the week bucket uses the ISO week-numbering year, so late-December usage can fall in the following calendar year's W01 (e.g. 2025-12-31 → 2026-W01) — while day/month use the calendar year. |
provider |
string | Provider that served the model. |
model |
string | Model id (never null — non-model side-service legs are excluded). |
byok |
integer | 1 if the legs used a bring-your-own-key credential (customer-paid), 0 for platform-paid. Kept as a separate dimension so customer and platform cost never merge. |
requests |
integer | Distinct end-user requests in this group (COUNT(DISTINCT request_log_id)), not the leg count. This is a per-row count and is not additive across rows: a single request that fans out across models (a fallback) or across a period boundary is counted once in each row it touches, so summing the requests column overstates the true request total. |
input_tokens |
integer | Sum of input (prompt) tokens. |
output_tokens |
integer | Sum of output (completion) tokens. |
total_tokens |
integer | input_tokens + output_tokens. |
cost_usd |
number | Total cost in USD for the group, rounded to 6 decimals. |
[
{
"user_id": "3a1f8c22-9d4e-4b70-8c11-2f6a0e7b5d13",
"user_email": "alex@example.com",
"department_id": "7c0e5d9a-31b2-4f68-a2c4-90d1e6b3f845",
"department": "Engineering",
"cost_center": "CC-4711",
"period": "2026-07",
"provider": "anthropic",
"model": "claude-opus-4-7",
"byok": 0,
"requests": 128,
"input_tokens": 540200,
"output_tokens": 96400,
"total_tokens": 636600,
"cost_usd": 3.11
}
]
GET /cogs/per-department
Cost and usage aggregated per department × period × provider × model × BYOK, ordered by cost descending — the chargeback view: "which department spent how much, on which model, in which period." Required permission: COGS_PER_USER_VIEW (held by finance, tenant_admin and admin by default; any other role gets 403). Tenant scoping, range / from / to, bucket, billable_only, tenant_id (platform admin only) and format=csv behave exactly as on /cogs/per-user.
| Parameter | Type | Default | Description |
|---|---|---|---|
department_id |
string | — | Restrict to a single department. Must be a single scalar value — a repeated param (?department_id=a&department_id=b) is rejected with 400 { "error": "department_id must be a single value" } (fail-closed; never bound into SQL). An empty value (?department_id=) means no filter — it does not select the unassigned bucket; read the department_id = "" row of the unfiltered result for that. A department of another tenant returns an empty result. |
user_id is not a parameter of this endpoint and is ignored (the result is never narrowed to one user); to see one user's spend per department use /cogs/per-user?user_id=…, whose rows carry department_id.
curl "https://<your-gateway-host>/admin/v1/cogs/per-department?range=30d&bucket=month"
curl -OJ "https://<your-gateway-host>/admin/v1/cogs/per-department?range=30d&format=csv"
How spend is attributed.
- The department is stamped on each billing leg at write time from the user's department at that moment. Moving a user to another department therefore does not re-book past spend: history stays with the department that was current when the request ran, new requests go to the new one.
- There is no backfill: legs written before this feature carry no department and appear in the row with
department_id = ""(the unassigned bucket), as do users without a department. Spend is never dropped. - A deleted department keeps its spend under its
department_id, with an emptydepartmentname; the name is never resurrected or guessed. - Agent runs are booked to the department of the agent's owner.
- If the department cannot be read at write time the leg is written without one (the request is never blocked by chargeback bookkeeping).
| Field | Type | Description |
|---|---|---|
department_id |
string | Department id the legs were booked to; "" = unassigned. |
department |
string | Current department name; "" if unassigned or deleted. |
period |
string | Period bucket, as on /cogs/per-user. |
provider |
string | Provider that served the model. |
model |
string | Model id. |
byok |
integer | 1 for customer-paid (bring-your-own-key) legs, 0 for platform-paid; never merged. |
users |
integer | Distinct users in the group (per-row; not additive across rows). |
requests |
integer | Distinct end-user requests (per-row; not additive across rows). |
input_tokens |
integer | Sum of input tokens. |
output_tokens |
integer | Sum of output tokens. |
total_tokens |
integer | input_tokens + output_tokens. |
cost_usd |
number | Total cost in USD, rounded to 6 decimals. |
The CSV columns are exactly: department_id,department,period,provider,model,byok,users,requests,input_tokens,output_tokens,total_tokens,cost_usd; the filename is cogs-per-department.csv.
Cost centre. To charge by cost centre use /cogs/per-user, which carries each user's department_id, department and cost_center. The cost centre comes from the SCIM enterprise costCenter attribute (SCIM) and is the user's current value at query time, not stamped per leg.
GET /cogs/per-agent
Cost and usage aggregated per agent × period (Zeitraum) × KI-Modell, ordered by cost descending. This is the per-agent cost-allocation view: it answers "which agent spent how much, on which model, in which period." Required permission: COGS_VIEW (View cost breakdowns; held by admin and tenant_admin by default, grantable through a custom role). It is the agent-dimension twin of /cogs/per-user — same period buckets, same tenant scoping, same row shape — with the grouping key swapped from the user to the agent.
Only agent-invoked traffic is included (requests that carry no agent are excluded). Agents are grouped by their clone-lineage root, so a shared agent and all of its clones roll up under one row group — matching the per-agent stats in /stats/analytics. Only genuine LLM legs are counted: legs with a NULL model (non-LLM side services such as PII scrubbing or guardrails) are excluded, so the per-model figures are clean. Customer-paid (BYOK) legs are kept on their own rows via the byok dimension and are never summed into platform cost. A single agent request that fans out into several same-model legs (e.g. a tool loop) counts as one request.
Cost and token figures are tenant-bounded (server-side tenant scope, fail-closed): a tenant_admin can only ever see their own tenant's agent spend; only an admin may scope to another tenant or read across all tenants.
Additional query parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
bucket |
string | month |
Period granularity for the period column. One of day, week, month, total. Any other value is rejected with 400 { "error": "invalid bucket" } (fail-closed allowlist — the value is never interpolated into SQL). total collapses the whole window into a single period labelled "total". |
tenant_id |
string | — | Restrict to one tenant. Honoured only for callers with the admin role. Every other caller (including tenant_admin) is scoped to their own tenant server-side; a spoofed tenant_id is ignored, and a caller with no tenant is refused 403. A caller can never read another tenant's cost rows. |
agent_id |
string | — | Restrict to a single agent, matched against the clone-lineage root id. Must be a single scalar value — a repeated param (?agent_id=a&agent_id=b) is rejected with 400 { "error": "agent_id must be a single value" } (fail-closed; never bound into SQL). Combined with the mandatory tenant scope: an agent_id whose traffic belongs to another tenant returns an empty result. |
billable_only |
string | 1 |
Include only billable legs (any value other than 0 / 1 is 400 { "code": "bad_param" }). Set to 0 to also include non-billable legs (e.g. free-tier / self-hosted). Non-billable legs still obey the model IS NOT NULL rule. |
Plus the shared range / from / to window parameters above.
Response
Array of rows. Returns 503 { "error": "temporarily unavailable; retry later" } on a storage failure (a failed read; retry), 400 { "error": "invalid bucket" } on a bad bucket.
| Field | Type | Description |
|---|---|---|
agent_id |
string | Clone-lineage root id the legs were attributed to (the stamped root, falling back to the agent's own id for pre-lineage rows). |
agent |
string | Display name of the root agent (agent.name, falling back to its slug, then the raw root id if the agent was deleted). For a cross-tenant cloned agent the label may resolve to the source agent's name; the cost and token figures always count only the caller's own tenant's legs. |
period |
string | Period bucket. Format depends on bucket: 2026-07-15 (day), 2026-W29 (ISO year-week), 2026-07 (month), or total. Boundaries are always UTC (a day runs from 00:00 UTC, an ISO week starts on Monday 00:00 UTC), whatever time zone the database server uses. Note: the week bucket uses the ISO week-numbering year, so late-December usage can fall in the following calendar year's W01 (e.g. 2025-12-31 → 2026-W01) — while day/month use the calendar year. |
provider |
string | Provider that served the model. |
model |
string | Model id (never null — non-model side-service legs are excluded). |
byok |
integer | 1 if the legs used a bring-your-own-key credential (customer-paid), 0 for platform-paid. Kept as a separate dimension so customer and platform cost never merge. |
requests |
integer | Distinct end-user requests in this group (COUNT(DISTINCT request_log_id)), not the leg count. This is a per-row count and is not additive across rows: a single request that fans out across models (a fallback) or across a period boundary is counted once in each row it touches, so summing the requests column overstates the true request total. |
input_tokens |
integer | Sum of input (prompt) tokens. |
output_tokens |
integer | Sum of output (completion) tokens. |
total_tokens |
integer | input_tokens + output_tokens. |
cost_usd |
number | Total cost in USD for the group, rounded to 6 decimals. |
[
{
"agent_id": "ddc230d8-78ef-11f1-a3ae-6c92cf1260f0",
"agent": "Support Triage",
"period": "2026-07",
"provider": "anthropic",
"model": "claude-opus-4-7",
"byok": 0,
"requests": 64,
"input_tokens": 210400,
"output_tokens": 38800,
"total_tokens": 249200,
"cost_usd": 1.42
}
]
Example curl requests
⭐ Example: The following examples show common query patterns for the timeseries endpoint.
Today's requests by hour (last 24 hours)
Yesterday's requests by hour
# Set 'until' to the end of yesterday (start of today in Unix seconds)
YESTERDAY_END=$(date -d "today 00:00:00" +%s)
curl "https://<your-gateway-host>/admin/v1/stats/timeseries?bucket=1h&n=24&until=${YESTERDAY_END}"
Last 7 days by day
Last hour in 5-minute buckets
Last 30 days in 6-hour buckets
GET /stats/reactivation
The platform-wide roll-up of the member-reactivation e-mails, shown as the Member reactivation card on the platform dashboard.
Authorization: platform admin only (cross-tenant data; 403 otherwise).
Response: mails_sent_7d, mails_sent_30d, reactivated_7d (members who became active within
7 days of a mail sent in the last 30 days), opt_outs_total, opt_outs_30d, and top_tenants —
the ten most-mailed workspaces of the last 30 days as [{ tenant_id, slug, mails_sent_30d }]
(an empty array when nothing was sent). Counts come from the send log only — no per-member
classification runs fleet-wide; the per-tenant states live on
GET /tenants/{id}/reactivation-metrics. A database
fault is 503.
GET /stats/growth
Growth statistics of the self-serve funnel across all tenants — signups, activation, paid subscriptions and the signup source / region — bucketed by local day or ISO week. Used by the operators and the daily morning report.
# browser session (platform admin)
curl -b aig_admin=… "https://<your-gateway-host>/admin/v1/stats/growth?from=2026-10-01&to=2026-10-14&group_by=week&tz_offset=-120"
# machine access with a scoped API token
curl -H "Authorization: Bearer myra_…" "https://<your-gateway-host>/admin/v1/stats/growth?group_by=day"
Authorization
One permission, GROWTH_STATS_VIEW (platform class — held by platform admins, never grantable to
a tenant custom role). Two ways to present it:
| Mode | When | Rule |
|---|---|---|
| Session | no Authorization header |
the normal admin session cookie; the user must hold GROWTH_STATS_VIEW (401 without a session, 403 without the permission) |
| Bearer token | an Authorization header is present (in any shape) |
the header is the only credential looked at — a session cookie sent alongside is ignored, and a malformed header is 401, never a fallback to the cookie. The token must carry the growth-statistics scopes and its owner must hold GROWTH_STATS_VIEW |
The bearer path accepts a myra_ API token on this route only; any other admin route keeps the
session-only gate.
include_domains=1 additionally needs (bearer mode) the token scope growth_stats_domains; in
session mode the permission suffices. Deviation from the ticket's two-permission wording: every
platform admin holds every platform permission, so a second permission would separate nothing — the
domain list is separated for machine access by the token scope instead.
Every include_domains=1 read writes an audit event (growth_stats.domains_read: actor user id,
auth mode, the token id in bearer mode — never the token —, the range and the number of domains)
before the response is sent; if it cannot be written the request fails with the sanitised 500 (the
row may still have been stored) and no domains leave. Bearer refusals are logged with the token id (never the secret); once the token's owner is
resolved, every further 403 is recorded as an access.denied audit row attributed to that owner (a
token without an owner, or whose owner no longer exists, is refused before that).
Query parameters
| Parameter | Accepted | Default | Rejected (400) |
|---|---|---|---|
from |
YYYY-MM-DD, a real calendar date between 2000-01-01 and 2100-12-31 — a local day at tz_offset |
to − 29 days |
anything else (2026-02-30, 2026-1-01, 2026/10/01, a time part, empty) |
to |
same, inclusive | today (local); a lone future from → from |
same; to before from; a range longer than 366 days |
group_by |
day or week |
day |
any other value (month, DAY, empty) |
include_domains |
0 or 1 |
0 |
any other value (true, yes, empty) |
tz_offset |
an integer number of minutes, -840…720, written as an optional - and digits |
0 (UTC) |
a fraction, +60, padding / whitespace, 1e2, out of range |
Every parameter must appear at most once with a value — a repeated (?from=…&from=…) or bare
(?from) parameter is 400, and so is a request with more than 100 query arguments (the server
reads at most 100, so a repeat beyond them could not be detected). Unknown parameters are ignored. Parameters are validated only after
authentication (an unauthenticated caller gets 401, not 400).
tz_offset uses the JavaScript getTimezoneOffset() convention: UTC minus local — Berlin is
-120 in summer and -60 in winter. One fixed offset applies to the whole range, so across a
daylight-saving change the buckets are shifted by one hour on one side of it; pass the offset of the
period you care about.
Response
{
"from": "2026-10-01", "to": "2026-10-14", "group_by": "week", "tz_offset": -120,
"paid": { "active_now": 12 },
"buckets": [
{
"start": "2026-10-01", "end": "2026-10-04",
"signups": {
"total": 9,
"by_domain_class": { "business": 4, "freemail": 3, "myra": 1, "test": 1 },
"by_region": { "dach": 6, "eu_eea": 1, "south_asia": 1, "other": 0, "unknown": 1 }
},
"activated": { "total": 3, "pending": 2, "by_domain_class": { "business": 2, "freemail": 1, "myra": 0, "test": 0 } },
"paid": { "new": 1 },
"source": {
"utm_source": [ { "value": "google", "count": 5 }, { "value": "(none)", "count": 4 } ],
"utm_medium": [ { "value": "cpc", "count": 5 }, { "value": "(none)", "count": 4 } ],
"click_id_type": [ { "value": "gclid", "count": 5 }, { "value": "(none)", "count": 4 } ]
},
"domains": [ "kanzlei-beispiel.de" ]
}
]
}
- Buckets cover the whole range, every one present and zero-filled (all four domain classes and
all five regions are always there; empty lists are
[]). Withgroup_by=weekthe buckets are ISO weeks (Monday first); the first and the last are clipped to the range and labelled with their own first day.start/endare the bucket's first and last local day (inclusive). signups— tenants created by a self-serve sign-up (e-mail trial, Google / Microsoft sign-in incl. the native app, paid self-checkout) in the bucket, bytenant.created_at. A tenant created by an administrator is never a signup. Tenants of the test harness (the00000000-e2e…ids and the synthetice2e-synthetictenant) are excluded everywhere. A signup counts even if the tenant was deleted since (soft-deleted); a tenant that was purged (hard-deleted) is gone from history.by_domain_class— the founder's e-mail domain (the tenant's trial registration domain, else its earliest user's):myra(Myra's own domains),test(the harness's test domains, the reserved.test/.local/.invalid/.examplenames,example.*, and a domain that cannot be determined),freemail(consumer mailbox providers such as gmail.com, web.de, gmx.de, outlook.com), elsebusiness.by_region— from the signup country (see Signup campaign source):dach(DE, AT, CH),eu_eea(the other EU member states plus IS, LI, NO),south_asia(PK, IN, BD, NP, LK),other,unknown(no country recorded — every signup before the country capture went live, and every signup where the CDN header is not trusted).activated— signups where any user of the tenant sent at least 5 chat messages within 14 days of the tenant's creation (the activation KPI). Counted are the user turns of chat conversations, including messages sent through a chat bridge (Teams, Slack, Mattermost); requests through the inference API are not chat messages and do not count. Scheduled prompts also write user turns and count — they exist only for paid self-checkout signups (the trial plan allows no scheduled tasks). Copied history is not counted again: neither a forked conversation's copied messages nor the earlier messages imported when someone continues a shared conversation (imports made before this version were not marked and still count). A conversation the user deletes later still counts (activation is a past event).pending= signups not (yet) activated whose 14-day window is still open, sototal + pending ≤ signups.total. Message history shrinks only when messages are physically removed: conversation retention and the messages of a hard-deleted user.paid.new— subscriptions created in the bucket on self-signup tenants (paid self-checkouts and conversions of self-signup trials; the same tenantssignupscounts, so the ratio is meaningful), not disputed, non-test — deleted tenants included. A subscription of a tenant created by Myra staff is not counted here (it is inactive_now).paid.active_now— a snapshot at query time, independent of the range: subscriptions in the active state on live non-test tenants. Subscriptions in the payment grace period are not counted.source— counts by the tenant's signup campaign source (utm_source,utm_medium, the click ID type): the 20 most frequent values (count descending, then value), the rest merged into(other); a signup without one counts as(none), a value containing@(it could be an e-mail address) as(redacted). These values are free text from campaign URLs — a consumer must escape them before putting them into HTML, a spreadsheet or a shell.domains(only withinclude_domains=1) — the distinct business domains of the bucket's signups, sorted; a domain is listed only while its tenant is not deleted and still has a live user (an erased solo founder's domain never appears). No e-mail address, name or IP address is part of the response.
Which tenants count as self-serve signups. The marker tenant.self_signup is set when a self-serve
sign-up provisions the tenant and never changes. Tenants from before the marker were back-filled from
provisioning traces only (an AVV acceptance recorded from a signup, a trial-start record with an IP
address); not found that way, and therefore not counted: paid self-checkout signups from before the
AVV acceptance was recorded, and trials whose trial record was reset or purged. Signups provisioned
during the rollout of this version by a server still running the previous version are not marked
at first; the same back-fill runs a second time with the following release.
Errors
| Status | When |
|---|---|
400 |
a malformed or repeated parameter (see above) — { "error": "<which parameter and why>" }; more than 100 query arguments — { "error": "too many query parameters" } |
401 |
no session and no Authorization header; a malformed / repeated / empty Authorization header; an unknown, revoked or expired token |
403 |
the session user lacks GROWTH_STATS_VIEW; a token without the growth-statistics scopes (incl. legacy unrestricted tokens and tokens that also carry other capabilities), without an owner, bound to an agent, with an unreadable scope list, whose owner is disabled / deleted / lacks the permission; include_domains=1 without growth_stats_domains |
503 |
a database fault on a read (token / owner lookup, the statistics query) — retry |
500 |
the domains audit row could not be written (it may still have been stored) — { "error": "internal error", "request_id": "…" }; no domains are sent |
See also
- Finance API — the
financerole and its per-user cost access (GET /cogs/per-user) - Logs API
- Models & Pricing API
- Error Codes
- Budget & Quota Enforcement