SPB Git

Repository Public MIT

usage.ts 12.8 KB 285 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : VQuant8 * File             : server/next/usage.ts9 * Module           : server10 * Repository       : https://git.spboucher.ai/vquant11 * Project Website  : https://vquant.spboucher.ai12 * Created          : 2026-11-2013 * Last Modified    : 2026-11-2014 *15 * Author           : Simon-Pierre Boucher16 * Position         : Professor of Finance17 * Institution      : Université du Québec en Outaouais (UQO)18 * Organization     : SP Boucher19 * Website          : https://spboucher.ai20 * Git              : https://git.spboucher.ai21 *22 * Preferred Contact: contact@spboucher.ai23 * Development      : dev@spboucher.ai24 * Support          : support@spboucher.ai25 * Security/Admin   : admin@spboucher.ai26 *27 * Copyright (c) 202628 * Simon-Pierre Boucher29 * All rights reserved where applicable. This file is governed by the30 * applicable project license, copyright notices and relevant law.31 * Existing third-party rights and notices remain unaffected.32 *33 * SPDX Identifier  : MIT34 * License          : MIT License35 * License File     : LICENSE36 *37 * Do not embed credentials, private keys, access tokens,38 * certificates or confidential personal information.39 *40 * =============================================================================41 * END OF SP BOUCHER SOURCE HEADER42 * =============================================================================43 */4445/**46 * Usage and cost accounting (contract: docs/next/CONTRACT.md §2.3).47 *48 * One row of vq_usage per model call (lead, worker, auditor, reviewer), with the generation and the conversation49 * it belongs to. Cost comes from the price the repository or the provider states for the model; when there is50 * none the cost is NULL — it is never estimated. A total that includes an unpriced call is reported as null, with51 * the priced part beside it (`knownCostUsd`), so nothing reads as a complete figure when it is not.52 */53import type { Express, Request, Response } from "express";54import type Database from "better-sqlite3";55import { isSqlite, pool } from "../db";56import { currentUser } from "../access";57import type { ModelPricing } from "./providers";5859/** "utility" = small auxiliary calls of a generation: follow-up suggestions, the history summariser. */60export type UsageRole = "lead" | "worker" | "auditor" | "reviewer" | "router" | "utility";6162export interface UsageEntry {63  model: string;64  provider: string;65  role: UsageRole;66  inputTokens: number;67  outputTokens: number;68  /** null = no known price for this model */69  costUsd: number | null;70}7172export interface UsageSummary {73  inputTokens: number;74  outputTokens: number;75  /** null as soon as one call has no known price */76  costUsd: number | null;77  /** sum of the calls that have a price */78  knownCostUsd: number;79  byModel: Array<{ model: string; provider: string; role: UsageRole; calls: number; inputTokens: number; outputTokens: number; costUsd: number | null }>;80}8182const round6 = (x: number) => Math.round(x * 1e6) / 1e6;8384/** Cost of a call at list price, or null when the price is not known. Token counts are plain input and output. */85export function costFromPricing(pricing: ModelPricing | null | undefined, inputTokens: number, outputTokens: number): number | null {86  if (!pricing) return null;87  return (inputTokens * pricing.inputPerMTok + outputTokens * pricing.outputPerMTok) / 1_000_000;88}8990/** Totals of a list of calls, grouped by model, provider and role. Pure. */91export function summarizeUsage(entries: UsageEntry[]): UsageSummary {92  const groups = new Map<string, UsageSummary["byModel"][number] & { unpriced: boolean }>();93  let inputTokens = 0;94  let outputTokens = 0;95  let known = 0;96  let unpriced = false;97  for (const e of entries) {98    inputTokens += e.inputTokens;99    outputTokens += e.outputTokens;100    if (e.costUsd === null) unpriced = true;101    else known += e.costUsd;102    const key = `${e.provider}\u0000${e.model}\u0000${e.role}`;103    let g = groups.get(key);104    if (!g) {105      g = { model: e.model, provider: e.provider, role: e.role, calls: 0, inputTokens: 0, outputTokens: 0, costUsd: 0, unpriced: false };106      groups.set(key, g);107    }108    g.calls++;109    g.inputTokens += e.inputTokens;110    g.outputTokens += e.outputTokens;111    if (e.costUsd === null) g.unpriced = true;112    else g.costUsd = (g.costUsd ?? 0) + e.costUsd;113  }114  return {115    inputTokens,116    outputTokens,117    costUsd: unpriced ? null : round6(known),118    knownCostUsd: round6(known),119    byModel: [...groups.values()].map(({ unpriced: u, ...g }) => ({ ...g, costUsd: u ? null : round6(g.costUsd ?? 0) })),120  };121}122123type Db = Database.Database;124const sqlite = (db?: Db): Db | null => db ?? (isSqlite ? (pool as Db) : null);125126export interface UsageScope {127  owner: string;128  sessionId?: string | null;129  generationId?: string | null;130}131132/** Writes one model call. Never throws: accounting must not break an analysis. */133export function recordUsage(scope: UsageScope, e: UsageEntry, db?: Db): void {134  try {135    sqlite(db)136      ?.prepare("INSERT INTO vq_usage (owner, session_id, generation_id, at, model, provider, role, input_tokens, output_tokens, cost_usd) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")137      .run(scope.owner, scope.sessionId ?? null, scope.generationId ?? null, Date.now(), e.model, e.provider, e.role, Math.round(e.inputTokens), Math.round(e.outputTokens), e.costUsd);138  } catch (err) {139    console.error("[usage] could not record a model call:", (err as Error).message);140  }141}142143/** Collects the calls of one generation (or one review): each is written to vq_usage and kept for the summary. */144export class UsageMeter {145  private entries: UsageEntry[] = [];146  constructor(private scope: UsageScope, private db?: Db) {}147148  add(e: UsageEntry): void {149    this.entries.push(e);150    recordUsage(this.scope, e, this.db);151  }152  /** Cost known so far (unpriced calls count for nothing: a budget can only be held against what is known). */153  knownCostUsd(): number {154    let s = 0;155    for (const e of this.entries) s += e.costUsd ?? 0;156    return s;157  }158  summary(): UsageSummary {159    return summarizeUsage(this.entries);160  }161}162163export interface BudgetLimits {164  maxCostUsd?: number | null;165  maxMinutes?: number | null;166}167export interface BudgetHit {168  kind: "cost" | "minutes";169  limit: number;170  spent: number;171}172173export interface AppliedBudget {174  maxCostUsd: number | null;175  maxMinutes: number | null;176  /** where the limits come from: the request wins as a whole over the person's preference; "default" = no limit */177  source: "request" | "preference" | "default";178}179180/** The budget a generation runs under. A request that sets any limit is used as is; otherwise the preference; otherwise none. Pure. */181export function resolveBudget(requested: BudgetLimits | null | undefined, preference: BudgetLimits | null | undefined): AppliedBudget {182  const ok = (v: unknown): number | null => (typeof v === "number" && Number.isFinite(v) && v > 0 ? v : null);183  const pick = (b: BudgetLimits | null | undefined) => ({ maxCostUsd: ok(b?.maxCostUsd), maxMinutes: ok(b?.maxMinutes) });184  const r = pick(requested);185  if (r.maxCostUsd !== null || r.maxMinutes !== null) return { ...r, source: "request" };186  const p = pick(preference);187  if (p.maxCostUsd !== null || p.maxMinutes !== null) return { ...p, source: "preference" };188  return { maxCostUsd: null, maxMinutes: null, source: "default" };189}190191/**192 * Budget of one generation (contract §2.4). `check()` is called between steps: the first time a limit is passed it193 * reports the hit once (the `budget` event) and from then on returns the sentence the agents are given. It never194 * interrupts anything by itself: the lead is asked to conclude, sub-agents to write up.195 */196export class BudgetGuard {197  private hits = new Map<BudgetHit["kind"], BudgetHit>();198  private limits: { cost: number | null; minutes: number | null };199200  constructor(limits: BudgetLimits, private deps: { startedAt: number; spentUsd: () => number; onExceeded?: (hit: BudgetHit) => void; now?: () => number }) {201    const ok = (v: unknown): number | null => (typeof v === "number" && Number.isFinite(v) && v > 0 ? v : null);202    this.limits = { cost: ok(limits.maxCostUsd), minutes: ok(limits.maxMinutes) };203  }204205  check(): string | null {206    const minutes = ((this.deps.now ?? Date.now)() - this.deps.startedAt) / 60_000;207    const cost = this.deps.spentUsd();208    this.test("cost", this.limits.cost, cost);209    this.test("minutes", this.limits.minutes, minutes);210    if (this.hits.size === 0) return null;211    const parts = [...this.hits.values()].map((h) => (h.kind === "cost" ? `about $${h.spent.toFixed(2)} spent for a limit of $${h.limit}` : `${Math.round(h.spent)} minutes elapsed for a limit of ${h.limit}`));212    return `The budget set for this analysis is reached (${parts.join("; ")}).`;213  }214215  /** New limits after the person approved a higher budget: what was reached below them no longer counts. */216  raise(limits: BudgetLimits): void {217    const ok = (v: unknown): number | null => (typeof v === "number" && Number.isFinite(v) && v > 0 ? v : null);218    const cost = ok(limits.maxCostUsd);219    const minutes = ok(limits.maxMinutes);220    if (cost !== null && (this.limits.cost === null || cost > this.limits.cost)) {221      this.limits.cost = cost;222      this.hits.delete("cost");223    }224    if (minutes !== null && (this.limits.minutes === null || minutes > this.limits.minutes)) {225      this.limits.minutes = minutes;226      this.hits.delete("minutes");227    }228  }229230  private test(kind: BudgetHit["kind"], limit: number | null, spent: number): void {231    if (limit === null || this.hits.has(kind) || spent < limit) return;232    const hit = { kind, limit, spent: Math.round(spent * 100) / 100 };233    this.hits.set(kind, hit);234    this.deps.onExceeded?.(hit);235  }236}237238/** Usage of one generation as stored (the trace route reads it after the fact). */239export function usageOfGeneration(owner: string, generationId: string, db?: Db): UsageSummary {240  const rows = (sqlite(db)?.prepare("SELECT model, provider, role, input_tokens, output_tokens, cost_usd FROM vq_usage WHERE owner = ? AND generation_id = ? ORDER BY id").all(owner, generationId) ?? []) as Array<{ model: string; provider: string; role: UsageRole; input_tokens: number; output_tokens: number; cost_usd: number | null }>;241  return summarizeUsage(rows.map((r) => ({ model: r.model, provider: r.provider, role: r.role, inputTokens: r.input_tokens, outputTokens: r.output_tokens, costUsd: r.cost_usd })));242}243244interface AggRow {245  calls: number;246  input_tokens: number;247  output_tokens: number;248  known_cost: number | null;249  unpriced: number;250}251const agg = "count(*) AS calls, coalesce(sum(input_tokens), 0) AS input_tokens, coalesce(sum(output_tokens), 0) AS output_tokens, sum(cost_usd) AS known_cost, coalesce(sum(cost_usd IS NULL), 0) AS unpriced";252const shape = (r: AggRow) => ({253  calls: r.calls,254  inputTokens: r.input_tokens,255  outputTokens: r.output_tokens,256  costUsd: r.unpriced > 0 ? null : round6(r.known_cost ?? 0),257  knownCostUsd: round6(r.known_cost ?? 0),258  unpricedCalls: r.unpriced,259});260261/** The person's usage over the last `days` days (days are UTC dates). */262export function usageReport(owner: string, days: number, db?: Db, now = Date.now()) {263  const s = sqlite(db);264  const since = now - days * 86_400_000;265  if (!s) return { days, since, totals: shape({ calls: 0, input_tokens: 0, output_tokens: 0, known_cost: 0, unpriced: 0 }), byDay: [], byModel: [] };266  const totals = s.prepare(`SELECT ${agg} FROM vq_usage WHERE owner = ? AND at >= ?`).get(owner, since) as AggRow;267  const byDay = s.prepare(`SELECT strftime('%Y-%m-%d', at / 1000, 'unixepoch') AS date, ${agg} FROM vq_usage WHERE owner = ? AND at >= ? GROUP BY date ORDER BY date`).all(owner, since) as Array<AggRow & { date: string }>;268  const byModel = s.prepare(`SELECT model, provider, role, ${agg} FROM vq_usage WHERE owner = ? AND at >= ? GROUP BY provider, model, role ORDER BY known_cost DESC, input_tokens DESC`).all(owner, since) as Array<AggRow & { model: string; provider: string; role: string }>;269  return {270    days,271    since,272    totals: shape(totals),273    byDay: byDay.map((r) => ({ date: r.date, ...shape(r) })),274    byModel: byModel.map((r) => ({ model: r.model, provider: r.provider, role: r.role, ...shape(r) })),275  };276}277278export function registerUsageRoutes(app: Express): void {279  app.get("/api/v2/usage", (req: Request, res: Response) => {280    const raw = Number.parseInt(String(req.query.days ?? "30"), 10);281    if (req.query.days !== undefined && (!Number.isFinite(raw) || raw < 1 || raw > 366)) return res.status(400).json({ error: "days must be between 1 and 366" });282    res.set("Cache-Control", "private, no-store").json(usageReport(currentUser(req).id, Number.isFinite(raw) ? raw : 30));283  });284}285
Files main
Menu

Theme