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 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 | 6x 6x 6x 6x 6x 6x 7x 7x 4x 4x 4x 7x 3x 1x 7x 7x 4x 4x 4x 7x 3x 7x 5x 3x 2x 8x 8x 2x 2x 2x 2x 2x 2x 4x 3x 3x 3x 4x 4x 8x 3x 6x 6x 6x 6x 30x 6x 6x 6x 6x 6x 30x 6x 6x 3x 6x 6x 6x 6x 186x 6x 6x 180x 186x 39x 39x 39x 939x 39x 6x 6x 186x 6x 6x 180x 186x 6x 6x 186x 6x 6x 180x 186x 6x 6x 186x 6x 6x 180x 186x 7x 7x 3x 3x 3x 3x 3x 7x 2x 1x 7x 7x 3x 3x 3x 3x 7x 2x 1x | import { Conversation } from "@/objects/Model";
import { LLMInvocationRecord } from "@/services/api/routers/StatsRouter";
import { ModelUnit, modelUnits } from "@/util/invocationModels";
import { groupTraceByNode } from "@/util/traceUtils";
import { parseServerDate } from "@/util/time";
// ─── Tool usage ───────────────────────────────────────────────────────────────
export interface ToolUsageStat {
tool: string;
success: number;
error: number;
total: number;
}
/** Tally tool calls across every message's trace, split by outcome. */
export function aggregateToolUsage(
conversations: Conversation[],
): ToolUsageStat[] {
const byTool = new Map<string, ToolUsageStat>();
for (const conv of conversations) {
for (const msg of conv.messages) {
if (!msg.trace) continue;
for (const node of groupTraceByNode(msg.trace)) {
for (const call of node.tools) {
const entry = byTool.get(call.tool) ?? {
tool: call.tool,
success: 0,
error: 0,
total: 0,
};
if (call.status === "error") entry.error++;
else entry.success++;
entry.total++;
byTool.set(call.tool, entry);
}
}
}
}
return Array.from(byTool.values()).sort((a, b) => b.total - a.total);
}
// ─── Agent token ranking ──────────────────────────────────────────────────────
export interface AgentTokenStat {
agentId: string;
name: string;
tokens: number;
conversationCount: number;
}
/** Sum conversation token totals per agent, resolving names via agentMap. */
export function aggregateAgentTokenUsage(
conversations: Conversation[],
agentNameById: Record<string, string>,
): AgentTokenStat[] {
const byAgent = new Map<string, AgentTokenStat>();
for (const conv of conversations) {
if (!conv.agent_id) continue;
const entry = byAgent.get(conv.agent_id) ?? {
agentId: conv.agent_id,
name: agentNameById[conv.agent_id] ?? "Unknown agent",
tokens: 0,
conversationCount: 0,
};
entry.tokens += conv.total_tokens ?? 0;
entry.conversationCount++;
byAgent.set(conv.agent_id, entry);
}
return Array.from(byAgent.values()).sort((a, b) => b.tokens - a.tokens);
}
// ─── Model token usage ────────────────────────────────────────────────────────
export interface ModelTokenStat {
/** The exact model — `provider/model_name` (see `ModelUnit.key`). */
key: string;
name: string;
tokens: number;
}
/**
* Tokens per model, each call's credited to the model that made it — pass
* `chatModelUnits` for the chats' tokens. A conversation's own total names
* no model (an agent chat's turns use several), so counting conversations
* left every agent chat out.
*/
export function aggregateModelTokenUsage(
units: readonly ModelUnit[],
): ModelTokenStat[] {
const byModel = new Map<string, ModelTokenStat>();
for (const unit of units) {
const entry = byModel.get(unit.key) ?? {
key: unit.key,
name: unit.label,
tokens: 0,
};
entry.tokens += unit.inputTokens + unit.outputTokens;
byModel.set(unit.key, entry);
}
return Array.from(byModel.values())
.filter((m) => m.tokens > 0)
.sort((a, b) => b.tokens - a.tokens);
}
// ─── Estimated cost by model ───────────────────────────────────────────────────
export interface ModelCostStat {
name: string;
cost: number;
}
/** Spend per model, each call's cost credited to the model that made it. */
export function aggregateCostByModel(
invocations: LLMInvocationRecord[],
): ModelCostStat[] {
const byModel = new Map<string, ModelCostStat>();
for (const unit of invocations.flatMap(modelUnits)) {
const entry = byModel.get(unit.key) ?? { name: unit.label, cost: 0 };
entry.cost += unit.costUsd ?? 0;
byModel.set(unit.key, entry);
}
return Array.from(byModel.values()).sort((a, b) => b.cost - a.cost);
}
// ─── Policy / audit rule hits ─────────────────────────────────────────────────
export interface PolicyHitStat {
rule: string;
action: string;
count: number;
}
export const POLICY_NODE_IDS = new Set(["__policy__", "__audit__"]);
/**
* A rule action as the hit charts count it. One key, `redact_pii`, serves
* both Input and Output rules (Input's was `filter_pii` before layers), so a
* redaction is named by the side of the model it ran on: its trace node.
*/
export function hitAction(nodeId: string, action: string): string {
if (action === "filter_pii") return "redact_prompt";
if (action === "redact_pii") {
return nodeId === "__audit__" ? "redact_answer" : "redact_prompt";
}
return action;
}
/** Tally rule/action pairs recorded by the policy and audit system nodes. */
export function aggregatePolicyHits(
conversations: Conversation[],
): PolicyHitStat[] {
const byKey = new Map<string, PolicyHitStat>();
for (const conv of conversations) {
for (const msg of conv.messages) {
Iif (!msg.trace) continue;
for (const node of groupTraceByNode(msg.trace)) {
Iif (!POLICY_NODE_IDS.has(node.node_id)) continue;
const events =
((node.system_result ?? {}) as {
events?: { rule: string; action: string; changed?: boolean }[];
}).events ?? [];
for (const ev of events) {
// A redactor over clean text emits an event that says it found
// nothing; that is the rule running, not the rule hitting.
if (ev.changed === false) continue;
const action = hitAction(node.node_id, ev.action);
const key = `${ev.rule}::${action}`;
const entry = byKey.get(key) ?? {
rule: ev.rule,
action,
count: 0,
};
entry.count++;
byKey.set(key, entry);
}
}
}
}
return Array.from(byKey.values()).sort((a, b) => b.count - a.count);
}
/** Fixed action display order, shared with the rule-hit chart's legend. */
export const POLICY_ACTION_ORDER = [
"block",
"redact_prompt",
"redact_answer",
"flag_for_review",
// Removed as an action (svc-core migration 79); historic traces carry it.
"log",
] as const;
export type PolicyHitByRuleRow = { rule: string } & Record<string, number>;
/** Pivot rule/action hit counts into one row per rule, one column per action. */
export function pivotPolicyHitsByRule(
hits: PolicyHitStat[],
): { rows: PolicyHitByRuleRow[]; actionsPresent: string[] } {
const ruleOrder: string[] = [];
const byRule = new Map<string, PolicyHitByRuleRow>();
for (const hit of hits) {
if (!byRule.has(hit.rule)) {
byRule.set(hit.rule, { rule: hit.rule });
ruleOrder.push(hit.rule);
}
byRule.get(hit.rule)![hit.action] =
(byRule.get(hit.rule)![hit.action] ?? 0) + hit.count;
}
const actionsPresent = POLICY_ACTION_ORDER.filter((action) =>
hits.some((h) => h.action === action),
);
// Any action outside the known fixed set still gets counted and shown.
for (const hit of hits) {
if (!POLICY_ACTION_ORDER.includes(hit.action as never)) {
if (!actionsPresent.includes(hit.action)) actionsPresent.push(hit.action);
}
}
const rows = ruleOrder
.map((rule) => byRule.get(rule)!)
.sort((a, b) => {
const totalA = actionsPresent.reduce((s, act) => s + (a[act] ?? 0), 0);
const totalB = actionsPresent.reduce((s, act) => s + (b[act] ?? 0), 0);
return totalB - totalA;
});
return { rows, actionsPresent };
}
export interface ActionStat {
action: string;
count: number;
}
/** Tally rule hits by action alone, collapsing across every rule. */
export function aggregateActionsTaken(hits: PolicyHitStat[]): ActionStat[] {
const byAction = new Map<string, number>();
for (const hit of hits) {
byAction.set(hit.action, (byAction.get(hit.action) ?? 0) + hit.count);
}
const known = POLICY_ACTION_ORDER.filter((a) => byAction.has(a)).map(
(action) => ({ action, count: byAction.get(action)! }),
);
const other = Array.from(byAction.entries())
.filter(([a]) => !(POLICY_ACTION_ORDER as readonly string[]).includes(a))
.map(([action, count]) => ({ action, count }));
return [...known, ...other];
}
// ─── Conversations over time ──────────────────────────────────────────────────
export type TimeBucketGranularity = "hour" | "day" | "week";
export const BUCKET_MS: Record<TimeBucketGranularity, number> = {
hour: 3_600_000,
day: 86_400_000,
week: 7 * 86_400_000,
};
/** Mirrors Grafana's "auto" interval: pick a bucket width from the span. */
export function chooseGranularity(spanMs: number): TimeBucketGranularity {
Iif (spanMs <= 2 * BUCKET_MS.day) return "hour";
Eif (spanMs <= 120 * BUCKET_MS.day) return "day";
return "week";
}
export interface TimeBucketCount {
/** Bucket start, ISO timestamp. */
date: string;
count: number;
}
/**
* Zero-filled conversation counts bucketed from `since` to `until` at
* `granularity`. Buckets are aligned to their natural boundary (UTC epoch
* multiples of the bucket width) so adjacent windows tile without gaps.
*/
export function aggregateConversationsOverTime(
conversations: Conversation[],
since: Date,
until: Date,
granularity: TimeBucketGranularity,
): TimeBucketCount[] {
const bucketMs = BUCKET_MS[granularity];
const counts = new Map<number, number>(
bucketStarts(since, until, bucketMs).map((t) => [t, 0]),
);
for (const conv of conversations) {
const created = parseServerDate(conv.created_at).getTime();
if (isNaN(created) || created < since.getTime() || created > until.getTime())
continue;
const bucket = Math.floor(created / bucketMs) * bucketMs;
if (counts.has(bucket)) counts.set(bucket, (counts.get(bucket) ?? 0) + 1);
}
return Array.from(counts.entries())
.sort(([a], [b]) => a - b)
.map(([t, count]) => ({ date: new Date(t).toISOString(), count }));
}
/** Aligned bucket-start timestamps spanning `since`..`until` at `bucketMs`. */
export function bucketStarts(since: Date, until: Date, bucketMs: number): number[] {
const start = Math.floor(since.getTime() / bucketMs) * bucketMs;
const end = Math.floor(until.getTime() / bucketMs) * bucketMs;
const starts: number[] = [];
for (let t = start; t <= end; t += bucketMs) starts.push(t);
return starts;
}
// ─── Token usage over time ─────────────────────────────────────────────────────
export interface TokenBucket {
date: string;
input: number;
output: number;
}
/** Zero-filled input/output token totals bucketed from `since` to `until`. */
export function aggregateTokensOverTime(
conversations: Conversation[],
since: Date,
until: Date,
granularity: TimeBucketGranularity,
): TokenBucket[] {
const bucketMs = BUCKET_MS[granularity];
const buckets = new Map<number, { input: number; output: number }>(
bucketStarts(since, until, bucketMs).map((t) => [t, { input: 0, output: 0 }]),
);
for (const conv of conversations) {
const created = parseServerDate(conv.created_at).getTime();
if (isNaN(created) || created < since.getTime() || created > until.getTime())
continue;
const entry = buckets.get(Math.floor(created / bucketMs) * bucketMs);
if (entry) {
entry.input += conv.total_input_tokens ?? 0;
entry.output += conv.total_output_tokens ?? 0;
}
}
return Array.from(buckets.entries())
.sort(([a], [b]) => a - b)
.map(([t, v]) => ({ date: new Date(t).toISOString(), ...v }));
}
// ─── Cost over time ─────────────────────────────────────────────────────────────
export interface CostBucket {
date: string;
cost: number;
}
/** Zero-filled estimated cost totals bucketed from `since` to `until`. */
export function aggregateCostOverTime(
invocations: LLMInvocationRecord[],
since: Date,
until: Date,
granularity: TimeBucketGranularity,
): CostBucket[] {
const bucketMs = BUCKET_MS[granularity];
const buckets = new Map<number, number>(
bucketStarts(since, until, bucketMs).map((t) => [t, 0]),
);
for (const inv of invocations) {
if (!inv.created_at) continue;
const created = parseServerDate(inv.created_at).getTime();
if (isNaN(created) || created < since.getTime() || created > until.getTime())
continue;
const bucket = Math.floor(created / bucketMs) * bucketMs;
if (buckets.has(bucket)) {
buckets.set(bucket, (buckets.get(bucket) ?? 0) + (inv.estimated_cost_usd ?? 0));
}
}
return Array.from(buckets.entries())
.sort(([a], [b]) => a - b)
.map(([t, cost]) => ({
date: new Date(t).toISOString(),
cost: Math.round(cost * 10_000) / 10_000,
}));
}
// ─── Invocation status over time ───────────────────────────────────────────────
export interface InvocationStatusBucket {
date: string;
success: number;
error: number;
}
/** Zero-filled success/error invocation counts bucketed from `since` to `until`. */
export function aggregateInvocationStatusOverTime(
invocations: LLMInvocationRecord[],
since: Date,
until: Date,
granularity: TimeBucketGranularity,
): InvocationStatusBucket[] {
const bucketMs = BUCKET_MS[granularity];
const buckets = new Map<number, { success: number; error: number }>(
bucketStarts(since, until, bucketMs).map((t) => [t, { success: 0, error: 0 }]),
);
for (const inv of invocations) {
if (!inv.created_at) continue;
const created = parseServerDate(inv.created_at).getTime();
if (isNaN(created) || created < since.getTime() || created > until.getTime())
continue;
const entry = buckets.get(Math.floor(created / bucketMs) * bucketMs);
if (entry) {
if (inv.status === "success") entry.success++;
else entry.error++;
}
}
return Array.from(buckets.entries())
.sort(([a], [b]) => a - b)
.map(([t, v]) => ({ date: new Date(t).toISOString(), ...v }));
}
// ─── Latency by model ───────────────────────────────────────────────────────────
export interface ModelLatencyStat {
name: string;
avgLatencyMs: number;
}
/** Mean response time per model, over the calls each model answered. */
export function aggregateLatencyByModel(
invocations: LLMInvocationRecord[],
): ModelLatencyStat[] {
const byModel = new Map<string, { name: string; sum: number; n: number }>();
for (const unit of invocations.flatMap(modelUnits)) {
Iif (unit.latencyMs === null) continue;
const entry = byModel.get(unit.key) ?? { name: unit.label, sum: 0, n: 0 };
entry.sum += unit.latencyMs;
entry.n += 1;
byModel.set(unit.key, entry);
}
return Array.from(byModel.values())
.map(({ name, sum, n }) => ({ name, avgLatencyMs: Math.round(sum / n) }))
.sort((a, b) => b.avgLatencyMs - a.avgLatencyMs);
}
// ─── Breakdown by maker ─────────────────────────────────────────────────────────
export interface MakerStat {
/** Who made the models (``objects/modelOrigin``). */
maker: string;
/** Model calls made to the maker's models. */
count: number;
cost: number;
}
/** Model calls and spend per model maker, each call credited to the maker
* of the model that made it — never to the platform that served it. */
export function aggregateByMaker(
invocations: LLMInvocationRecord[],
): MakerStat[] {
const byMaker = new Map<string, { count: number; cost: number }>();
for (const unit of invocations.flatMap(modelUnits)) {
const entry = byMaker.get(unit.maker) ?? { count: 0, cost: 0 };
entry.count += 1;
entry.cost += unit.costUsd ?? 0;
byMaker.set(unit.maker, entry);
}
return Array.from(byMaker.entries())
.map(([maker, { count, cost }]) => ({ maker, count, cost }))
.sort((a, b) => b.count - a.count);
}
|