New /analytics route: token usage dashboard with aggregate summary, per-session breakdown, context window stats, and per-category token distribution. Data served from existing agent_sessions + tool_cost_stats. New /results route: browsable archive of orchestrator flow runs and arena battles. Two-tab layout (Analysis Runs / Arena Battles) using existing API endpoints (no new backend). Sidebar gains Results (ScrollText icon) and Token Analytics (BarChart3 icon) nav buttons above Settings.
34 lines
1.2 KiB
TypeScript
34 lines
1.2 KiB
TypeScript
import type { FastifyInstance } from 'fastify';
|
|
import type { Sql } from '../db.js';
|
|
|
|
// token-analyzer-ui: context window utilization and token breakdown data.
|
|
// v1 — global aggregates only.
|
|
|
|
export interface ContextWindowStats {
|
|
avg_ctx_used: number | null;
|
|
avg_ctx_max: number | null;
|
|
avg_utilization_pct: number | null;
|
|
message_count: number;
|
|
}
|
|
|
|
export function registerAnalyticsRoutes(app: FastifyInstance, sql: Sql): void {
|
|
// GET /api/analytics/context — average context window utilization across
|
|
// completed assistant messages that carry ctx_used/ctx_max.
|
|
app.get('/api/analytics/context', async () => {
|
|
const [row] = await sql<ContextWindowStats[]>`
|
|
SELECT
|
|
AVG(ctx_used)::DOUBLE PRECISION AS avg_ctx_used,
|
|
AVG(ctx_max)::DOUBLE PRECISION AS avg_ctx_max,
|
|
AVG(ctx_used::float / NULLIF(ctx_max, 0))::DOUBLE PRECISION AS avg_utilization_pct,
|
|
COUNT(*)::INT AS message_count
|
|
FROM messages
|
|
WHERE role = 'assistant'
|
|
AND status = 'complete'
|
|
AND ctx_used IS NOT NULL
|
|
AND ctx_max IS NOT NULL
|
|
AND ctx_max > 0
|
|
`;
|
|
return row ?? { avg_ctx_used: null, avg_ctx_max: null, avg_utilization_pct: null, message_count: 0 };
|
|
});
|
|
}
|