Model usage was recorded per call and never read, so an org could not see what it spent. Add the read side: - model_usage carries identity_id. Task calls take it from the task row, chat and curator calls from the calling principal carried in the usage record, so an outbox replay keeps its attribution. Existing task rows are backfilled from tasks. - StatsService.UsageTotals sums the caller org's rows by UTC day, source, provider, model and identity. The org comes from the principal, with no org parameter, so cross-org reads do not exist. - GET /api/usage prices tokens at the catalog's list rate, netting cache hits, and reports calls to unpriced models as tokens only. The published catalog view now carries each model's cost. - A new org Usage page behind a read_usage grant: admin and owner only, with a 7, 30 or 90 day range, totals, the daily series, and model, source and identity breakdowns. The org shell keeps it on the caller's own org.
34 lines
1.5 KiB
SQL
34 lines
1.5 KiB
SQL
-- name: InsertModelUsage :exec
|
|
-- A task's usage belongs to the task's org and identity, whatever the caller
|
|
-- says; every other call is billed to the caller's org and identity.
|
|
INSERT INTO model_usage (
|
|
org_id, source, task_id, attempt, workflow, step, alias, provider, model,
|
|
identity_id, input_tokens, output_tokens, cached_tokens, at
|
|
) VALUES (
|
|
COALESCE((SELECT t.org_id FROM tasks t WHERE t.id = sqlc.arg(task_id) AND sqlc.arg(task_id) <> 0), sqlc.arg(org_id)::text),
|
|
sqlc.arg(source), sqlc.arg(task_id), sqlc.arg(attempt), sqlc.arg(workflow), sqlc.arg(step), sqlc.arg(alias),
|
|
sqlc.arg(provider), sqlc.arg(model),
|
|
COALESCE((SELECT t.identity FROM tasks t WHERE t.id = sqlc.arg(task_id) AND sqlc.arg(task_id) <> 0), sqlc.arg(identity_id)::text),
|
|
sqlc.arg(input_tokens), sqlc.arg(output_tokens), sqlc.arg(cached_tokens), sqlc.arg(at)
|
|
);
|
|
|
|
-- name: ListModelUsageTotals :many
|
|
-- One row per day, source, provider, model and identity the org used.
|
|
-- cached_tokens is a subset of input_tokens; the reader prices them.
|
|
SELECT
|
|
to_char(at AT TIME ZONE 'UTC', 'YYYY-MM-DD') AS day,
|
|
source,
|
|
provider,
|
|
model,
|
|
identity_id,
|
|
count(*)::bigint AS calls,
|
|
COALESCE(sum(input_tokens), 0)::bigint AS input_tokens,
|
|
COALESCE(sum(output_tokens), 0)::bigint AS output_tokens,
|
|
COALESCE(sum(cached_tokens), 0)::bigint AS cached_tokens
|
|
FROM model_usage
|
|
WHERE org_id = sqlc.arg(org_id)
|
|
AND at >= sqlc.arg(from_at)::timestamptz
|
|
AND at < sqlc.arg(to_at)::timestamptz
|
|
GROUP BY 1, 2, 3, 4, 5
|
|
ORDER BY 1;
|