feat(analytics): add Requests mode and provider/model breakdown charts
This commit is contained in:
@@ -0,0 +1,107 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useMemo } from "react";
|
||||
import PropTypes from "prop-types";
|
||||
import {
|
||||
BarChart,
|
||||
Bar,
|
||||
XAxis,
|
||||
YAxis,
|
||||
CartesianGrid,
|
||||
Tooltip,
|
||||
ResponsiveContainer,
|
||||
Cell,
|
||||
} from "recharts";
|
||||
import Card from "@/shared/components/Card";
|
||||
|
||||
const COLORS = ["#6366f1", "#14b8a6", "#f59e0b", "#ef4444", "#8b5cf6", "#06b6d4", "#10b981", "#f97316"];
|
||||
|
||||
const fmtTokens = (n) => {
|
||||
if (n >= 1000000) return `${(n / 1000000).toFixed(1)}M`;
|
||||
if (n >= 1000) return `${(n / 1000).toFixed(1)}K`;
|
||||
return String(n || 0);
|
||||
};
|
||||
|
||||
export default function ProviderBarChart({ byProvider }) {
|
||||
const [viewMode, setViewMode] = useState("tokens");
|
||||
|
||||
const chartData = useMemo(() => {
|
||||
if (!byProvider) return [];
|
||||
return Object.entries(byProvider)
|
||||
.map(([id, data]) => ({
|
||||
name: id,
|
||||
tokens: (data.promptTokens || 0) + (data.completionTokens || 0),
|
||||
requests: data.requests || 0,
|
||||
}))
|
||||
.filter((d) => d[viewMode] > 0)
|
||||
.sort((a, b) => b[viewMode] - a[viewMode]);
|
||||
}, [byProvider, viewMode]);
|
||||
|
||||
const fmt = viewMode === "tokens" ? fmtTokens : String;
|
||||
const label = viewMode === "tokens" ? "Tokens" : "Requests";
|
||||
|
||||
return (
|
||||
<Card className="flex min-w-0 flex-col gap-3 p-3 sm:p-4">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<span className="text-sm font-semibold text-text-muted uppercase tracking-wide">By Provider</span>
|
||||
<div className="grid grid-cols-2 items-center gap-1 rounded-lg border border-border bg-bg-subtle p-1">
|
||||
<button
|
||||
onClick={() => setViewMode("tokens")}
|
||||
className={`px-2.5 py-0.5 rounded-md text-xs font-medium transition-colors ${viewMode === "tokens" ? "bg-primary text-white shadow-sm" : "text-text-muted hover:text-text hover:bg-bg-hover"}`}
|
||||
>
|
||||
Tokens
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setViewMode("requests")}
|
||||
className={`px-2.5 py-0.5 rounded-md text-xs font-medium transition-colors ${viewMode === "requests" ? "bg-primary text-white shadow-sm" : "text-text-muted hover:text-text hover:bg-bg-hover"}`}
|
||||
>
|
||||
Requests
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{!chartData.length ? (
|
||||
<div className="h-44 flex items-center justify-center text-text-muted text-sm">No provider usage yet</div>
|
||||
) : (
|
||||
<ResponsiveContainer width="100%" height={180}>
|
||||
<BarChart data={chartData} margin={{ top: 4, right: 8, left: 0, bottom: 4 }}>
|
||||
<CartesianGrid strokeDasharray="3 3" strokeOpacity={0.1} vertical={false} />
|
||||
<XAxis
|
||||
dataKey="name"
|
||||
tick={{ fontSize: 10, fill: "currentColor", fillOpacity: 0.6 }}
|
||||
tickLine={false}
|
||||
axisLine={false}
|
||||
interval={0}
|
||||
tickFormatter={(v) => v.length > 10 ? v.slice(0, 10) + "…" : v}
|
||||
/>
|
||||
<YAxis
|
||||
tick={{ fontSize: 10, fill: "currentColor", fillOpacity: 0.5 }}
|
||||
tickLine={false}
|
||||
axisLine={false}
|
||||
tickFormatter={fmt}
|
||||
width={44}
|
||||
/>
|
||||
<Tooltip
|
||||
contentStyle={{
|
||||
backgroundColor: "var(--color-bg)",
|
||||
border: "1px solid var(--color-border)",
|
||||
borderRadius: "8px",
|
||||
fontSize: "12px",
|
||||
}}
|
||||
formatter={(value) => [fmt(value), label]}
|
||||
/>
|
||||
<Bar dataKey={viewMode} radius={[4, 4, 0, 0]}>
|
||||
{chartData.map((_, i) => (
|
||||
<Cell key={i} fill={COLORS[i % COLORS.length]} fillOpacity={0.85} />
|
||||
))}
|
||||
</Bar>
|
||||
</BarChart>
|
||||
</ResponsiveContainer>
|
||||
)}
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
ProviderBarChart.propTypes = {
|
||||
byProvider: PropTypes.object,
|
||||
};
|
||||
114
src/app/(dashboard)/dashboard/usage/components/TopModelsChart.js
Normal file
114
src/app/(dashboard)/dashboard/usage/components/TopModelsChart.js
Normal file
@@ -0,0 +1,114 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useMemo } from "react";
|
||||
import PropTypes from "prop-types";
|
||||
import {
|
||||
BarChart,
|
||||
Bar,
|
||||
XAxis,
|
||||
YAxis,
|
||||
CartesianGrid,
|
||||
Tooltip,
|
||||
ResponsiveContainer,
|
||||
Cell,
|
||||
} from "recharts";
|
||||
import Card from "@/shared/components/Card";
|
||||
|
||||
const COLORS = ["#6366f1", "#14b8a6", "#f59e0b", "#ef4444", "#8b5cf6"];
|
||||
|
||||
const fmtTokens = (n) => {
|
||||
if (n >= 1000000) return `${(n / 1000000).toFixed(1)}M`;
|
||||
if (n >= 1000) return `${(n / 1000).toFixed(1)}K`;
|
||||
return String(n || 0);
|
||||
};
|
||||
|
||||
const truncate = (s, max = 22) => (s && s.length > max ? s.slice(0, max) + "…" : s || "");
|
||||
|
||||
export default function TopModelsChart({ byModel }) {
|
||||
const [viewMode, setViewMode] = useState("tokens");
|
||||
|
||||
const chartData = useMemo(() => {
|
||||
if (!byModel) return [];
|
||||
return Object.values(byModel)
|
||||
.map((data) => ({
|
||||
name: truncate(data.rawModel || "Unknown"),
|
||||
tokens: (data.promptTokens || 0) + (data.completionTokens || 0),
|
||||
requests: data.requests || 0,
|
||||
}))
|
||||
.filter((d) => d[viewMode] > 0)
|
||||
.sort((a, b) => b[viewMode] - a[viewMode])
|
||||
.slice(0, 5);
|
||||
}, [byModel, viewMode]);
|
||||
|
||||
const fmt = viewMode === "tokens" ? fmtTokens : String;
|
||||
const label = viewMode === "tokens" ? "Tokens" : "Requests";
|
||||
|
||||
return (
|
||||
<Card className="flex min-w-0 flex-col gap-3 p-3 sm:p-4">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<span className="text-sm font-semibold text-text-muted uppercase tracking-wide">Top Models</span>
|
||||
<div className="grid grid-cols-2 items-center gap-1 rounded-lg border border-border bg-bg-subtle p-1">
|
||||
<button
|
||||
onClick={() => setViewMode("tokens")}
|
||||
className={`px-2.5 py-0.5 rounded-md text-xs font-medium transition-colors ${viewMode === "tokens" ? "bg-primary text-white shadow-sm" : "text-text-muted hover:text-text hover:bg-bg-hover"}`}
|
||||
>
|
||||
Tokens
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setViewMode("requests")}
|
||||
className={`px-2.5 py-0.5 rounded-md text-xs font-medium transition-colors ${viewMode === "requests" ? "bg-primary text-white shadow-sm" : "text-text-muted hover:text-text hover:bg-bg-hover"}`}
|
||||
>
|
||||
Requests
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{!chartData.length ? (
|
||||
<div className="h-44 flex items-center justify-center text-text-muted text-sm">No model usage yet</div>
|
||||
) : (
|
||||
<ResponsiveContainer width="100%" height={180}>
|
||||
<BarChart
|
||||
data={chartData}
|
||||
layout="vertical"
|
||||
margin={{ top: 4, right: 40, left: 4, bottom: 4 }}
|
||||
>
|
||||
<CartesianGrid strokeDasharray="3 3" strokeOpacity={0.1} horizontal={false} />
|
||||
<XAxis
|
||||
type="number"
|
||||
tick={{ fontSize: 10, fill: "currentColor", fillOpacity: 0.5 }}
|
||||
tickLine={false}
|
||||
axisLine={false}
|
||||
tickFormatter={fmt}
|
||||
/>
|
||||
<YAxis
|
||||
type="category"
|
||||
dataKey="name"
|
||||
tick={{ fontSize: 10, fill: "currentColor", fillOpacity: 0.7 }}
|
||||
tickLine={false}
|
||||
axisLine={false}
|
||||
width={90}
|
||||
/>
|
||||
<Tooltip
|
||||
contentStyle={{
|
||||
backgroundColor: "var(--color-bg)",
|
||||
border: "1px solid var(--color-border)",
|
||||
borderRadius: "8px",
|
||||
fontSize: "12px",
|
||||
}}
|
||||
formatter={(value) => [fmt(value), label]}
|
||||
/>
|
||||
<Bar dataKey={viewMode} radius={[0, 4, 4, 0]}>
|
||||
{chartData.map((_, i) => (
|
||||
<Cell key={i} fill={COLORS[i % COLORS.length]} fillOpacity={0.85} />
|
||||
))}
|
||||
</Bar>
|
||||
</BarChart>
|
||||
</ResponsiveContainer>
|
||||
)}
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
TopModelsChart.propTypes = {
|
||||
byModel: PropTypes.object,
|
||||
};
|
||||
@@ -10,7 +10,6 @@ import {
|
||||
CartesianGrid,
|
||||
Tooltip,
|
||||
ResponsiveContainer,
|
||||
Legend,
|
||||
} from "recharts";
|
||||
import Card from "@/shared/components/Card";
|
||||
|
||||
@@ -21,6 +20,19 @@ const fmtTokens = (n) => {
|
||||
};
|
||||
|
||||
const fmtCost = (n) => `$${(n || 0).toFixed(4)}`;
|
||||
const fmtRequests = (n) => String(n || 0);
|
||||
|
||||
const VIEW_MODES = [
|
||||
{ value: "tokens", label: "Tokens" },
|
||||
{ value: "requests", label: "Requests" },
|
||||
{ value: "cost", label: "Cost" },
|
||||
];
|
||||
|
||||
const VIEW_CONFIG = {
|
||||
tokens: { dataKey: "tokens", color: "#6366f1", gradId: "gradTokens", formatter: fmtTokens, label: "Tokens" },
|
||||
requests: { dataKey: "requests", color: "#14b8a6", gradId: "gradRequests", formatter: fmtRequests, label: "Requests" },
|
||||
cost: { dataKey: "cost", color: "#f59e0b", gradId: "gradCost", formatter: fmtCost, label: "Cost" },
|
||||
};
|
||||
|
||||
export default function UsageChart({ period = "7d" }) {
|
||||
const [data, setData] = useState([]);
|
||||
@@ -46,23 +58,24 @@ export default function UsageChart({ period = "7d" }) {
|
||||
fetchData();
|
||||
}, [fetchData]);
|
||||
|
||||
const hasData = data.some((d) => d.tokens > 0 || d.cost > 0);
|
||||
const cfg = VIEW_CONFIG[viewMode];
|
||||
const hasData = data.some((d) => (d[cfg.dataKey] || 0) > 0);
|
||||
|
||||
return (
|
||||
<Card className="flex min-w-0 flex-col gap-3 p-3 sm:p-4">
|
||||
<div className="grid w-full grid-cols-2 items-center gap-1 rounded-lg border border-border bg-bg-subtle p-1 sm:w-auto sm:self-start">
|
||||
<button
|
||||
onClick={() => setViewMode("tokens")}
|
||||
className={`px-3 py-1 rounded-md text-sm font-medium transition-colors ${viewMode === "tokens" ? "bg-primary text-white shadow-sm" : "text-text-muted hover:text-text hover:bg-bg-hover"}`}
|
||||
>
|
||||
Tokens
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setViewMode("cost")}
|
||||
className={`px-3 py-1 rounded-md text-sm font-medium transition-colors ${viewMode === "cost" ? "bg-primary text-white shadow-sm" : "text-text-muted hover:text-text hover:bg-bg-hover"}`}
|
||||
>
|
||||
Cost
|
||||
</button>
|
||||
<div
|
||||
className="grid w-full items-center gap-1 rounded-lg border border-border bg-bg-subtle p-1 sm:w-auto sm:self-start"
|
||||
style={{ gridTemplateColumns: `repeat(${VIEW_MODES.length}, minmax(0, 1fr))` }}
|
||||
>
|
||||
{VIEW_MODES.map((m) => (
|
||||
<button
|
||||
key={m.value}
|
||||
onClick={() => setViewMode(m.value)}
|
||||
className={`px-3 py-1 rounded-md text-sm font-medium transition-colors ${viewMode === m.value ? "bg-primary text-white shadow-sm" : "text-text-muted hover:text-text hover:bg-bg-hover"}`}
|
||||
>
|
||||
{m.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{loading ? (
|
||||
@@ -77,6 +90,10 @@ export default function UsageChart({ period = "7d" }) {
|
||||
<stop offset="5%" stopColor="#6366f1" stopOpacity={0.25} />
|
||||
<stop offset="95%" stopColor="#6366f1" stopOpacity={0} />
|
||||
</linearGradient>
|
||||
<linearGradient id="gradRequests" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="5%" stopColor="#14b8a6" stopOpacity={0.25} />
|
||||
<stop offset="95%" stopColor="#14b8a6" stopOpacity={0} />
|
||||
</linearGradient>
|
||||
<linearGradient id="gradCost" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="5%" stopColor="#f59e0b" stopOpacity={0.25} />
|
||||
<stop offset="95%" stopColor="#f59e0b" stopOpacity={0} />
|
||||
@@ -94,7 +111,7 @@ export default function UsageChart({ period = "7d" }) {
|
||||
tick={{ fontSize: 10, fill: "currentColor", fillOpacity: 0.5 }}
|
||||
tickLine={false}
|
||||
axisLine={false}
|
||||
tickFormatter={viewMode === "tokens" ? fmtTokens : fmtCost}
|
||||
tickFormatter={cfg.formatter}
|
||||
width={50}
|
||||
/>
|
||||
<Tooltip
|
||||
@@ -104,31 +121,17 @@ export default function UsageChart({ period = "7d" }) {
|
||||
borderRadius: "8px",
|
||||
fontSize: "12px",
|
||||
}}
|
||||
formatter={(value, name) =>
|
||||
name === "tokens" ? [fmtTokens(value), "Tokens"] : [fmtCost(value), "Cost"]
|
||||
}
|
||||
formatter={(value) => [cfg.formatter(value), cfg.label]}
|
||||
/>
|
||||
<Area
|
||||
type="monotone"
|
||||
dataKey={cfg.dataKey}
|
||||
stroke={cfg.color}
|
||||
strokeWidth={2}
|
||||
fill={`url(#${cfg.gradId})`}
|
||||
dot={false}
|
||||
activeDot={{ r: 4 }}
|
||||
/>
|
||||
{viewMode === "tokens" ? (
|
||||
<Area
|
||||
type="monotone"
|
||||
dataKey="tokens"
|
||||
stroke="#6366f1"
|
||||
strokeWidth={2}
|
||||
fill="url(#gradTokens)"
|
||||
dot={false}
|
||||
activeDot={{ r: 4 }}
|
||||
/>
|
||||
) : (
|
||||
<Area
|
||||
type="monotone"
|
||||
dataKey="cost"
|
||||
stroke="#f59e0b"
|
||||
strokeWidth={2}
|
||||
fill="url(#gradCost)"
|
||||
dot={false}
|
||||
activeDot={{ r: 4 }}
|
||||
/>
|
||||
)}
|
||||
</AreaChart>
|
||||
</ResponsiveContainer>
|
||||
)}
|
||||
|
||||
@@ -670,7 +670,7 @@ export async function getChartData(period = "7d") {
|
||||
const startTime = startOfDay.getTime();
|
||||
const endTime = startTime + bucketCount * bucketMs;
|
||||
const labelFn = (ts) => new Date(ts).toLocaleTimeString("en-US", { hour: "2-digit", minute: "2-digit", hour12: false });
|
||||
const buckets = Array.from({ length: bucketCount }, (_, i) => ({ label: labelFn(startTime + i * bucketMs), tokens: 0, cost: 0 }));
|
||||
const buckets = Array.from({ length: bucketCount }, (_, i) => ({ label: labelFn(startTime + i * bucketMs), tokens: 0, cost: 0, requests: 0 }));
|
||||
|
||||
const rows = db.all(
|
||||
`SELECT timestamp, promptTokens, completionTokens, cost FROM usageHistory WHERE timestamp >= ?`,
|
||||
@@ -683,6 +683,7 @@ export async function getChartData(period = "7d") {
|
||||
if (idx >= 0 && idx < bucketCount) {
|
||||
buckets[idx].tokens += (r.promptTokens || 0) + (r.completionTokens || 0);
|
||||
buckets[idx].cost += r.cost || 0;
|
||||
buckets[idx].requests += 1;
|
||||
}
|
||||
}
|
||||
return buckets;
|
||||
@@ -693,7 +694,7 @@ export async function getChartData(period = "7d") {
|
||||
const bucketMs = 3600000;
|
||||
const labelFn = (ts) => new Date(ts).toLocaleTimeString("en-US", { hour: "2-digit", minute: "2-digit", hour12: false });
|
||||
const startTime = now - bucketCount * bucketMs;
|
||||
const buckets = Array.from({ length: bucketCount }, (_, i) => ({ label: labelFn(startTime + i * bucketMs), tokens: 0, cost: 0 }));
|
||||
const buckets = Array.from({ length: bucketCount }, (_, i) => ({ label: labelFn(startTime + i * bucketMs), tokens: 0, cost: 0, requests: 0 }));
|
||||
|
||||
const rows = db.all(
|
||||
`SELECT timestamp, promptTokens, completionTokens, cost FROM usageHistory WHERE timestamp >= ?`,
|
||||
@@ -705,6 +706,7 @@ export async function getChartData(period = "7d") {
|
||||
const idx = Math.min(Math.floor((t - startTime) / bucketMs), bucketCount - 1);
|
||||
buckets[idx].tokens += (r.promptTokens || 0) + (r.completionTokens || 0);
|
||||
buckets[idx].cost += r.cost || 0;
|
||||
buckets[idx].requests += 1;
|
||||
}
|
||||
return buckets;
|
||||
}
|
||||
@@ -727,6 +729,7 @@ export async function getChartData(period = "7d") {
|
||||
label: labelFn(d),
|
||||
tokens: dayData ? (dayData.promptTokens || 0) + (dayData.completionTokens || 0) : 0,
|
||||
cost: dayData ? (dayData.cost || 0) : 0,
|
||||
requests: dayData ? (dayData.requests || 0) : 0,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
@@ -18,6 +18,8 @@ import dynamic from "next/dynamic";
|
||||
// Lazy-load: keeps @xyflow/react out of the shared bundle until topology renders
|
||||
const ProviderTopology = dynamic(() => import("@/app/(dashboard)/dashboard/usage/components/ProviderTopology"), { ssr: false });
|
||||
import UsageChart from "@/app/(dashboard)/dashboard/usage/components/UsageChart";
|
||||
import ProviderBarChart from "@/app/(dashboard)/dashboard/usage/components/ProviderBarChart";
|
||||
import TopModelsChart from "@/app/(dashboard)/dashboard/usage/components/TopModelsChart";
|
||||
|
||||
function timeAgo(timestamp) {
|
||||
const diff = Math.floor((Date.now() - new Date(timestamp)) / 1000);
|
||||
@@ -483,6 +485,14 @@ export default function UsageStats({ period: periodProp, setPeriod: setPeriodPro
|
||||
{/* Token / Cost chart - sync period */}
|
||||
{loading ? spinner : <UsageChart period={period} />}
|
||||
|
||||
{/* Provider and model breakdown charts */}
|
||||
{!loading && (stats.byProvider || stats.byModel) && (
|
||||
<div className="grid min-w-0 grid-cols-1 gap-2 lg:grid-cols-2">
|
||||
<ProviderBarChart byProvider={stats.byProvider} />
|
||||
<TopModelsChart byModel={stats.byModel} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Table with dropdown selector */}
|
||||
<div className="flex flex-col gap-3">
|
||||
<div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
|
||||
|
||||
Reference in New Issue
Block a user