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:
@@ -1,6 +1,7 @@
|
||||
import userAuth from "@/src/functions/backend/auth/user-auth";
|
||||
import grabSpeakableMessage from "@/src/functions/backend/db/bots/grab-speakable-message";
|
||||
import speakText from "@/src/harness/audio/speak-text";
|
||||
import withUsageScope from "@/src/harness/usage/with-usage-scope";
|
||||
import HarnessError from "@/src/harness/harness-error";
|
||||
import { SpeakBotMessageRequestSchema } from "@/src/schemas/bot-schema";
|
||||
import AppError from "@/src/utils/app-error";
|
||||
@@ -47,11 +48,26 @@ export const handler: BunextAPIRouteHandler<APIResponseObject> = async ({ req, q
|
||||
throw new AppError(`There's nothing to read in that message.`);
|
||||
}
|
||||
|
||||
const audio = await speakText({
|
||||
text,
|
||||
bot_id: conversation.bot.id,
|
||||
workspace_id: conversation.workspace_id,
|
||||
signal: req.signal,
|
||||
/**
|
||||
* Reading a message aloud is billed like any other model call, so
|
||||
* it is recorded against the message it reads.
|
||||
*/
|
||||
const audio = await withUsageScope({
|
||||
scope: {
|
||||
user_id: user.id,
|
||||
bot_id: conversation.bot.id,
|
||||
workspace_id: conversation.workspace_id,
|
||||
session_id: message.session_id || null,
|
||||
job_id: null,
|
||||
message_id: message.id || null,
|
||||
},
|
||||
task: () =>
|
||||
speakText({
|
||||
text,
|
||||
bot_id: conversation.bot.id,
|
||||
workspace_id: conversation.workspace_id,
|
||||
signal: req.signal,
|
||||
}),
|
||||
});
|
||||
|
||||
return new Response(audio.stream, {
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import userAuth from "@/src/functions/backend/auth/user-auth";
|
||||
import grabActiveBotSession from "@/src/functions/backend/db/bot-sessions/grab-active-bot-session";
|
||||
import grabUserConversation from "@/src/functions/backend/db/bot-sessions/grab-user-conversation";
|
||||
import transcribeAudio from "@/src/harness/audio/transcribe-audio";
|
||||
import withUsageScope from "@/src/harness/usage/with-usage-scope";
|
||||
import { TranscribeVoiceRequestSchema } from "@/src/schemas/bot-schema";
|
||||
import HarnessError from "@/src/harness/harness-error";
|
||||
import AppError from "@/src/utils/app-error";
|
||||
@@ -60,12 +62,33 @@ export const handler: BunextAPIRouteHandler<
|
||||
throw new AppError(`Nothing was recorded.`);
|
||||
}
|
||||
|
||||
const text = await transcribeAudio({
|
||||
audio: { data: new Uint8Array(buffer), format: AudioFormats[type] || type },
|
||||
/**
|
||||
* The dictation is work done for this user in this conversation,
|
||||
* even though no queued job or message is behind it.
|
||||
*/
|
||||
const session = await grabActiveBotSession({
|
||||
user_id: user.id,
|
||||
bot_id: conversation.bot.id,
|
||||
workspace_id: conversation.workspace_id,
|
||||
});
|
||||
|
||||
const text = await withUsageScope({
|
||||
scope: {
|
||||
user_id: user.id,
|
||||
bot_id: conversation.bot.id,
|
||||
workspace_id: conversation.workspace_id,
|
||||
session_id: session?.id || null,
|
||||
job_id: null,
|
||||
message_id: null,
|
||||
},
|
||||
task: () =>
|
||||
transcribeAudio({
|
||||
audio: { data: new Uint8Array(buffer), format: AudioFormats[type] || type },
|
||||
bot_id: conversation.bot.id,
|
||||
workspace_id: conversation.workspace_id,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!text) {
|
||||
throw new AppError(`No speech was heard. Try again a little closer to the mic.`);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import userAuth from "@/src/functions/backend/auth/user-auth";
|
||||
import grabUsageOverview from "@/src/functions/backend/db/usage/grab-usage-overview";
|
||||
import { UsageRequestSchema } from "@/src/schemas/usage-schema";
|
||||
import type { UsageOverview } from "@/src/types";
|
||||
import canManageCrew from "@/src/utils/rbac/can-manage-crew";
|
||||
import parseWithSchema from "@/src/utils/parse-with-schema";
|
||||
import safeErrorMessage from "@/src/utils/safe-error-message";
|
||||
import type { APIResponseObject, BunextAPIRouteHandler } from "@moduletrace/bunext/types";
|
||||
|
||||
/**
|
||||
* What the install's models spent over a period: in total, per day, per
|
||||
* harness and per model. Super admins and admins only, since it is the
|
||||
* whole install's work rather than one user's conversation.
|
||||
*/
|
||||
export const handler: BunextAPIRouteHandler<APIResponseObject<UsageOverview>> = async ({ req, query }) => {
|
||||
try {
|
||||
if (req.method != "GET") {
|
||||
return { success: false, msg: `Method not allowed` };
|
||||
}
|
||||
|
||||
const { user, user_types } = await userAuth({ req });
|
||||
|
||||
if (!user?.logged_in_status || !user.id) {
|
||||
return { success: false, msg: `Unauthorized`, logoutUser: true };
|
||||
}
|
||||
|
||||
if (!canManageCrew({ user_types })) {
|
||||
return { success: false, msg: `You don't manage the crew.` };
|
||||
}
|
||||
|
||||
const request = parseWithSchema({ schema: UsageRequestSchema, data: query });
|
||||
|
||||
return {
|
||||
success: true,
|
||||
singleRes: await grabUsageOverview({ days: request.days }),
|
||||
};
|
||||
} catch (error: unknown) {
|
||||
return { success: false, msg: safeErrorMessage({ error }) };
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user