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 { 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), }); }