All files / src/util invocationModels.ts

100% Statements 36/36
85% Branches 34/40
100% Functions 10/10
100% Lines 28/28

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176                                            4x     4x                                                             162x             74x 74x                                             27x 69x   3x               3x 1x                   2x 1x                   1x                                   12x 12x 12x                   4x 5x 4x 4x 5x 5x   4x                   91x 4x 4x 3x 2x        
import { makerLabel } from "@/objects/modelOrigin";
import {
  LLMInvocationCall,
  LLMInvocationRecord,
} from "@/services/api/routers/StatsRouter";
 
/**
 * Which model did the work behind a traced invocation.
 *
 * svc-ai stores every model call an invocation made — provider, exact model,
 * graph node, tokens, latency, cost — so a skill whose nodes used three
 * models is credited to all three, each for what it did. Every by-model and
 * by-provider figure is counted in {@link ModelUnit}s from here, never from
 * the invocation's own `model_name`, which is the model it *asked for* and is
 * null for a multi-model run.
 *
 * Traces older than call records carry no calls: their own model stands in
 * for the whole invocation (what the stats always did), and one with no model
 * either is labelled as not recorded rather than "Unknown".
 */
 
/** Label for an older trace whose model was never recorded. */
export const MODEL_NOT_RECORDED = "Model not recorded";
 
/** Label for an invocation that ended before any model was called. */
export const NO_MODEL_CALL = "No model call";
 
/** One model's part in an invocation: a call, or a whole older trace. */
export interface ModelUnit {
  /** Groups by exact model — `provider/model_name` — so two models that
   *  share a display name are never merged. */
  key: string;
  /** What to call the model on a chart. */
  label: string;
  /** The catalogue provider key, as the call recorded it (part of ``key``).
   *  ``bedrock`` for a model registered under the platform that serves it —
   *  never shown: read ``maker``. */
  provider: string;
  /** Who made the model (``objects/modelOrigin``): what by-maker figures
   *  group on, so the platform that served a call is never a "provider". */
  maker: string;
  created_at: string | null;
  costUsd: number | null;
  latencyMs: number | null;
  failed: boolean;
  /** The tokens it spent. A failed call's are left out, as svc-ai leaves
   *  them out of the trace's own total. */
  inputTokens: number;
  outputTokens: number;
}
 
/** The label for one exact model: the catalogue's name, else its identifier. */
export function modelLabel(
  modelName: string,
  displayName?: string | null,
): string {
  return displayName || modelName;
}
 
function callUnit(
  call: LLMInvocationCall,
  createdAt: string | null,
): ModelUnit {
  const failed = call.status !== "success";
  return {
    key: `${call.provider}/${call.model_name}`,
    label: modelLabel(call.model_name, call.model_display_name),
    provider: call.provider,
    maker: makerLabel(call.provider, call.model_name),
    created_at: createdAt,
    costUsd: call.estimated_cost_usd,
    latencyMs: call.latency_ms,
    failed,
    inputTokens: failed ? 0 : call.prompt_tokens,
    outputTokens: failed ? 0 : call.completion_tokens,
  };
}
 
/**
 * The model units an invocation contributes to by-model figures.
 *
 * One per recorded call; for an older trace without calls, one for the
 * model it names (or one "not recorded" unit). An invocation that made no
 * call and named no model — refused before reaching one — contributes none:
 * it is not model work.
 */
export function modelUnits(inv: LLMInvocationRecord): ModelUnit[] {
  const calls = inv.calls ?? [];
  if (calls.length > 0) return calls.map((c) => callUnit(c, inv.created_at));
 
  const base = {
    created_at: inv.created_at,
    costUsd: inv.estimated_cost_usd,
    latencyMs: inv.latency_ms,
    failed: inv.status !== "success",
    inputTokens: inv.prompt_tokens,
    outputTokens: inv.completion_tokens,
  };
  if (inv.model_name) {
    return [
      {
        ...base,
        key: `${inv.provider ?? ""}/${inv.model_name}`,
        label: modelLabel(inv.model_name, inv.model_display_name),
        provider: inv.provider ?? MODEL_NOT_RECORDED,
        maker: inv.provider ? makerLabel(inv.provider, inv.model_name) : MODEL_NOT_RECORDED,
      },
    ];
  }
  if (inv.total_tokens > 0) {
    return [
      {
        ...base,
        key: MODEL_NOT_RECORDED,
        label: MODEL_NOT_RECORDED,
        provider: MODEL_NOT_RECORDED,
        maker: MODEL_NOT_RECORDED,
      },
    ];
  }
  return [];
}
 
/**
 * The model calls behind a set of chats' token totals: every call a turn of
 * one of `conversations` made.
 *
 * svc-core keeps a conversation's tokens as a single total with no model or
 * provider — an agent chat names no model at all, and its turns use several
 * (triage, the agent, the evaluator) — while each turn's trace records every
 * call's provider, model and tokens against the conversation's id. So
 * by-model and by-provider token figures are counted here, and add up to the
 * same chats' totals.
 */
export function chatModelUnits(
  invocations: readonly LLMInvocationRecord[],
  conversations: readonly { id: string }[],
): ModelUnit[] {
  const ids = new Set(conversations.map((c) => c.id));
  return invocations
    .filter((inv) => !!inv.conversation_id && ids.has(inv.conversation_id))
    .flatMap(modelUnits);
}
 
/**
 * The distinct models an invocation's calls used, in first-call order: its
 * chat models — embeddings beside them do not make a run multi-model — or,
 * for work that made no chat call (indexing, a search), every model.
 */
export function calledModels(inv: LLMInvocationRecord): ModelUnit[] {
  const calls = inv.calls ?? [];
  const chat = calls.filter((c) => c.kind === "chat");
  const seen = new Map<string, ModelUnit>();
  for (const call of chat.length > 0 ? chat : calls) {
    const unit = callUnit(call, inv.created_at);
    if (!seen.has(unit.key)) seen.set(unit.key, unit);
  }
  return Array.from(seen.values());
}
 
/**
 * One line naming an invocation's model, for a feed row or a panel title.
 *
 * The model it asked for when it named one; otherwise the models its calls
 * used ("Claude Sonnet 5 + 2 more").
 */
export function invocationModelLabel(inv: LLMInvocationRecord): string {
  if (inv.model_name) return modelLabel(inv.model_name, inv.model_display_name);
  const used = calledModels(inv);
  if (used.length === 1) return used[0].label;
  if (used.length > 1) return `${used[0].label} + ${used.length - 1} more`;
  return (inv.calls ?? []).length > 0 || inv.total_tokens > 0
    ? MODEL_NOT_RECORDED
    : NO_MODEL_CALL;
}