import useSWR from "swr"; import dayjs, { Dayjs } from "dayjs"; import useFetch from "../../hooks/useFetch"; import { LineChart } from '@mui/x-charts/LineChart'; import { CurveType } from '@mui/x-charts/models'; import { CircularProgress, Typography, Box } from "@mui/material"; interface DailyStats { date: string; latency: Record; input_tokens: Record; output_tokens: Record; time_took: Record; } interface OverallStats { total_chats: number; total_users: number; total_messages: { user: number; assistant: number; }; } type AnalyticsData = { daily: DailyStats[]; overall: OverallStats; }; interface TimeSeriesChartProps { data: DailyStats[]; metricKey: 'latency' | 'input_tokens' | 'output_tokens' | 'time_took'; title: string; percentiles: string[]; colors: string[]; yAxisTitle: string; } const StatOverview = ({ stats }: { stats: OverallStats }) => { return (
Overall {stats.total_chats} Conversations {stats.total_users} Users {stats.total_messages.user + stats.total_messages.assistant} Messages
); }; const TimeSeriesChart = ({ data, metricKey, title, percentiles, colors, yAxisTitle } : TimeSeriesChartProps) => { if (!data || !data.length) return null; const sortedData = [...data].sort((a, b) => new Date(a.date).getTime() - new Date(b.date).getTime()); const xAxisData = sortedData.map(item => item.date); const chartSeries = percentiles.map((percentile, index) => { const seriesData = sortedData.map(item => { if (item[metricKey] && typeof item[metricKey][percentile] === 'number') { return item[metricKey][percentile]; } return null; }); return { id: `percentile-${percentile}`, label: `${percentile} percentile`, curve: 'linear' as CurveType, data: seriesData, color: colors[index % colors.length], }; }); return (
{title} dayjs(value).format('MMM D'), scaleType: 'point', tickLabelStyle: { angle: 290, textAnchor: 'end', fontSize: 13, }, }]} yAxis={[{ id: "values", label: yAxisTitle, labelStyle: { transform: `rotate(270deg) translate(-80px, -175px)` }, }]} margin={{ left: 70, right: 20, top: 20, bottom: 80 }} />
); }; export const Statistics = ({ startDate, endDate }: { startDate: Dayjs | null; endDate: Dayjs | null }) => { const { fetcher } = useFetch(); const { data, isLoading } = useSWR( ["chat_analytics", startDate, endDate], async ([_, start, end]) => { const params: { start?: string; end?: string } = {}; if (start) params.start = (start as Dayjs).format('YYYY-MM-DD'); if (end) params.end = (end as Dayjs).format('YYYY-MM-DD'); const data: AnalyticsData = await fetcher(`/api/analytics/`, { method: "POST", body: JSON.stringify(params) }); return data; } ); const selectedPercentiles = ["50.0", "90.0", "99.0"]; const colors = ["#1976d2", "#8884d8", "#ff6384"]; if (isLoading || !data) { return (
); } return (
); };