Record what every model call spends, and show it
Nothing anywhere recorded what a model call cost: the harness used a provider's usage numbers only to decide whether a turn had finished, then dropped them. So a reply could not say what it took to make, one model could not be compared with another on price, and there was no way to ask what a day, a week or a month of the crew's work came to. - `token_usages` records one row per call: user, bot, workspace, session, job and message, the harness, the provider and model that actually answered, the prompt and completion counts, and the cost when the provider reports one. - `harness-usage-scope.ts` carries those ids in an AsyncLocalStorage scope that `run-bot-job.ts` enters once, so a run's turns, its session summary, its transcriptions, images and embeddings are all attributed without threading ids through every harness function. Nested runs merge rather than replace, and a null genuinely clears a field (a bot's own chat has no workspace). - Work with no run behind it is charged to its owner instead: `run-with-fallback-scope.ts` reaches the workspace's creator else the bot's, and deliberately does not override a real run, so an ingest a bot asked for is not misattributed to the bot's owner. - All six harnesses record through `withCandidates`'s `on_success`. Recording never throws: a model that answered must not lose its answer to a failed insert. - A job's calls land before its message exists, so `complete-bot-job.ts` back-fills `message_id` once the message is inserted. - The message's actions row shows what it cost, beside the timestamp and the play button, with the breakdown in its title. - `/admin/usage` totals the install's spending for 7, 30 or 90 days: the total against the previous period, a day-by-day chart, a split per kind of call, and a table per model with the price per thousand tokens worked out from cost and tokens, which is what makes two models comparable. Crew managers only, since it is the whole install's work rather than one user's conversation. It sits with Routines and Activity in the user popover rather than under Settings, because it is a record of what happened, not something to configure. Days are grouped in local time (`date(created_at / 1000, 'unixepoch', 'localtime')`), matching the local midnights the window builds and the `YYYY-MM-DD` buckets it looks up. Grouping by the bare UTC day put a late evening's calls under a name no bucket carried, so they vanished and the chart's total silently disagreed with the totals card; a test pins it. `canSeeRailItem` now decides who sees a popover or rail entry. The two each filtered with their own inline rule and only one understood `can_view`, so a gated page could be offered in the popover to everyone.
This commit is contained in:
@@ -0,0 +1,92 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import type {
|
||||
BUN_SQLITE_COBBLE_TOKEN_USAGES,
|
||||
BunSQLiteTables,
|
||||
} from "@/db/types/db";
|
||||
import { logError } from "@/src/functions/backend/logger";
|
||||
import { grabHarnessUsageScope } from "./harness-usage-scope";
|
||||
import type { HarnessUsageCall, HarnessUsageScope } from "./types";
|
||||
|
||||
type Params = {
|
||||
/**
|
||||
* The scope the call ran under. Left out, the ambient one
|
||||
* (`grabHarnessUsageScope`) is used, which is what every entry point
|
||||
* does: the ids came in through `runWithHarnessUsageScope`.
|
||||
*/
|
||||
scope?: HarnessUsageScope;
|
||||
/**
|
||||
* Which harness and which model answered, with what the provider
|
||||
* reported it cost.
|
||||
*/
|
||||
call: HarnessUsageCall;
|
||||
};
|
||||
|
||||
/**
|
||||
* Writes one model call into `token_usages`: the tokens it spent, on which
|
||||
* model and provider, for whom, and which message or job it was for. This
|
||||
* is what a message's token line, a bot's and a provider's totals and the
|
||||
* usage page all read.
|
||||
*
|
||||
* Never throws: a model that answered must not have its answer lost
|
||||
* because the bookkeeping failed. A call without an owner (no scope, no
|
||||
* user) is not written at all, since nothing could show it.
|
||||
*/
|
||||
export default async function recordHarnessUsage({ scope, call }: Params) {
|
||||
const resolved = scope || grabHarnessUsageScope();
|
||||
const user_id = Number(resolved?.user_id) || null;
|
||||
|
||||
if (!user_id) return;
|
||||
|
||||
const row: BUN_SQLITE_COBBLE_TOKEN_USAGES = {
|
||||
user_id,
|
||||
bot_id: numberOrNull(resolved?.bot_id),
|
||||
workspace_id: numberOrNull(resolved?.workspace_id),
|
||||
session_id: numberOrNull(resolved?.session_id),
|
||||
message_id: numberOrNull(resolved?.message_id),
|
||||
job_id: numberOrNull(resolved?.job_id),
|
||||
harness: call.harness,
|
||||
provider_id: call.provider_id,
|
||||
provider_name: call.provider_name,
|
||||
model_id: call.model_id,
|
||||
model_slug: call.model_slug,
|
||||
prompt_tokens: Math.max(0, Math.round(call.prompt_tokens || 0)),
|
||||
completion_tokens: Math.max(0, Math.round(call.completion_tokens || 0)),
|
||||
cost: typeof call.cost == "number" && Number.isFinite(call.cost) ? call.cost : undefined,
|
||||
};
|
||||
|
||||
try {
|
||||
const res = await BunSQLite.insert<
|
||||
BUN_SQLITE_COBBLE_TOKEN_USAGES,
|
||||
(typeof BunSQLiteTables)[number]
|
||||
>({
|
||||
table: "token_usages",
|
||||
data: [row],
|
||||
});
|
||||
|
||||
if (!res.success) {
|
||||
throw new Error(res.msg || `The usage wasn't saved.`);
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
await logError({
|
||||
title: "Model usage not recorded",
|
||||
error,
|
||||
metadata: {
|
||||
harness: call.harness,
|
||||
model_slug: call.model_slug || null,
|
||||
provider_name: call.provider_name || null,
|
||||
user_id,
|
||||
},
|
||||
}).catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* SQLite stores NULL for what isn't given; `Number(undefined)` is NaN,
|
||||
* which bun-sqlite would refuse. An absent id is `undefined`, not `null`:
|
||||
* bun-sqlite's row types spell "no value" that way.
|
||||
*/
|
||||
function numberOrNull(value: unknown): number | undefined {
|
||||
const number = Number(value);
|
||||
|
||||
return Number.isFinite(number) && number > 0 ? number : undefined;
|
||||
}
|
||||
Reference in New Issue
Block a user