File size: 1,673 Bytes
6d6eaef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
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),
  });
}