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 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 | 2x 2x 15x 15x 15x 195x 15x 195x 15x 15x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 15x 15x 195x 195x 195x 195x 16x 16x 16x 195x 15x 15x 2x 2x 2x 3x 1x 2x 3x 2x 2x 2x 1x 14x 7x 7x 15x 2x 2x 15x 15x 15x 15x 9x 8x 15x 8x 4x 8x 5x 5x 16x 12x 1x 5x 1x 4x 1x 1x 4x 1x 1x 15x | import { Conversation } from "@/objects/Model";
import { LLMInvocationRecord } from "@/services/api/routers/StatsRouter";
import {
BUCKET_MS,
bucketStarts,
POLICY_NODE_IDS,
TimeBucketGranularity,
} from "@/util/statsAggregation";
import {
chatModelUnits,
ModelUnit,
modelUnits,
} from "@/util/invocationModels";
import { groupTraceByNode } from "@/util/traceUtils";
import { parseServerDate } from "@/util/time";
// ─── Metric catalog ─────────────────────────────────────────────────────────
//
// A small, self-describing catalog of "what can be plotted" — the data users
// pick from in the Explorer tab, similar to a cloud metrics viewer (CloudWatch
// Metrics Explorer, Grafana Explore). Each metric declares its own valid
// group-by dimensions so the UI can offer only sensible combinations.
export type MetricKey =
| "conversations"
| "total_tokens"
| "input_tokens"
| "output_tokens"
| "tool_calls"
| "policy_hits"
| "invocations"
| "cost"
| "latency"
| "errors";
export type GroupByKey =
| "none"
| "agent"
| "model"
| "tool"
| "provider"
| "rule"
| "action"
| "status";
export type MetricUnit = "count" | "tokens" | "usd" | "ms";
export interface MetricDef {
key: MetricKey;
label: string;
unit: MetricUnit;
groupOptions: GroupByKey[];
}
export const GROUP_BY_LABEL: Record<GroupByKey, string> = {
none: "None (total)",
agent: "Agent",
model: "Model",
tool: "Tool",
provider: "Model maker",
rule: "Rule",
action: "Action",
status: "Status",
};
export const METRICS: MetricDef[] = [
{
key: "conversations",
label: "Conversations",
unit: "count",
groupOptions: ["none", "agent", "model"],
},
{
key: "total_tokens",
label: "Total Tokens",
unit: "tokens",
groupOptions: ["none", "agent", "model", "provider"],
},
{
key: "input_tokens",
label: "Input Tokens",
unit: "tokens",
groupOptions: ["none", "agent", "model", "provider"],
},
{
key: "output_tokens",
label: "Output Tokens",
unit: "tokens",
groupOptions: ["none", "agent", "model", "provider"],
},
{
key: "tool_calls",
label: "Tool Calls",
unit: "count",
groupOptions: ["none", "tool", "status"],
},
{
key: "policy_hits",
label: "Policy/Audit Hits",
unit: "count",
groupOptions: ["none", "rule", "action"],
},
{
key: "invocations",
label: "LLM Invocations",
unit: "count",
groupOptions: ["none", "model", "provider", "status"],
},
{
key: "cost",
label: "Estimated Cost",
unit: "usd",
groupOptions: ["none", "model", "provider"],
},
{
key: "latency",
label: "Avg Latency",
unit: "ms",
groupOptions: ["none", "model", "provider"],
},
{
key: "errors",
label: "Invocation Errors",
unit: "count",
groupOptions: ["none", "model", "provider"],
},
];
export function metricDef(key: MetricKey): MetricDef {
return METRICS.find((m) => m.key === key) ?? METRICS[0];
}
// ─── Event extraction (for metrics with no 1:1 row of their own) ──────────────
interface ToolCallEvent {
date: string;
tool: string;
status: string;
}
/** Flattens every tool call across all conversations, attributed to the
* message's send time (falling back to the conversation's created_at). */
function extractToolCallEvents(conversations: Conversation[]): ToolCallEvent[] {
const events: ToolCallEvent[] = [];
for (const conv of conversations) {
for (const msg of conv.messages) {
if (!msg.trace) continue;
const date = msg.sent_at || conv.created_at;
for (const node of groupTraceByNode(msg.trace)) {
for (const call of node.tools) {
events.push({ date, tool: call.tool, status: call.status });
}
}
}
}
return events;
}
interface PolicyHitEvent {
date: string;
rule: string;
action: string;
}
/** Flattens every policy/audit rule event across all conversations. */
function extractPolicyHitEvents(conversations: Conversation[]): PolicyHitEvent[] {
const events: PolicyHitEvent[] = [];
for (const conv of conversations) {
for (const msg of conv.messages) {
if (!msg.trace) continue;
const date = msg.sent_at || conv.created_at;
for (const node of groupTraceByNode(msg.trace)) {
if (!POLICY_NODE_IDS.has(node.node_id)) continue;
const ruleEvents =
((node.system_result ?? {}) as {
events?: { rule: string; action: string; changed?: boolean }[];
}).events ?? [];
for (const ev of ruleEvents) {
// An action that found nothing to do is not a hit.
if (ev.changed === false) continue;
events.push({ date, rule: ev.rule, action: ev.action });
}
}
}
}
return events;
}
// ─── Generic time-bucketed, grouped aggregator ─────────────────────────────────
export type MetricPoint = { date: string } & Record<string, number | string>;
type Aggregation = "sum" | "avg" | "count";
/**
* Buckets `items` over time and, within each bucket, sums/averages/counts
* `getValue` per group returned by `getGroup`. Zero-filled across the full
* `since`..`until` span so every series has one point per bucket.
*/
function aggregateMetricOverTime<T>(
items: T[],
getDate: (item: T) => string | null | undefined,
getValue: (item: T) => number,
getGroup: (item: T) => string,
since: Date,
until: Date,
granularity: TimeBucketGranularity,
agg: Aggregation,
): { rows: MetricPoint[]; groups: string[] } {
const bucketMs = BUCKET_MS[granularity];
const starts = bucketStarts(since, until, bucketMs);
const sums = new Map<number, Map<string, number>>(
starts.map((t) => [t, new Map()]),
);
const counts = new Map<number, Map<string, number>>(
starts.map((t) => [t, new Map()]),
);
const groupSet = new Set<string>();
for (const item of items) {
const dateStr = getDate(item);
Iif (!dateStr) continue;
const t = parseServerDate(dateStr).getTime();
Iif (isNaN(t) || t < since.getTime() || t > until.getTime()) continue;
const bucket = Math.floor(t / bucketMs) * bucketMs;
const sumMap = sums.get(bucket);
const countMap = counts.get(bucket);
Iif (!sumMap || !countMap) continue;
const group = getGroup(item);
groupSet.add(group);
const value = agg === "count" ? 1 : getValue(item);
sumMap.set(group, (sumMap.get(group) ?? 0) + value);
countMap.set(group, (countMap.get(group) ?? 0) + 1);
}
const groups = Array.from(groupSet).sort();
const rows: MetricPoint[] = starts.map((t) => {
const row: MetricPoint = { date: new Date(t).toISOString() };
const sumMap = sums.get(t)!;
const countMap = counts.get(t)!;
for (const g of groups) {
const sum = sumMap.get(g) ?? 0;
const n = countMap.get(g) ?? 0;
row[g] = agg === "avg" ? (n > 0 ? Math.round((sum / n) * 100) / 100 : 0) : sum;
}
return row;
});
return { rows, groups };
}
/** Caps the number of series to `limit`, folding the rest into "Other". */
export function capSeries(
rows: MetricPoint[],
groups: string[],
limit = 8,
): { rows: MetricPoint[]; groups: string[] } {
Eif (groups.length <= limit) return { rows, groups };
const totals = new Map(groups.map((g) => [g, 0]));
for (const row of rows) {
for (const g of groups) totals.set(g, (totals.get(g) ?? 0) + Number(row[g] ?? 0));
}
const kept = [...groups]
.sort((a, b) => (totals.get(b) ?? 0) - (totals.get(a) ?? 0))
.slice(0, limit);
const dropped = groups.filter((g) => !kept.includes(g));
const cappedRows = rows.map((row) => {
const next: MetricPoint = { date: row.date };
for (const g of kept) next[g] = row[g] ?? 0;
if (dropped.length > 0) {
next["Other"] = dropped.reduce((sum, g) => sum + Number(row[g] ?? 0), 0);
}
return next;
});
return { rows: cappedRows, groups: dropped.length > 0 ? [...kept, "Other"] : kept };
}
// ─── Query dispatcher ───────────────────────────────────────────────────────
export interface ExplorerQueryInput {
metric: MetricKey;
groupBy: GroupByKey;
conversations: Conversation[];
invocations: LLMInvocationRecord[];
agentNameById: Record<string, string>;
modelNameById: Record<string, string>;
since: Date;
until: Date;
granularity: TimeBucketGranularity;
}
const GROUP_TOTAL = () => "Total";
const INVOCATION_METRICS: ReadonlySet<MetricKey> = new Set([
"invocations",
"cost",
"latency",
"errors",
]);
const TOKEN_METRICS: ReadonlySet<MetricKey> = new Set([
"total_tokens",
"input_tokens",
"output_tokens",
]);
/** Which records a query is counted from, so a page waits for exactly those
* before drawing it. */
export function querySources(
metric: MetricKey,
groupBy: GroupByKey,
): { conversations: boolean; invocations: boolean } {
if (INVOCATION_METRICS.has(metric)) {
return { conversations: false, invocations: true };
}
const byModel = groupBy === "model" || groupBy === "provider";
return {
conversations: true,
invocations: TOKEN_METRICS.has(metric) && byModel,
};
}
/** A conversation by agent, when it is a chat with a model directly. */
export const DIRECT_MODEL_CHAT = "Direct model chat";
/** A conversation by model, when it is an agent's: its turns use several. */
export const AGENT_CHAT = "Agent chat";
type TokenMetric = "total_tokens" | "input_tokens" | "output_tokens";
/**
* A token metric's figure on a conversation (its stored total) and on one
* model call. By agent or in total a token metric counts conversations; by
* model or provider it counts the calls their turns made, since only a call
* records which model and provider spent the tokens.
*/
const TOKEN_VALUE: Record<
TokenMetric,
{ conversation: (c: Conversation) => number; unit: (u: ModelUnit) => number }
> = {
total_tokens: {
conversation: (c) => c.total_tokens ?? 0,
unit: (u) => u.inputTokens + u.outputTokens,
},
input_tokens: {
conversation: (c) => c.total_input_tokens ?? 0,
unit: (u) => u.inputTokens,
},
output_tokens: {
conversation: (c) => c.total_output_tokens ?? 0,
unit: (u) => u.outputTokens,
},
};
/** Runs one Explorer query: resolves the metric's data source, applies the
* chosen group-by, and returns a zero-filled, capped time series. */
export function runExplorerQuery({
metric,
groupBy,
conversations,
invocations,
agentNameById,
modelNameById,
since,
until,
granularity,
}: ExplorerQueryInput): { rows: MetricPoint[]; groups: string[] } {
const groupConversation =
groupBy === "agent"
? (c: Conversation) =>
c.agent_id
? (agentNameById[c.agent_id] ?? "Deleted agent")
: DIRECT_MODEL_CHAT
: groupBy === "model"
? (c: Conversation) =>
c.ai_model_id
? (modelNameById[c.ai_model_id] ?? "Unknown model")
: AGENT_CHAT
: GROUP_TOTAL;
const groupInvocation =
groupBy === "status" ? (i: LLMInvocationRecord) => i.status : GROUP_TOTAL;
// By model or provider, the unit is a model call — the only thing that has
// exactly one model — each credited with its own tokens, cost, latency and
// outcome. Token metrics take only the chats' calls (see TOKEN_VALUE).
const byModel = groupBy === "model" || groupBy === "provider";
const units = byModel ? invocations.flatMap(modelUnits) : [];
const groupUnit =
groupBy === "provider"
? (u: ModelUnit) => u.maker
: (u: ModelUnit) => u.label;
let result: { rows: MetricPoint[]; groups: string[] };
switch (metric) {
case "conversations":
result = aggregateMetricOverTime(
conversations,
(c) => c.created_at,
() => 1,
groupConversation,
since,
until,
granularity,
"count",
);
break;
case "total_tokens":
case "input_tokens":
case "output_tokens": {
const value = TOKEN_VALUE[metric];
result = byModel
? aggregateMetricOverTime(
// A refused call spent nothing; it is no series on a token chart.
chatModelUnits(invocations, conversations).filter(
(u) => value.unit(u) > 0,
),
(u) => u.created_at,
value.unit,
groupUnit,
since,
until,
granularity,
"sum",
)
: aggregateMetricOverTime(
conversations,
(c) => c.created_at,
value.conversation,
groupConversation,
since,
until,
granularity,
"sum",
);
break;
}
case "tool_calls": {
const events = extractToolCallEvents(conversations);
const groupEvent =
groupBy === "tool"
? (e: ToolCallEvent) => e.tool
: groupBy === "status"
? (e: ToolCallEvent) => e.status
: GROUP_TOTAL;
result = aggregateMetricOverTime(
events,
(e) => e.date,
() => 1,
groupEvent,
since,
until,
granularity,
"count",
);
break;
}
case "policy_hits": {
const events = extractPolicyHitEvents(conversations);
const groupEvent =
groupBy === "rule"
? (e: PolicyHitEvent) => e.rule
: groupBy === "action"
? (e: PolicyHitEvent) => e.action
: GROUP_TOTAL;
result = aggregateMetricOverTime(
events,
(e) => e.date,
() => 1,
groupEvent,
since,
until,
granularity,
"count",
);
break;
}
case "invocations":
result = byModel
? aggregateMetricOverTime(
units,
(u) => u.created_at,
() => 1,
groupUnit,
since,
until,
granularity,
"count",
)
: aggregateMetricOverTime(
invocations,
(i) => i.created_at,
() => 1,
groupInvocation,
since,
until,
granularity,
"count",
);
break;
case "cost":
result = byModel
? aggregateMetricOverTime(
units,
(u) => u.created_at,
(u) => u.costUsd ?? 0,
groupUnit,
since,
until,
granularity,
"sum",
)
: aggregateMetricOverTime(
invocations,
(i) => i.created_at,
(i) => i.estimated_cost_usd ?? 0,
groupInvocation,
since,
until,
granularity,
"sum",
);
break;
case "latency":
result = byModel
? aggregateMetricOverTime(
units.filter((u) => u.latencyMs !== null),
(u) => u.created_at,
(u) => u.latencyMs ?? 0,
groupUnit,
since,
until,
granularity,
"avg",
)
: aggregateMetricOverTime(
invocations,
(i) => i.created_at,
(i) => i.latency_ms ?? 0,
groupInvocation,
since,
until,
granularity,
"avg",
);
break;
case "errors":
result = byModel
? aggregateMetricOverTime(
units.filter((u) => u.failed),
(u) => u.created_at,
() => 1,
groupUnit,
since,
until,
granularity,
"count",
)
: aggregateMetricOverTime(
invocations.filter((i) => i.status !== "success"),
(i) => i.created_at,
() => 1,
groupInvocation,
since,
until,
granularity,
"count",
);
break;
}
return capSeries(result.rows, result.groups);
}
|