Download src/server/usage/record.ts from bhyve/auto-lms: direct link, hf CLI and curl.
- Browser
- Download file 1.67 kB
-
https://huggingface.co/spaces/bhyve/auto-lms/resolve/main/src/server/usage/record.ts
- Command line
-
hf download hf://spaces/bhyve/auto-lms/src/server/usage/record.ts
-
curl -L -o record.ts https://huggingface.co/spaces/bhyve/auto-lms/resolve/main/src/server/usage/record.ts
1.67 kB
| import { db } from '../db/client'; | |
| import { llmUsage } from '../db/schema'; | |
| import { estimateCostUsd } from './pricing'; | |
| // Where a usage row is attributed. Passed through every LLM/TTS call so token | |
| // accounting is centralised, never scattered across call sites. | |
| export interface UsageContext { | |
| jobId?: string | null; | |
| stepId?: string | null; | |
| courseId?: string | null; | |
| sourceInputId?: string | null; | |
| operation: string; | |
| model: string; | |
| provider?: string; | |
| } | |
| // Subset of Gemini's usageMetadata we care about. | |
| export interface RawUsage { | |
| promptTokenCount?: number; | |
| candidatesTokenCount?: number; | |
| totalTokenCount?: number; | |
| thoughtsTokenCount?: number; | |
| } | |
| export async function recordUsage(ctx: UsageContext, usage: RawUsage | undefined): Promise<void> { | |
| const prompt = usage?.promptTokenCount ?? 0; | |
| const candidates = usage?.candidatesTokenCount ?? 0; | |
| const thoughts = usage?.thoughtsTokenCount ?? 0; | |
| let total = usage?.totalTokenCount ?? 0; | |
| // Output billing covers candidate tokens AND thinking tokens. Deriving from | |
| // total captures both even when the breakdown fields are absent. | |
| const completion = total > prompt ? total - prompt : candidates + thoughts; | |
| if (total === 0) total = prompt + completion; | |
| await db.insert(llmUsage).values({ | |
| jobId: ctx.jobId ?? null, | |
| stepId: ctx.stepId ?? null, | |
| courseId: ctx.courseId ?? null, | |
| sourceInputId: ctx.sourceInputId ?? null, | |
| provider: ctx.provider ?? 'google', | |
| model: ctx.model, | |
| operation: ctx.operation, | |
| promptTokens: prompt, | |
| completionTokens: completion, | |
| totalTokens: total, | |
| estCostUsd: estimateCostUsd(ctx.model, prompt, completion), | |
| }); | |
| } | |