🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
charting version 3 (#314)
Maximilian Deichmannd1d86bda4f46
diff --git a/src/__tests__/query-builder.servertest.ts b/src/__tests__/query-builder.servertest.tsindex aefac64590..1ef2660e27 100644--- a/src/__tests__/query-builder.servertest.ts+++ b/src/__tests__/query-builder.servertest.ts@@ -42,10 +42,7 @@ describe("Build valid SQL queries", () => {it(`should enrich mandatory filters ${prop.table}`, () => {const preparedQuery = enrichAndCreateQuery("project-id", {from: prop.table,- filter: [],- groupBy: [],select: [],- orderBy: [],});expect(preparedQuery.values).toEqual(prop.values);expect(preparedQuery.strings).toEqual(prop.strings);@@ -65,9 +62,8 @@ describe("Build valid SQL queries", () => {value: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",},],- groupBy: [],- select: [{ column: "traceId", agg: null }],- orderBy: [],++ select: [{ column: "traceId" }],});expect(preparedQuery.values).toEqual([@@ -87,8 +83,7 @@ describe("Build valid SQL queries", () => {},],groupBy: [{ type: "string", column: "version" }],- select: [{ column: "traceId", agg: null }],- orderBy: [],+ select: [{ column: "traceId" }],});expect(preparedQuery.values).toEqual([@@ -117,7 +112,6 @@ describe("Build valid SQL queries", () => {{ type: "datetime", column: "startTime", temporalUnit: "day" },],select: [{ column: "completionTokens", agg: "SUM" }],- orderBy: [],});expect(preparedQuery.values).toEqual([@@ -135,9 +129,7 @@ describe("Build valid SQL queries", () => {filter: [{ type: "string", column: "unknown", operator: "=", value: "" },],- groupBy: [],select: [],- orderBy: [],}),).toThrow("Column unknown not found");});@@ -146,10 +138,7 @@ describe("Build valid SQL queries", () => {expect(() =>createQuery({from: "traces",- filter: [],- groupBy: [],- select: [{ column: "unknown", agg: null }],- orderBy: [],+ select: [{ column: "unknown" }],}),).toThrow("Column unknown not found");});@@ -158,10 +147,8 @@ describe("Build valid SQL queries", () => {expect(() =>createQuery({from: "traces",- filter: [],groupBy: [{ column: "unknown", type: "string" }],select: [],- orderBy: [],}),).toThrow("Column unknown not found");});@@ -170,8 +157,6 @@ describe("Build valid SQL queries", () => {expect(() =>createQuery({from: "traces",- filter: [],- groupBy: [],select: [],orderBy: [{ column: "unknown", direction: "ASC" }],}),@@ -218,10 +203,7 @@ describe("Build valid SQL queries", () => {"7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",{from: "traces",- filter: [],- groupBy: [],- select: [{ column: "traceId", agg: null }],- orderBy: [],+ select: [{ column: "traceId" }],},);@@ -295,13 +277,11 @@ describe("Build valid SQL queries", () => {"7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",{from: "observations",- filter: [],groupBy: [{ type: "string", column: "name" }],select: [{ column: "completionTokens", agg: prop.agg as "SUM" | "AVG" },- { column: "name", agg: null },+ { column: "name" },],- orderBy: [],},);@@ -367,8 +347,8 @@ describe("Build valid SQL queries", () => {value: new Date("2021-01-04T00:00:00.000Z"),},],- groupBy: [],- select: [{ column: "completionTokens", agg: null }],++ select: [{ column: "completionTokens" }],orderBy: [{ column: "completionTokens", direction: "ASC" }],},);@@ -444,7 +424,6 @@ describe("Build valid SQL queries", () => {select: [{ column: "completionTokens", agg: prop.agg as "SUM" | "AVG" },],- orderBy: [],},);diff --git a/src/features/dashboard/components/BaseTimeSeriesChart.tsx b/src/features/dashboard/components/BaseTimeSeriesChart.tsxindex 1a9c7526cd..263ee09557 100644--- a/src/features/dashboard/components/BaseTimeSeriesChart.tsx+++ b/src/features/dashboard/components/BaseTimeSeriesChart.tsx@@ -1,12 +1,20 @@import { type DateTimeAggregationOption } from "@/src/features/dashboard/lib/timeseries-aggregation";import { numberFormatter } from "@/src/utils/numbers";+import { cn } from "@/src/utils/tailwind";import { AreaChart } from "@tremor/react";+export type TimeSeriesChartDataPoint = {+ ts: number;+ values: { label: string; value?: number }[];+};+export function BaseTimeSeriesChart(props: {+ className?: string;agg: DateTimeAggregationOption;- data: { ts: number; values: { label: string; value?: number }[] }[];+ data: TimeSeriesChartDataPoint[];showLegend?: boolean;connectNulls?: boolean;+ valueFormatter?: (value: number) => string;}) {const labels = new Set(props.data.flatMap((d) => d.values.map((v) => v.label)),@@ -16,9 +24,7 @@ export function BaseTimeSeriesChart(props: {[key: string]: number | undefined;};- function transformArray(- array: { ts: number; values: { label: string; value?: number }[] }[],- ): ChartInput[] {+ function transformArray(array: TimeSeriesChartDataPoint[]): ChartInput[] {return array.map((item) => {const outputObject: ChartInput = {timestamp: convertDate(item.ts, props.agg),@@ -50,15 +56,18 @@ export function BaseTimeSeriesChart(props: {};return (<AreaChart- className="mt-4 h-72"+ className={cn("mt-4", props.className)}data={transformArray(props.data)}index="timestamp"categories={Array.from(labels)}connectNulls={props.connectNulls}colors={["indigo", "cyan"]}- valueFormatter={numberFormatter}+ valueFormatter={+ props.valueFormatter ? props.valueFormatter : numberFormatter+ }noDataText="No data"showLegend={props.showLegend}+ showAnimation={true}/>);}diff --git a/src/features/dashboard/components/ChartScores.tsx b/src/features/dashboard/components/ChartScores.tsxnew file mode 100644index 0000000000..c2b2bd8cec--- /dev/null+++ b/src/features/dashboard/components/ChartScores.tsx@@ -0,0 +1,30 @@+import { api } from "@/src/utils/api";+import { type DateTimeAggregationOption } from "@/src/features/dashboard/lib/timeseries-aggregation";+import { BaseTimeSeriesChart } from "@/src/features/dashboard/components/BaseTimeSeriesChart";+import { DashboardCard } from "@/src/features/dashboard/components/cards/DashboardCard";++export function ChartScores(props: {+ className?: string;+ agg: DateTimeAggregationOption;+ projectId: string;+}) {+ const data = api.dashboard.scores.useQuery({+ agg: props.agg,+ projectId: props.projectId,+ });++ return (+ <DashboardCard+ className={props.className}+ title="Scores"+ description="Average"+ isLoading={data.isLoading}+ >+ <BaseTimeSeriesChart+ agg={props.agg}+ data={data.data ?? []}+ connectNulls+ />+ </DashboardCard>+ );+}diff --git a/src/features/dashboard/components/EventsCard.tsx b/src/features/dashboard/components/EventsCard.tsxdeleted file mode 100644index a00c73d2a2..0000000000--- a/src/features/dashboard/components/EventsCard.tsx+++ /dev/null@@ -1,189 +0,0 @@-import {- Card,- CardHeader,- CardTitle,- CardDescription,- CardContent,-} from "@/src/components/ui/card";-import { api } from "@/src/utils/api";-import { BaseTimeSeriesChart } from "@/src/features/dashboard/components/BaseTimeSeriesChart";-import {- dateTimeAggregationSettings,- type DateTimeAggregationOption,-} from "@/src/features/dashboard/lib/timeseries-aggregation";-import { type FilterState } from "@/src/features/filters/types";-import { Loader } from "lucide-react";--export const EventsCard = ({- projectId,- globalFilterState,- agg,-}: {- projectId: string;- globalFilterState: FilterState;- agg: DateTimeAggregationOption;-}) => {- const observations = api.dashboard.chart.useQuery({- projectId,- from: "observations",- select: [{ column: "observationId", agg: "COUNT" }],- filter: globalFilterState ?? [],- groupBy: [- {- type: "datetime",- column: "startTime",- temporalUnit: dateTimeAggregationSettings[agg].date_trunc,- },- ],- orderBy: [],- });-- const traces = api.dashboard.chart.useQuery({- projectId,- from: "traces",- select: [{ column: "traceId", agg: "COUNT" }],- filter:- globalFilterState.map((f) =>- f.type === "datetime" ? { ...f, column: "timestamp" } : f,- ) ?? [],- groupBy: [- {- type: "datetime",- column: "timestamp",- temporalUnit: dateTimeAggregationSettings[agg].date_trunc,- },- ],- orderBy: [],- });-- const scores = api.dashboard.chart.useQuery({- projectId,- from: "traces_scores",- select: [{ column: "scoreId", agg: "COUNT" }],- filter:- globalFilterState.map((f) =>- f.type === "datetime" ? { ...f, column: "timestamp" } : f,- ) ?? [],- groupBy: [- {- type: "datetime",- column: "timestamp",- temporalUnit: dateTimeAggregationSettings[agg].date_trunc,- },- ],- orderBy: [],- });-- const transformedObservations = observations.data- ? observations.data.map((item) => {- return {- ts: (item.startTime as Date).getTime(),- values: [- {- label: "Observations",- value:- typeof item.countObservationId === "number"- ? item.countObservationId- : undefined,- },- ],- };- })- : [];-- const transformedTraces = traces.data- ? traces.data.map((item) => {- return {- ts: (item.timestamp as Date).getTime(),- values: [- {- label: "Traces",- value:- typeof item.countTraceId === "number"- ? item.countTraceId- : undefined,- },- ],- };- })- : [];-- const transformedScores = scores.data- ? scores.data.map((item) => {- return {- ts: (item.timestamp as Date).getTime(),- values: [- {- label: "Scores",- value:- typeof item.countScoreId === "number"- ? item.countScoreId- : undefined,- },- ],- };- })- : [];-- return (- <div className="grid gap-4 xl:grid-cols-3">- <Card>- <CardHeader className="relative">- <CardTitle>Number of traces</CardTitle>- <CardDescription>Count</CardDescription>- {traces.isLoading ? (- <div className="absolute right-5 top-5 ">- <Loader className="h-5 w-5 animate-spin" />- </div>- ) : null}- </CardHeader>- <CardContent>- <BaseTimeSeriesChart- agg={agg}- data={transformedTraces ?? []}- connectNulls={true}- showLegend={false}- />- </CardContent>- </Card>- <Card>- <CardHeader className="relative">- <CardTitle>Number of observations</CardTitle>- <CardDescription>Count</CardDescription>- {observations.isLoading ? (- <div className="absolute right-5 top-5 ">- <Loader className="h-5 w-5 animate-spin" />- </div>- ) : null}- </CardHeader>- <CardContent>- <BaseTimeSeriesChart- agg={agg}- data={transformedObservations ?? []}- connectNulls={true}- showLegend={false}- />- </CardContent>- </Card>- <Card>- <CardHeader className="relative">- <CardTitle>Number of scores</CardTitle>- <CardDescription>Count</CardDescription>- {scores.isLoading ? (- <div className="absolute right-5 top-5 ">- <Loader className="h-5 w-5 animate-spin" />- </div>- ) : null}- </CardHeader>- <CardContent>- <BaseTimeSeriesChart- agg={agg}- data={transformedScores ?? []}- connectNulls={true}- showLegend={false}- />- </CardContent>- </Card>- </div>- );-};diff --git a/src/features/dashboard/components/LatencyChart.tsx b/src/features/dashboard/components/LatencyChart.tsxindex 12e8bf69be..a2c201d1ca 100644--- a/src/features/dashboard/components/LatencyChart.tsx+++ b/src/features/dashboard/components/LatencyChart.tsx@@ -1,29 +1,24 @@-import {- Card,- CardHeader,- CardTitle,- CardDescription,- CardContent,-} from "@/src/components/ui/card";import { api } from "@/src/utils/api";-import { BaseTimeSeriesChart } from "@/src/features/dashboard/components/BaseTimeSeriesChart";import {dateTimeAggregationSettings,type DateTimeAggregationOption,} from "@/src/features/dashboard/lib/timeseries-aggregation";import { type FilterState } from "@/src/features/filters/types";-import { Loader } from "lucide-react";import {getAllModels,reduceData,transformMapAndFillZeroValues,} from "@/src/features/dashboard/components/hooks";+import { DashboardCard } from "@/src/features/dashboard/components/cards/DashboardCard";+import { BaseTimeSeriesChart } from "@/src/features/dashboard/components/BaseTimeSeriesChart";export const LatencyChart = ({+ className,projectId,globalFilterState,agg,}: {+ className?: string;projectId: string;globalFilterState: FilterState;agg: DateTimeAggregationOption;@@ -31,10 +26,7 @@ export const LatencyChart = ({const data = api.dashboard.chart.useQuery({projectId,from: "observations",- select: [- { column: "duration", agg: "AVG" },- { column: "model", agg: null },- ],+ select: [{ column: "duration", agg: "AVG" }, { column: "model" }],filter:[...globalFilterState,@@ -48,7 +40,6 @@ export const LatencyChart = ({},{ type: "string", column: "model" },],- orderBy: [],});const allModels = getAllModels(projectId, globalFilterState);@@ -62,25 +53,17 @@ export const LatencyChart = ({: [];return (- <Card>- <CardHeader className="relative">- <CardTitle>Model latencies</CardTitle>- <CardDescription>- Average latency (ms) per LLM generation- </CardDescription>- {data.isLoading ? (- <div className="absolute right-5 top-5 ">- <Loader className="h-5 w-5 animate-spin" />- </div>- ) : null}- </CardHeader>- <CardContent>- <BaseTimeSeriesChart- agg={agg}- data={transformedData ?? []}- connectNulls={true}- />- </CardContent>- </Card>+ <DashboardCard+ className={className}+ title="Model latencies"+ description="Average latency (ms) per LLM generation"+ isLoading={data.isLoading}+ >+ <BaseTimeSeriesChart+ agg={agg}+ data={transformedData ?? []}+ connectNulls={true}+ />+ </DashboardCard>);};diff --git a/src/features/dashboard/components/MetricTable.tsx b/src/features/dashboard/components/MetricTable.tsxnew file mode 100644index 0000000000..62e46c737a--- /dev/null+++ b/src/features/dashboard/components/MetricTable.tsx@@ -0,0 +1,95 @@+import { api } from "@/src/utils/api";+import { type FilterState } from "@/src/features/filters/types";+import { TotalMetric } from "./TotalMetric";+import { numberFormatter, usdFormatter } from "@/src/utils/numbers";+import { DashboardTable } from "@/src/features/dashboard/components/cards/DashboardTable";+import { RightAlignedCell } from "@/src/features/dashboard/components/RightAlignedCell";+import { DashboardCard } from "@/src/features/dashboard/components/cards/DashboardCard";+import { ExpandListButton } from "@/src/features/dashboard/components/cards/ChevronButton";+import { useState } from "react";++export const MetricTable = ({+ className,+ projectId,+ globalFilterState,+}: {+ className: string;+ projectId: string;+ globalFilterState: FilterState;+}) => {+ const [isExpanded, setIsExpanded] = useState(false);+ const localFilters = globalFilterState.map((f) => ({+ ...f,+ column: "timestamp",+ }));++ const metrics = api.dashboard.chart.useQuery({+ projectId,+ from: "traces_observations",+ select: [+ { column: "totalTokenCost" },+ { column: "totalTokens", agg: "SUM" },+ { column: "model" },+ ],+ filter: localFilters ?? [],+ groupBy: [{ type: "string", column: "model" }],+ orderBy: [{ column: "totalTokenCost", direction: "DESC" }],+ });++ const totalTokens = metrics.data?.reduce(+ (acc, curr) =>+ acc + (curr.totalTokenCost ? (curr.totalTokenCost as number) : 0),+ 0,+ );++ const metricsData = metrics.data+ ? metrics.data+ .filter((item) => item.model !== null)+ .map((item, i) => [+ item.model as string,+ <RightAlignedCell key={i}>+ {item.sumTotalTokens+ ? numberFormatter(item.sumTotalTokens as number)+ : "0"}+ </RightAlignedCell>,+ <RightAlignedCell key={i}>+ {item.totalTokenCost+ ? usdFormatter(item.totalTokenCost as number)+ : "$0"}+ </RightAlignedCell>,+ ])+ : [];++ const maxNumberOfEntries = 5;+ const expandedMetricsData = isExpanded+ ? metricsData+ : metricsData.slice(0, maxNumberOfEntries);++ return (+ <DashboardCard+ className={className}+ title="Model costs"+ isLoading={metrics.isLoading}+ >+ <DashboardTable+ headers={[+ "Model",+ <RightAlignedCell key={1}>Total tokens</RightAlignedCell>,+ <RightAlignedCell key={1}>Total cost</RightAlignedCell>,+ ]}+ rows={expandedMetricsData}+ >+ <TotalMetric+ metric={totalTokens ? usdFormatter(totalTokens) : "$0"}+ description="Total cost"+ />+ </DashboardTable>+ <ExpandListButton+ isExpanded={isExpanded}+ setExpanded={setIsExpanded}+ totalLength={metricsData.length}+ maxLength={maxNumberOfEntries}+ />+ </DashboardCard>+ );+};diff --git a/src/features/dashboard/components/ModelUsageChart.tsx b/src/features/dashboard/components/ModelUsageChart.tsxnew file mode 100644index 0000000000..bb7cd61919--- /dev/null+++ b/src/features/dashboard/components/ModelUsageChart.tsx@@ -0,0 +1,129 @@+import { api } from "@/src/utils/api";++import {+ dateTimeAggregationSettings,+ type DateTimeAggregationOption,+} from "@/src/features/dashboard/lib/timeseries-aggregation";+import { type FilterState } from "@/src/features/filters/types";++import {+ getAllModels,+ reduceData,+ transformMapAndFillZeroValues,+} from "@/src/features/dashboard/components/hooks";+import { DashboardCard } from "@/src/features/dashboard/components/cards/DashboardCard";+import { numberFormatter, usdFormatter } from "@/src/utils/numbers";+import { TabComponent } from "@/src/features/dashboard/components/TabsComponent";+import { BaseTimeSeriesChart } from "@/src/features/dashboard/components/BaseTimeSeriesChart";+import { TotalMetric } from "@/src/features/dashboard/components/TotalMetric";++export const ModelUsageChart = ({+ className,+ projectId,+ globalFilterState,+ agg,+}: {+ className?: string;+ projectId: string;+ globalFilterState: FilterState;+ agg: DateTimeAggregationOption;+}) => {+ const tokens = api.dashboard.chart.useQuery({+ projectId,+ from: "observations",+ select: [+ { column: "totalTokens", agg: "SUM" },+ { column: "totalTokenCost" },+ { column: "model" },+ ],+ filter: globalFilterState ?? [],+ groupBy: [+ {+ type: "datetime",+ column: "startTime",+ temporalUnit: dateTimeAggregationSettings[agg].date_trunc,+ },+ {+ type: "string",+ column: "model",+ },+ ],+ orderBy: [{ column: "totalTokenCost", direction: "DESC" }],+ });++ const allModels = getAllModels(projectId, globalFilterState);++ const transformedTotalTokens =+ tokens.data && allModels+ ? transformMapAndFillZeroValues(+ reduceData(tokens.data, "sumTotalTokens"),+ allModels,+ )+ : [];++ const transformedModelCost =+ tokens.data && allModels+ ? transformMapAndFillZeroValues(+ reduceData(tokens.data, "totalTokenCost"),+ allModels,+ )+ : [];++ const totalCost = tokens.data?.reduce(+ (acc, curr) => acc + (curr.totalTokenCost as number),+ 0,+ );++ const totalTokens = tokens.data?.reduce(+ (acc, curr) => acc + (curr.sumTotalTokens as number),+ 0,+ );++ const data = [+ {+ tabTitle: "Total cost",+ data: transformedModelCost,+ totalMetric: totalCost ? usdFormatter(totalCost) : "-",+ metricDescription: `Token cost per ${dateTimeAggregationSettings[agg].date_trunc}`,+ formatter: usdFormatter,+ },+ {+ tabTitle: "Total tokens",+ data: transformedTotalTokens,+ totalMetric: totalTokens ? numberFormatter(totalTokens) : "-",+ metricDescription: `Token count per ${dateTimeAggregationSettings[agg].date_trunc}`,+ },+ ];++ return (+ <DashboardCard+ className={className}+ title={"Model Usage"}+ isLoading={tokens.isLoading}+ >+ <TabComponent+ tabs={data.map((item) => {+ return {+ tabTitle: item.tabTitle,+ totalMetric: item.totalMetric,+ metricDescription: item.metricDescription,+ content: (+ <>+ <TotalMetric+ metric={item.totalMetric}+ description={item.metricDescription}+ />+ <BaseTimeSeriesChart+ agg={agg}+ data={item.data}+ showLegend={true}+ valueFormatter={item.formatter}+ />+ </>+ ),+ };+ })}+ />+ </DashboardCard>+ );+};diff --git a/src/features/dashboard/components/NoData.tsx b/src/features/dashboard/components/NoData.tsxnew file mode 100644index 0000000000..af5b0058f2--- /dev/null+++ b/src/features/dashboard/components/NoData.tsx@@ -0,0 +1,16 @@+import { Flex, Text } from "@tremor/react";++interface NoDataProps {+ noDataText?: string;+}+export const NoData = ({ noDataText = "No data" }: NoDataProps) => {+ return (+ <Flex+ alignItems="center"+ justifyContent="center"+ className="mt-5 min-h-[9rem] w-full rounded-tremor-default border border-dashed border-tremor-border"+ >+ <Text className="text-tremor-content">{noDataText}</Text>+ </Flex>+ );+};diff --git a/src/features/dashboard/components/ReleaseTable.tsx b/src/features/dashboard/components/ReleaseTable.tsxdeleted file mode 100644index 19f8c9b977..0000000000--- a/src/features/dashboard/components/ReleaseTable.tsx+++ /dev/null@@ -1,105 +0,0 @@-import Header from "@/src/components/layouts/header";-import {- Card,- CardHeader,- CardTitle,- CardDescription,- CardContent,-} from "@/src/components/ui/card";-import { api } from "@/src/utils/api";-import { type FilterState } from "@/src/features/filters/types";-import {- Table,- TableBody,- TableCaption,- TableCell,- TableHead,- TableHeader,- TableRow,-} from "@/src/components/ui/table";-import { Loader } from "lucide-react";-import { numberFormatter } from "@/src/utils/numbers";--export const ReleaseTable = ({- projectId,- globalFilterState,-}: {- projectId: string;- globalFilterState: FilterState;-}) => {- const data = api.dashboard.chart.useQuery({- projectId,- from: "traces_parent_observation_scores",- select: [- { column: "value", agg: "AVG" },- { column: "release", agg: null },- { column: "value", agg: "COUNT" },- { column: "scoreName", agg: null },- { column: "duration", agg: "AVG" },- ],- filter:- globalFilterState.map((f) => ({- ...f,- column: "timestamp",- })) ?? [],- groupBy: [- { type: "string", column: "release" },- { type: "string", column: "scoreName" },- ],- orderBy: [{ column: "release", direction: "DESC" }],- });-- return (- <div className="md:container">- <Header title="Releases" />- <Card>- <CardHeader className="relative">- <CardTitle>Releases</CardTitle>- <CardDescription>Count</CardDescription>- {data.isLoading ? (- <div className="absolute right-5 top-5 ">- <Loader className="h-5 w-5 animate-spin" />- </div>- ) : null}- </CardHeader>- <CardContent>- <Table>- <TableCaption>A list of your recent releases.</TableCaption>- <TableHeader>- <TableRow>- <TableHead className="w-[100px]">Release</TableHead>- <TableHead className="w-[100px]">Score Name</TableHead>- <TableHead>Average Score</TableHead>- <TableHead>Number of traces</TableHead>- <TableHead className="text-right">- Average duration (ms)- </TableHead>- </TableRow>- </TableHeader>- <TableBody>- {data.data?.map((row) => (- <TableRow- key={(row.release as string) + "-" + (row.name as string)}- >- <TableCell className="font-medium">- {row.release ? (row.release as string) : "-"}- </TableCell>- <TableCell className="font-medium">- {row.name as string}- </TableCell>- <TableCell>- {numberFormatter(row.avgValue as number)}- </TableCell>- <TableCell>{row.countValue as number}</TableCell>- <TableCell className="text-right">- {numberFormatter(row.avgDuration as number)}- </TableCell>- </TableRow>- ))}- </TableBody>- </Table>- </CardContent>- </Card>- </div>- );-};diff --git a/src/features/dashboard/components/RightAlignedCell.tsx b/src/features/dashboard/components/RightAlignedCell.tsxnew file mode 100644index 0000000000..c5305a74a3--- /dev/null+++ b/src/features/dashboard/components/RightAlignedCell.tsx@@ -0,0 +1,18 @@+import { type ReactNode } from "react";+import { cn } from "@/src/utils/tailwind";++export const RightAlignedCell = ({+ children,+ className,+ key,+}: {+ children: ReactNode;+ className?: string;+ key: number;+}) => {+ return (+ <div className={cn("mr-2 text-right", className)} key={key}>+ {children}+ </div>+ );+};diff --git a/src/features/dashboard/components/ScoresTable.tsx b/src/features/dashboard/components/ScoresTable.tsxnew file mode 100644index 0000000000..e4248701ca--- /dev/null+++ b/src/features/dashboard/components/ScoresTable.tsx@@ -0,0 +1,156 @@+import { api } from "@/src/utils/api";+import { type FilterState } from "@/src/features/filters/types";+import { TotalMetric } from "./TotalMetric";+import { numberFormatter } from "@/src/utils/numbers";+import { DashboardTable } from "@/src/features/dashboard/components/cards/DashboardTable";+import { ExpandListButton } from "./cards/ChevronButton";+import { DashboardCard } from "@/src/features/dashboard/components/cards/DashboardCard";+import { NoData } from "@/src/features/dashboard/components/NoData";+import { RightAlignedCell } from "./RightAlignedCell";+import { useState } from "react";++export const ScoresTable = ({+ className,+ projectId,+ globalFilterState,+}: {+ className: string;+ projectId: string;+ globalFilterState: FilterState;+}) => {+ const [isExpanded, setIsExpanded] = useState(false);+ const localFilters = globalFilterState.map((f) => ({+ ...f,+ column: "timestamp",+ }));++ const metrics = api.dashboard.chart.useQuery({+ projectId,+ from: "traces_scores",+ select: [+ { column: "scoreName" },+ { column: "scoreId", agg: "COUNT" },+ { column: "value", agg: "AVG" },+ ],+ filter: localFilters ?? [],+ groupBy: [{ type: "string", column: "scoreName" }],+ orderBy: [{ column: "scoreId", direction: "DESC", agg: "COUNT" }],+ });++ const [zeroValueScores, oneValueScores] = [0, 1].map((i) =>+ api.dashboard.chart.useQuery({+ projectId,+ from: "traces_scores",+ select: [{ column: "scoreName" }, { column: "scoreId", agg: "COUNT" }],+ filter:+ [+ ...localFilters,+ {+ column: "value",+ operator: "=",+ value: i,+ type: "number",+ },+ ] ?? [],+ groupBy: [{ type: "string", column: "scoreName" }],+ orderBy: [{ column: "scoreId", direction: "DESC", agg: "COUNT" }],+ }),+ );++ if (!zeroValueScores || !oneValueScores) {+ return (+ <DashboardCard title={"Scores"} isLoading={false}>+ <NoData noDataText="No data" />+ </DashboardCard>+ );+ }++ const joinRequestData = () => {+ if (!metrics.data || !zeroValueScores.data || !oneValueScores.data)+ return [];++ return metrics.data.map((metric) => {+ const scoreName = metric.scoreName as string;++ const zeroValueScore = zeroValueScores.data.find(+ (item) => item.scoreName === scoreName,+ );+ const oneValueScore = oneValueScores.data.find(+ (item) => item.scoreName === scoreName,+ );++ return {+ scoreName: metric.scoreName as string,+ countScoreId: metric.countScoreId ? metric.countScoreId : 0,+ avgValue: metric.avgValue ? (metric.avgValue as number) : 0,+ zeroValueScore: zeroValueScore?.countScoreId+ ? zeroValueScore.countScoreId+ : 0,+ oneValueScore: oneValueScore?.countScoreId+ ? (oneValueScore.countScoreId as number)+ : 0,+ };+ });+ };++ const maxNumberOfEntries = 5;+ const joinedData = joinRequestData();+ const adjustedData = isExpanded+ ? joinedData+ : joinedData.slice(0, maxNumberOfEntries);++ const totalScores = joinedData.reduce(+ (acc, curr) => acc + (curr.countScoreId as number),+ 0,+ );++ return (+ <DashboardCard+ className={className}+ title="Scores"+ isLoading={+ metrics.isLoading ||+ zeroValueScores.isLoading ||+ oneValueScores.isLoading+ }+ >+ <DashboardTable+ headers={[+ "Name",+ <RightAlignedCell key={1}>Count</RightAlignedCell>,+ <RightAlignedCell key={1}>Average</RightAlignedCell>,+ <RightAlignedCell key={1}>0</RightAlignedCell>,+ <RightAlignedCell key={1}>1</RightAlignedCell>,+ ]}+ rows={+ adjustedData.map((item, i) => [+ item.scoreName,+ <RightAlignedCell key={i}>+ {numberFormatter(item.countScoreId as number)}+ </RightAlignedCell>,+ <RightAlignedCell key={i}>+ {numberFormatter(item.avgValue)}+ </RightAlignedCell>,+ <RightAlignedCell key={i}>+ {numberFormatter(item.zeroValueScore as number)}+ </RightAlignedCell>,+ <RightAlignedCell key={i}>+ {numberFormatter(item.oneValueScore)}+ </RightAlignedCell>,+ ]) ?? []+ }+ >+ <TotalMetric+ metric={totalScores ? numberFormatter(totalScores) : "0"}+ description="Total scores tracked"+ />+ </DashboardTable>+ <ExpandListButton+ isExpanded={isExpanded}+ setExpanded={setIsExpanded}+ totalLength={joinedData.length}+ maxLength={maxNumberOfEntries}+ />+ </DashboardCard>+ );+};diff --git a/src/features/dashboard/components/TabTimeSeriesChart.tsx b/src/features/dashboard/components/TabTimeSeriesChart.tsxnew file mode 100644index 0000000000..18ff1fd806--- /dev/null+++ b/src/features/dashboard/components/TabTimeSeriesChart.tsx@@ -0,0 +1,61 @@+import {+ BaseTimeSeriesChart,+ type TimeSeriesChartDataPoint,+} from "@/src/features/dashboard/components/BaseTimeSeriesChart";+import { TotalMetric } from "@/src/features/dashboard/components/TotalMetric";+import { type DateTimeAggregationOption } from "@/src/features/dashboard/lib/timeseries-aggregation";+import { Tab, TabList, TabGroup, TabPanel, TabPanels } from "@tremor/react";++import { type ReactNode, useState } from "react";++export type BaseTabTimeseriesChartProps = {+ agg: DateTimeAggregationOption;+ showLegend?: boolean;+ connectNulls?: boolean;+ data: {+ totalMetric: ReactNode;+ metricDescription: ReactNode;+ tabTitle: string;+ formatter?: (value: number) => string;+ data: TimeSeriesChartDataPoint[];+ }[];+};++export const BaseTabTimeseriesChart = (props: BaseTabTimeseriesChartProps) => {+ const [selectedIndex, setSelectedIndex] = useState(0);++ return (+ <div className="flex flex-col justify-between">+ <TotalMetric+ metric={props.data[selectedIndex]?.totalMetric}+ description={props.data[selectedIndex]?.metricDescription}+ />+ <TabGroup+ className="mt-4"+ index={selectedIndex}+ onIndexChange={(i) => setSelectedIndex(i)}+ defaultIndex={0}+ >+ <TabList className="h-10">+ {props.data.map((data, index) => (+ <Tab tabIndex={index} key={index}>+ {data.tabTitle}+ </Tab>+ ))}+ </TabList>+ <TabPanels>+ {props.data.map((data, index) => (+ <TabPanel key={index}>+ <BaseTimeSeriesChart+ agg={props.agg}+ data={data.data}+ showLegend={true}+ valueFormatter={data.formatter}+ />+ </TabPanel>+ ))}+ </TabPanels>+ </TabGroup>+ </div>+ );+};diff --git a/src/features/dashboard/components/TabsComponent.tsx b/src/features/dashboard/components/TabsComponent.tsxnew file mode 100644index 0000000000..3ba52b4272--- /dev/null+++ b/src/features/dashboard/components/TabsComponent.tsx@@ -0,0 +1,56 @@+import { cn } from "@/src/utils/tailwind";+import { type ReactNode, useState } from "react";++export type TabComponentProps = {+ tabs: {+ tabTitle: string;+ content: ReactNode;+ totalMetric: string;+ metricDescription: string;+ }[];+};++export const TabComponent = ({ tabs }: TabComponentProps) => {+ const [selectedIndex, setSelectedIndex] = useState(0);+ return (+ <div>+ <div className="sm:hidden">+ <label htmlFor="tabs" className="sr-only">+ Select a tab+ </label>+ <select+ id="tabs"+ name="tabs"+ className="block w-full rounded-md border-gray-300 py-2 pl-3 pr-10 text-base focus:border-indigo-500 focus:outline-none focus:ring-indigo-500 sm:text-sm"+ defaultValue={0}+ >+ {tabs.map((tab) => (+ <option key={tab.tabTitle}>{tab.tabTitle}</option>+ ))}+ </select>+ </div>+ <div className="hidden sm:block">+ <div className="border-b border-gray-200">+ <nav className="-mb-px flex space-x-8" aria-label="Tabs">+ {tabs.map((tab, index) => (+ <a+ key={tab.tabTitle}+ className={cn(+ index === selectedIndex+ ? "border-indigo-500 text-indigo-600"+ : "border-transparent text-gray-500 hover:border-gray-300 hover:text-gray-700",+ "whitespace-nowrap border-b-2 px-1 py-3 text-sm font-medium",+ )}+ aria-current={index === selectedIndex ? "page" : undefined}+ onClick={() => setSelectedIndex(index)}+ >+ {tab.tabTitle}+ </a>+ ))}+ </nav>+ </div>+ </div>+ <div className="mt-6">{tabs[selectedIndex]?.content}</div>+ </div>+ );+};diff --git a/src/features/dashboard/components/TokenChart.tsx b/src/features/dashboard/components/TokenChart.tsxdeleted file mode 100644index af730e1347..0000000000--- a/src/features/dashboard/components/TokenChart.tsx+++ /dev/null@@ -1,133 +0,0 @@-import {- Card,- CardHeader,- CardTitle,- CardDescription,- CardContent,-} from "@/src/components/ui/card";-import { api } from "@/src/utils/api";-import { BaseTimeSeriesChart } from "@/src/features/dashboard/components/BaseTimeSeriesChart";-import {- dateTimeAggregationSettings,- type DateTimeAggregationOption,-} from "@/src/features/dashboard/lib/timeseries-aggregation";-import { type FilterState } from "@/src/features/filters/types";-import { Loader } from "lucide-react";-import {- getAllModels,- reduceData,- transformMapAndFillZeroValues,-} from "@/src/features/dashboard/components/hooks";--export const TokenChart = ({- projectId,- globalFilterState,- agg,-}: {- projectId: string;- globalFilterState: FilterState;- agg: DateTimeAggregationOption;-}) => {- const totalTokens = api.dashboard.chart.useQuery({- projectId,- from: "observations",- select: [- { column: "totalTokens", agg: "SUM" },- { column: "model", agg: null },- ],- filter: globalFilterState ?? [],- groupBy: [- {- type: "datetime",- column: "startTime",- temporalUnit: dateTimeAggregationSettings[agg].date_trunc,- },- {- type: "string",- column: "model",- },- ],- orderBy: [],- });-- const modelCost = api.dashboard.chart.useQuery({- projectId,- from: "observations",- select: [- { column: "totalTokenCost", agg: null },- { column: "model", agg: null },- ],- filter: globalFilterState ?? [],- groupBy: [- {- type: "datetime",- column: "startTime",- temporalUnit: dateTimeAggregationSettings[agg].date_trunc,- },- {- type: "string",- column: "model",- },- ],- orderBy: [],- });-- const allModels = getAllModels(projectId, globalFilterState);-- const transformedTotalTokens =- totalTokens.data && allModels- ? transformMapAndFillZeroValues(- reduceData(totalTokens.data, "sumTotalTokens"),- allModels,- )- : [];-- const transformedModelCost =- modelCost.data && allModels- ? transformMapAndFillZeroValues(- reduceData(modelCost.data, "totalTokenCost"),- allModels,- )- : [];-- return (- <div className="grid gap-4 xl:grid-cols-2">- <Card>- <CardHeader className="relative">- <CardTitle>Number of tokens</CardTitle>- <CardDescription>Count</CardDescription>- {totalTokens.isLoading ? (- <div className="absolute right-5 top-5 ">- <Loader className="h-5 w-5 animate-spin" />- </div>- ) : null}- </CardHeader>- <CardContent>- <BaseTimeSeriesChart- agg={agg}- data={transformedTotalTokens ?? []}- connectNulls={true}- />- </CardContent>- </Card>- <Card>- <CardHeader className="relative">- <CardTitle>Model cost</CardTitle>- <CardDescription>USD</CardDescription>- {totalTokens.isLoading ? (- <div className="absolute right-5 top-5 ">- <Loader className="h-5 w-5 animate-spin" />- </div>- ) : null}- </CardHeader>- <CardContent>- <BaseTimeSeriesChart- agg={agg}- data={transformedModelCost ?? []}- connectNulls={true}- />- </CardContent>- </Card>- </div>- );-};diff --git a/src/features/dashboard/components/TotalMetric.tsx b/src/features/dashboard/components/TotalMetric.tsxnew file mode 100644index 0000000000..d5104a3023--- /dev/null+++ b/src/features/dashboard/components/TotalMetric.tsx@@ -0,0 +1,24 @@+import { cn } from "@/src/utils/tailwind";+import { Flex, Metric, Text } from "@tremor/react";+import { type ReactNode } from "react";++export const TotalMetric = ({+ className,+ metric,+ description,+}: {+ className?: string;+ metric: ReactNode;+ description?: ReactNode;+}) => {+ return (+ <Flex+ justifyContent="start"+ alignItems="baseline"+ className={cn("space-x-2 animate-in", className)}+ >+ <Metric>{metric}</Metric>+ <Text>{description}</Text>+ </Flex>+ );+};diff --git a/src/features/dashboard/components/TracesChart.tsx b/src/features/dashboard/components/TracesChart.tsxnew file mode 100644index 0000000000..3f4c2619ef--- /dev/null+++ b/src/features/dashboard/components/TracesChart.tsx@@ -0,0 +1,78 @@+import { api } from "@/src/utils/api";+import { type FilterState } from "@/src/features/filters/types";+import BarChartCard from "@/src/features/dashboard/components/cards/BarChartCard";+import { ExpandListButton } from "@/src/features/dashboard/components/cards/ChevronButton";+import { useState } from "react";++export const TracesBarListChart = ({+ className,+ projectId,+ globalFilterState,+}: {+ className?: string;+ projectId: string;+ globalFilterState: FilterState;+}) => {+ const [isExpanded, setIsExpanded] = useState(false);+ const timeFilter =+ globalFilterState.map((f) =>+ f.type === "datetime" ? { ...f, column: "timestamp" } : f,+ ) ?? [];++ const totalTraces = api.dashboard.chart.useQuery({+ projectId,+ from: "traces",+ select: [{ column: "traceId", agg: "COUNT" }],+ filter: timeFilter,+ });++ const traces = api.dashboard.chart.useQuery({+ projectId,+ from: "traces",+ select: [{ column: "traceId", agg: "COUNT" }, { column: "traceName" }],+ filter: timeFilter,+ groupBy: [{ column: "traceName", type: "string" }],+ orderBy: [{ column: "traceId", direction: "DESC", agg: "COUNT" }],+ });++ const transformedTraces = traces.data+ ? traces.data.map((item) => {+ return {+ name: item.traceName ? (item.traceName as string) : "Unknown",+ value: item.countTraceId as number,+ };+ })+ : [];++ const maxNumberOfEntries = 5;++ const adjustedData = isExpanded+ ? transformedTraces+ : transformedTraces.slice(0, maxNumberOfEntries);++ return (+ <>+ <BarChartCard+ className={className}+ header={{+ metric: "Total traces tracked",+ stat: (totalTraces.data?.[0]?.countTraceId as number) ?? 0,+ category: "Traces",+ }}+ isLoading={traces.isLoading || totalTraces.isLoading}+ chart={{+ data: adjustedData,+ header: "Trace Name",+ metric: "Count",+ }}+ >+ <ExpandListButton+ isExpanded={isExpanded}+ setExpanded={setIsExpanded}+ totalLength={transformedTraces.length}+ maxLength={maxNumberOfEntries}+ />+ </BarChartCard>+ </>+ );+};diff --git a/src/features/dashboard/components/TracesTimeSeriesChart.tsx b/src/features/dashboard/components/TracesTimeSeriesChart.tsxnew file mode 100644index 0000000000..26d8f54cf9--- /dev/null+++ b/src/features/dashboard/components/TracesTimeSeriesChart.tsx@@ -0,0 +1,80 @@+import { api } from "@/src/utils/api";+import {+ dateTimeAggregationSettings,+ type DateTimeAggregationOption,+} from "@/src/features/dashboard/lib/timeseries-aggregation";+import { type FilterState } from "@/src/features/filters/types";+import { DashboardCard } from "@/src/features/dashboard/components/cards/DashboardCard";+import { BaseTimeSeriesChart } from "@/src/features/dashboard/components/BaseTimeSeriesChart";+import { TotalMetric } from "@/src/features/dashboard/components/TotalMetric";+import { numberFormatter } from "@/src/utils/numbers";++export const TracesTimeSeriesChart = ({+ className,+ projectId,+ globalFilterState,+ agg,+}: {+ className?: string;+ projectId: string;+ globalFilterState: FilterState;+ agg: DateTimeAggregationOption;+}) => {+ const traces = api.dashboard.chart.useQuery({+ projectId,+ from: "traces",+ select: [{ column: "traceId", agg: "COUNT" }],+ filter:+ globalFilterState.map((f) =>+ f.type === "datetime" ? { ...f, column: "timestamp" } : f,+ ) ?? [],+ groupBy: [+ {+ type: "datetime",+ column: "timestamp",+ temporalUnit: dateTimeAggregationSettings[agg].date_trunc,+ },+ ],+ });++ const transformedTraces = traces.data+ ? traces.data.map((item) => {+ return {+ ts: (item.timestamp as Date).getTime(),+ values: [+ {+ label: "Traces",+ value:+ typeof item.countTraceId === "number"+ ? item.countTraceId+ : undefined,+ },+ ],+ };+ })+ : [];++ const total = traces.data?.reduce((acc, item) => {+ return acc + (item.countTraceId as number);+ }, 0);++ return (+ <DashboardCard+ className={className}+ title="Traces"+ isLoading={traces.isLoading}+ cardContentClassName="flex flex-col content-end "+ >+ <TotalMetric+ description={`Traces tracked per ${dateTimeAggregationSettings[agg].date_trunc}`}+ metric={total ? numberFormatter(total) : "-"}+ />+ <BaseTimeSeriesChart+ className="min-h-80 lg:h-full"+ agg={agg}+ data={transformedTraces ?? []}+ connectNulls={true}+ />+ </DashboardCard>+ );+};diff --git a/src/features/dashboard/components/UserChart.tsx b/src/features/dashboard/components/UserChart.tsxnew file mode 100644index 0000000000..7dab131773--- /dev/null+++ b/src/features/dashboard/components/UserChart.tsx@@ -0,0 +1,159 @@+import { api } from "@/src/utils/api";+import { type DateTimeAggregationOption } from "@/src/features/dashboard/lib/timeseries-aggregation";+import { type FilterState } from "@/src/features/filters/types";+import { DashboardCard } from "@/src/features/dashboard/components/cards/DashboardCard";+import { numberFormatter, usdFormatter } from "@/src/utils/numbers";+import { TabComponent } from "@/src/features/dashboard/components/TabsComponent";+import { BarList } from "@tremor/react";+import { isNotUndefinedOrNull } from "@/src/utils/types";+import { type BarChartDataPoint } from "@/src/features/dashboard/components/cards/BarChartCard";+import { TotalMetric } from "@/src/features/dashboard/components/TotalMetric";+import { ExpandListButton } from "@/src/features/dashboard/components/cards/ChevronButton";+import { useState } from "react";++export const UserChart = ({+ className,+ projectId,+ globalFilterState,+}: {+ className?: string;+ projectId: string;+ globalFilterState: FilterState;+ agg: DateTimeAggregationOption;+}) => {+ const [isExpanded, setIsExpanded] = useState(false);+ const user = api.dashboard.chart.useQuery({+ projectId,+ from: "traces_observations",+ select: [+ { column: "totalTokenCost" },+ { column: "user" },+ { column: "traceId", agg: "COUNT" },+ ],+ filter: globalFilterState ?? [],+ groupBy: [+ {+ type: "string",+ column: "user",+ },+ ],+ orderBy: [{ column: "totalTokenCost", direction: "DESC" }],+ });++ const traces = api.dashboard.chart.useQuery({+ projectId,+ from: "traces",+ select: [{ column: "user" }, { column: "traceId", agg: "COUNT" }],+ filter:+ globalFilterState.map((f) => ({+ ...f,+ column: "timestamp",+ })) ?? [],+ groupBy: [+ {+ type: "string",+ column: "user",+ },+ ],+ orderBy: [{ column: "traceId", agg: "COUNT", direction: "DESC" }],+ });++ const transformedNumberOfTraces: BarChartDataPoint[] = traces.data+ ? traces.data+ .filter((item) => item.user !== undefined)+ .map((item) => {+ return {+ name: item.user as string,+ value: item.countTraceId ? (item.countTraceId as number) : 0,+ };+ })+ : [];++ const transformedCost: BarChartDataPoint[] = user.data+ ? user.data+ .filter((item) => item.user !== undefined)+ .map((item) => {+ return {+ name: item.user as string,+ value: item.totalTokenCost ? (item.totalTokenCost as number) : 0,+ };+ })+ .filter((i) => (isNotUndefinedOrNull(i.name) ? true : false))+ : [];++ const totalCost = user.data?.reduce(+ (acc, curr) => acc + (curr.totalTokenCost as number),+ 0,+ );++ const totalTraces = traces.data?.reduce(+ (acc, curr) => acc + (curr.countTraceId as number),+ 0,+ );++ const maxNumberOfEntries = { collapsed: 5, expanded: 20 } as const;++ const data = [+ {+ tabTitle: "Token cost",+ data: isExpanded+ ? transformedCost.slice(0, maxNumberOfEntries.expanded)+ : transformedCost.slice(0, maxNumberOfEntries.collapsed),+ totalMetric: totalCost ? usdFormatter(totalCost) : "-",+ metricDescription: "Total cost",+ formatter: usdFormatter,+ },+ {+ tabTitle: "Count of Traces",+ data: isExpanded+ ? transformedNumberOfTraces.slice(0, maxNumberOfEntries.expanded)+ : transformedNumberOfTraces.slice(0, maxNumberOfEntries.collapsed),+ totalMetric: totalTraces ? numberFormatter(totalTraces) : "-",+ metricDescription: "Total traces",+ },+ ];++ return (+ <DashboardCard+ className={className}+ title={"User consumption"}+ isLoading={user.isLoading}+ >+ <TabComponent+ tabs={data.map((item) => {+ return {+ tabTitle: item.tabTitle,+ totalMetric: item.totalMetric,+ metricDescription: item.metricDescription,+ content: (+ <>+ <TotalMetric+ metric={item.totalMetric}+ description={item.metricDescription}+ />+ <BarList+ data={item.data}+ valueFormatter={item.formatter}+ className="mt-2"+ showAnimation={true}+ color={"indigo"}+ />+ </>+ ),+ };+ })}+ />+ <ExpandListButton+ isExpanded={isExpanded}+ setExpanded={setIsExpanded}+ totalLength={transformedCost.length}+ maxLength={maxNumberOfEntries.collapsed}+ expandText={+ transformedCost.length > maxNumberOfEntries.expanded+ ? `Show top ${maxNumberOfEntries.expanded}`+ : "Show all"+ }+ />+ </DashboardCard>+ );+};diff --git a/src/features/dashboard/components/cards/BarChartCard.tsx b/src/features/dashboard/components/cards/BarChartCard.tsxnew file mode 100644index 0000000000..766af5eb81--- /dev/null+++ b/src/features/dashboard/components/cards/BarChartCard.tsx@@ -0,0 +1,64 @@+import { DashboardCard } from "@/src/features/dashboard/components/cards/DashboardCard";+import { NoData } from "@/src/features/dashboard/components/NoData";+import { TotalMetric } from "@/src/features/dashboard/components/TotalMetric";+import { numberFormatter } from "@/src/utils/numbers";+import { BarList } from "@tremor/react";++export type BarChartDataPoint = {+ name: string;+ value: number;+};++interface BarChartCardProps {+ children?: React.ReactNode;+ className?: string;+ isLoading: boolean;+ header: {+ metric: string;+ stat: number;+ category: string;+ };+ chart: {+ data: BarChartDataPoint[];+ header: string;+ metric: string;+ };+}++export default function BarChartCard({+ className,+ header,+ chart,+ isLoading,+ children,+}: BarChartCardProps) {+ const stat = header.stat ? numberFormatter(header.stat) : "0";+ return (+ <DashboardCard+ className={className}+ title={header.category}+ description={null}+ isLoading={isLoading}+ >+ <>+ <TotalMetric metric={stat} description={header.metric} />+ {chart.data.length > 0 ? (+ <>+ <BarList+ data={chart.data}+ valueFormatter={(number: number) =>+ Intl.NumberFormat("us").format(number).toString()+ }+ className="mt-6"+ showAnimation={true}+ color={"indigo"}+ />+ </>+ ) : (+ <NoData noDataText="No data" />+ )}+ {children}+ </>+ </DashboardCard>+ );+}diff --git a/src/features/dashboard/components/cards/ChevronButton.tsx b/src/features/dashboard/components/cards/ChevronButton.tsxnew file mode 100644index 0000000000..e45d4b4536--- /dev/null+++ b/src/features/dashboard/components/cards/ChevronButton.tsx@@ -0,0 +1,38 @@+import { ChevronDown, ChevronUp } from "lucide-react";+import { Button } from "@/src/components/ui/button";++export const ExpandListButton = ({+ isExpanded,+ setExpanded,+ totalLength,+ maxLength,+ expandText = "See more",+}: {+ isExpanded: boolean;+ setExpanded: (isExpanded: boolean) => void;+ totalLength: number;+ maxLength: number;+ expandText?: string;+}) => {+ if (totalLength <= maxLength) {+ return null;+ }++ return (+ <Button+ className="mt-2"+ variant="ghost"+ onClick={() => setExpanded(!isExpanded)}+ >+ {isExpanded ? (+ <>+ <ChevronUp className="mr-2 h-4 w-4" /> See less+ </>+ ) : (+ <>+ <ChevronDown className="mr-2 h-4 w-4" /> {expandText}+ </>+ )}+ </Button>+ );+};diff --git a/src/features/dashboard/components/cards/DashboardCard.tsx b/src/features/dashboard/components/cards/DashboardCard.tsxnew file mode 100644index 0000000000..dbdfa1dfc2--- /dev/null+++ b/src/features/dashboard/components/cards/DashboardCard.tsx@@ -0,0 +1,50 @@+import {+ Card,+ CardHeader,+ CardTitle,+ CardDescription,+ CardContent,+} from "@/src/components/ui/card";+import { cn } from "@/src/utils/tailwind";+import { Loader } from "lucide-react";+import { type ReactNode } from "react";++export type DashboardCardProps = {+ className?: string;+ title: ReactNode;+ description?: ReactNode;+ isLoading: boolean;+ children?: ReactNode;+ headerChildren?: ReactNode;+ cardContentClassName?: string;+};++export const DashboardCard = ({+ className,+ title,+ description,+ isLoading,+ children,+ headerChildren,+ cardContentClassName,+}: DashboardCardProps) => {+ return (+ <Card className={cn("flex flex-col", className)}>+ <CardHeader className="relative">+ <CardTitle>{title}</CardTitle>+ {description ? (+ <CardDescription>{description}</CardDescription>+ ) : undefined}+ {headerChildren ?? undefined}+ {isLoading ? (+ <div className="absolute right-5 top-5 ">+ <Loader className="h-5 w-5 animate-spin" />+ </div>+ ) : null}+ </CardHeader>+ <CardContent className={cn("flex-1", cardContentClassName)}>+ {children}+ </CardContent>+ </Card>+ );+};diff --git a/src/features/dashboard/components/cards/DashboardTable.tsx b/src/features/dashboard/components/cards/DashboardTable.tsxnew file mode 100644index 0000000000..19430e922c--- /dev/null+++ b/src/features/dashboard/components/cards/DashboardTable.tsx@@ -0,0 +1,62 @@+import { NoData } from "../NoData";+import { type ReactNode } from "react";++type TableHeaders = ReactNode[];+type TableRows = ReactNode[][];+type DashboardTableProps = {+ headers: TableHeaders;+ rows: TableRows;+ children?: ReactNode;+};++export const DashboardTable = ({+ headers,+ rows,+ children,+}: DashboardTableProps) => {+ return (+ <>+ {children}+ {rows.length > 0 ? (+ <div className="mt-4">+ <div className="overflow-x-auto">+ <div className="inline-block min-w-full align-middle">+ <table className="min-w-full divide-y divide-gray-300 animate-in animate-out">+ <thead>+ <tr>+ {headers.map((header, i) => (+ <th+ key={i}+ scope="col"+ className="whitespace-nowrap py-3.5 pl-4 pr-3 text-left text-xs font-semibold text-gray-900 sm:pl-0"+ >+ {header}+ </th>+ ))}+ </tr>+ </thead>++ <tbody className="divide-y divide-gray-200 bg-white">+ {rows.map((row) => (+ <tr key={"1"}>+ {row.map((cell, i) => (+ <td+ key={i}+ className="whitespace-nowrap py-2 pl-3 pr-2 text-xs text-gray-500 sm:pl-0"+ >+ {cell}+ </td>+ ))}+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ </div>+ </div>+ ) : (+ <NoData noDataText="No data" />+ )}+ </>+ );+};diff --git a/src/features/dashboard/components/charts.tsx b/src/features/dashboard/components/charts.tsxdeleted file mode 100644index 5a2e922308..0000000000--- a/src/features/dashboard/components/charts.tsx+++ /dev/null@@ -1,42 +0,0 @@-import { api } from "@/src/utils/api";-import {- Card,- CardHeader,- CardContent,- CardDescription,- CardTitle,-} from "@/src/components/ui/card";-import { BaseTimeSeriesChart } from "./BaseTimeSeriesChart";-import { type DateTimeAggregationOption } from "@/src/features/dashboard/lib/timeseries-aggregation";-import { Loader } from "lucide-react";--export function ChartScores(props: {- agg: DateTimeAggregationOption;- projectId: string;-}) {- const data = api.dashboard.scores.useQuery({- agg: props.agg,- projectId: props.projectId,- });-- return (- <Card>- <CardHeader className="relative">- <CardTitle>Scores</CardTitle>- <CardDescription>Average</CardDescription>- {data.isLoading ? (- <div className="absolute right-5 top-5 ">- <Loader className="h-5 w-5 animate-spin" />- </div>- ) : null}- </CardHeader>- <CardContent>- <BaseTimeSeriesChart- agg={props.agg}- data={data.data ?? []}- connectNulls- />- </CardContent>- </Card>- );-}diff --git a/src/features/dashboard/components/hooks.ts b/src/features/dashboard/components/hooks.tsindex b3998bb5e2..8012690016 100644--- a/src/features/dashboard/components/hooks.ts+++ b/src/features/dashboard/components/hooks.ts@@ -1,3 +1,4 @@+import { type TimeSeriesChartDataPoint } from "@/src/features/dashboard/components/BaseTimeSeriesChart";import { type FilterState } from "@/src/features/filters/types";import { type DatabaseRow } from "@/src/server/api/services/query-builder";import { api } from "@/src/utils/api";@@ -9,21 +10,22 @@ export const getAllModels = (const allModels = api.dashboard.chart.useQuery({projectId,from: "observations",- select: [{ column: "model", agg: null }],+ select: [{ column: "model" }],filter:[...globalFilterState,{ type: "string", column: "type", operator: "=", value: "GENERATION" },] ?? [],groupBy: [{ type: "string", column: "model" }],- orderBy: [],});return allModels.data ? extractAllModels(allModels.data) : [];};const extractAllModels = (data: DatabaseRow[]): string[] => {- return data.map((item) => item.model as string);+ return data+ .filter((item) => item.model !== null)+ .map((item) => item.model as string);};type Field = string;@@ -33,10 +35,6 @@ type ChartData = {value?: number;};-type Result = {- ts: number;- values: { label: string; value?: number }[];-};export function reduceData(data: DatabaseRow[],field: Field,@@ -64,8 +62,8 @@ export function reduceData(export function transformMapAndFillZeroValues(map: Map<number, ChartData[]>,allModels: string[],-): Result[] {- const result: Result[] = [];+): TimeSeriesChartDataPoint[] {+ const result: TimeSeriesChartDataPoint[] = [];for (const [date, items] of map) {const values = items.map((item) => ({diff --git a/src/features/dashboard/lib/timeseries-aggregation.ts b/src/features/dashboard/lib/timeseries-aggregation.tsindex ee4ef761cd..0e7fbe67a4 100644--- a/src/features/dashboard/lib/timeseries-aggregation.ts+++ b/src/features/dashboard/lib/timeseries-aggregation.ts@@ -24,7 +24,7 @@ export const dateTimeAggregationSettings: Record<date.toLocaleDateString("en-US", { year: "2-digit", month: "short" }),},"3 months": {- date_trunc: "week",+ date_trunc: "day",date_formatter: (date) =>date.toLocaleDateString("en-US", { month: "short", day: "numeric" }),},diff --git a/src/pages/project/[projectId]/index.tsx b/src/pages/project/[projectId]/index.tsxindex ee0dd15eaa..8be3eaba63 100644--- a/src/pages/project/[projectId]/index.tsx+++ b/src/pages/project/[projectId]/index.tsx@@ -6,10 +6,14 @@ import {type DateTimeAggregationOption,} from "@/src/features/dashboard/lib/timeseries-aggregation";import { useRouter } from "next/router";-import { TokenChart } from "@/src/features/dashboard/components/TokenChart";import { LatencyChart } from "@/src/features/dashboard/components/LatencyChart";-import { ChartScores } from "@/src/features/dashboard/components/charts";-import { EventsCard } from "@/src/features/dashboard/components/EventsCard";+import { ChartScores } from "@/src/features/dashboard/components/ChartScores";+import { TracesBarListChart } from "@/src/features/dashboard/components/TracesChart";+import { MetricTable } from "@/src/features/dashboard/components/MetricTable";+import { ScoresTable } from "@/src/features/dashboard/components/ScoresTable";+import { ModelUsageChart } from "@/src/features/dashboard/components/ModelUsageChart";+import { TracesTimeSeriesChart } from "@/src/features/dashboard/components/TracesTimeSeriesChart";+import { UserChart } from "@/src/features/dashboard/components/UserChart";export default function Start() {const [agg, setAgg] = useState<DateTimeAggregationOption>("7 days");@@ -64,70 +68,142 @@ export default function Start() {))}</TabsList></Tabs>- <div className="grid gap-4 xl:grid-cols-2">- <div className="col-span-2">- <EventsCard- projectId={projectId}- agg={agg}- globalFilterState={[- {- column: "startTime",- operator: ">",- type: "datetime",- value: convertAggToDateTime(agg),- },- {- column: "startTime",- operator: "<",- type: "datetime",- value: new Date(),- },- ]}- />- </div>- <div className="col-span-2">- <TokenChart- projectId={projectId}- agg={agg}- globalFilterState={[- {- column: "startTime",- operator: ">",- type: "datetime",- value: convertAggToDateTime(agg),- },- {- column: "startTime",- operator: "<",- type: "datetime",- value: new Date(),- },- ]}- />- </div>- <div className="col-span-2">- <LatencyChart- projectId={projectId}- agg={agg}- globalFilterState={[- {- column: "startTime",- operator: ">",- type: "datetime",- value: convertAggToDateTime(agg),- },- {- column: "startTime",- operator: "<",- type: "datetime",- value: new Date(),- },- ]}- />- </div>- <div className="col-span-full">- <ChartScores agg={agg} projectId={projectId} />- </div>+ <div className="grid w-full grid-cols-1 gap-4 overflow-hidden lg:grid-cols-2 xl:grid-cols-6">+ <TracesBarListChart+ className="col-span-1 xl:col-span-2 "+ projectId={projectId}+ globalFilterState={[+ {+ column: "startTime",+ operator: ">",+ type: "datetime",+ value: convertAggToDateTime(agg),+ },+ {+ column: "startTime",+ operator: "<",+ type: "datetime",+ value: new Date(),+ },+ ]}+ />+ <MetricTable+ className="col-span-1 xl:col-span-2"+ projectId={projectId}+ globalFilterState={[+ {+ column: "startTime",+ operator: ">",+ type: "datetime",+ value: convertAggToDateTime(agg),+ },+ {+ column: "startTime",+ operator: "<",+ type: "datetime",+ value: new Date(),+ },+ ]}+ />+ <ScoresTable+ className="col-span-1 xl:col-span-2"+ projectId={projectId}+ globalFilterState={[+ {+ column: "startTime",+ operator: ">",+ type: "datetime",+ value: convertAggToDateTime(agg),+ },+ {+ column: "startTime",+ operator: "<",+ type: "datetime",+ value: new Date(),+ },+ ]}+ />+ <TracesTimeSeriesChart+ className="col-span-1 xl:col-span-3"+ projectId={projectId}+ globalFilterState={[+ {+ column: "startTime",+ operator: ">",+ type: "datetime",+ value: convertAggToDateTime(agg),+ },+ {+ column: "startTime",+ operator: "<",+ type: "datetime",+ value: new Date(),+ },+ ]}+ agg={agg}+ />+ <ModelUsageChart+ className="min-h-24 col-span-1 xl:col-span-3"+ projectId={projectId}+ globalFilterState={[+ {+ column: "startTime",+ operator: ">",+ type: "datetime",+ value: convertAggToDateTime(agg),+ },+ {+ column: "startTime",+ operator: "<",+ type: "datetime",+ value: new Date(),+ },+ ]}+ agg={agg}+ />+ <UserChart+ className="col-span-1 xl:col-span-3"+ projectId={projectId}+ globalFilterState={[+ {+ column: "startTime",+ operator: ">",+ type: "datetime",+ value: convertAggToDateTime(agg),+ },+ {+ column: "startTime",+ operator: "<",+ type: "datetime",+ value: new Date(),+ },+ ]}+ agg={agg}+ />+ <ChartScores+ className="col-span-1 xl:col-span-3"+ agg={agg}+ projectId={projectId}+ />+ <LatencyChart+ className="col-span-1 flex-auto justify-between xl:col-span-full"+ projectId={projectId}+ agg={agg}+ globalFilterState={[+ {+ column: "startTime",+ operator: ">",+ type: "datetime",+ value: convertAggToDateTime(agg),+ },+ {+ column: "startTime",+ operator: "<",+ type: "datetime",+ value: new Date(),+ },+ ]}+ /></div></div>);diff --git a/src/server/api/services/query-builder.ts b/src/server/api/services/query-builder.tsindex e8c8665417..c05e53d8fa 100644--- a/src/server/api/services/query-builder.ts+++ b/src/server/api/services/query-builder.ts@@ -7,7 +7,12 @@ import { Prisma, type PrismaClient } from "@prisma/client";import { type Sql } from "@prisma/client/runtime/library";import Decimal from "decimal.js";import { type z } from "zod";-import { type sqlInterface } from "./sqlInterface";+import {+ sqlInterface,+ aggregations,+ groupByInterface,+ filterInterface,+} from "./sqlInterface";import { tableDefinitions } from "./tableDefinitions";export type InternalDatabaseRow = {@@ -21,8 +26,10 @@ export type DatabaseRow = {export const executeQuery = async (prisma: PrismaClient,projectId: string,- query: z.TypeOf<typeof sqlInterface>,+ unsafeQuery: z.TypeOf<typeof sqlInterface>,) => {+ const query = sqlInterface.parse(unsafeQuery);+const sql = enrichAndCreateQuery(projectId, query);const response = await prisma.$queryRaw<InternalDatabaseRow[]>(sql);@@ -34,16 +41,26 @@ export const executeQuery = async (export const enrichAndCreateQuery = (projectId: string,- query: z.TypeOf<typeof sqlInterface>,+ queryUnsafe: z.TypeOf<typeof sqlInterface>,) => {+ const query = sqlInterface.parse(queryUnsafe);return createQuery({...query,- filter: [...query.filter, ...getMandatoryFilter(query.from, projectId)],+ filter: [+ ...(query.filter ?? []),+ ...getMandatoryFilter(query.from, projectId),+ ],});};-export const createQuery = (query: z.TypeOf<typeof sqlInterface>) => {- const cte = createDateRangeCte(query.from, query.filter, query.groupBy);+export const createQuery = (queryUnsafe: z.TypeOf<typeof sqlInterface>) => {+ const query = sqlInterface.parse(queryUnsafe);++ const cte = createDateRangeCte(+ query.from,+ query.filter ?? [],+ query.groupBy ?? [],+ );const fromString = cte?.from ?? Prisma.sql` FROM ${getTableSql(query.from)}`;@@ -51,15 +68,18 @@ export const createQuery = (query: z.TypeOf<typeof sqlInterface>) => {// raw mandatory everywhere here as this creates the selection// agg is typed via zod// column names come from our defs via the table definitions- field.agg- ? Prisma.sql`${Prisma.raw(field.agg)}(${getInternalSql(- getColumnSql(query.from, field.column),- )}) as "${Prisma.raw(field.agg.toLowerCase())}${Prisma.raw(- capitalizeFirstLetter(field.column),- )}"`- : Prisma.sql`${getInternalSql(- getColumnSql(query.from, field.column),- )} as "${Prisma.raw(getColumnSql(query.from, field.column).name)}"`,+ {+ const safeColumn = getColumnDefinition(query.from, field.column);+ return field.agg+ ? Prisma.sql`${Prisma.raw(field.agg)}(${getInternalSql(+ safeColumn,+ )}) as "${Prisma.raw(field.agg.toLowerCase())}${Prisma.raw(+ capitalizeFirstLetter(safeColumn.name),+ )}"`+ : Prisma.sql`${getInternalSql(safeColumn)} as "${Prisma.raw(+ safeColumn.name,+ )}"`;+ },);if (cte)@@ -70,8 +90,8 @@ export const createQuery = (query: z.TypeOf<typeof sqlInterface>) => {let groupString = Prisma.empty;- if (query.groupBy.length > 0 || cte) {- const groupByFields = query.groupBy.map((groupBy) =>+ if ((query.groupBy && query.groupBy.length > 0) || cte) {+ const groupByFields = (query.groupBy ?? []).map((groupBy) =>prepareGroupBy(query.from, groupBy),);groupString =@@ -85,13 +105,13 @@ export const createQuery = (query: z.TypeOf<typeof sqlInterface>) => {: Prisma.empty;const orderByString = prepareOrderByString(+ query.from,query.orderBy,- tableDefinitions[query.from]!.columns,cte ? true : false,);const filterString =- query.filter.length > 0+ query.filter && query.filter.length > 0? Prisma.sql` ${cte ? Prisma.sql` AND ` : Prisma.sql` WHERE `} ${prepareFilterString(@@ -101,27 +121,42 @@ export const createQuery = (query: z.TypeOf<typeof sqlInterface>) => {)}`: Prisma.empty;+ const limitString = query.limit+ ? Prisma.sql` LIMIT ${query.limit}`+ : Prisma.empty;+return Prisma.sql`${cte?.cte ?? Prisma.empty- }${selectString}${fromString}${filterString}${groupString}${orderByString};`;+ }${selectString}${fromString}${filterString}${groupString}${orderByString}${limitString};`;+};++const createAggregatedColumn = (+ from: z.infer<typeof sqlInterface>["from"],+ column: string,+ agg?: z.infer<typeof aggregations>,+): Prisma.Sql => {+ // raw mandatory everywhere here as this creates the selection+ // agg is typed via zod+ // column names come from our defs via the table definitions+ return agg+ ? Prisma.sql`${Prisma.raw(+ aggregations.parse(agg) as string,+ )}(${getInternalSql(getColumnDefinition(from, column))})`+ : Prisma.sql`${getInternalSql(getColumnDefinition(from, column))}`;};const prepareOrderByString = (+ from: z.infer<typeof sqlInterface>["from"],orderBy: z.infer<typeof sqlInterface>["orderBy"],- columnDefinitions: ColumnDefinition[],hasCte: boolean,): Prisma.Sql => {- const orderBys = orderBy.map((orderBy) => {- const column = columnDefinitions.find((x) => x.name === orderBy.column);- if (!column) {- console.error(`Column ${orderBy.column} not found`);- throw new Error(`Column ${orderBy.column} not found`);- }-+ const orderBys = (orderBy ?? []).map((orderBy) => {// raw mandatory here- return Prisma.sql`${getInternalSql(column)} ${Prisma.raw(- orderBy.direction,- )}`;+ return Prisma.sql`${createAggregatedColumn(+ from,+ orderBy.column,+ orderBy.agg,+ )} ${Prisma.raw(orderBy.direction)}`;});const addedCte = hasCte? [Prisma.sql`date_series."date" ASC`, ...orderBys]@@ -134,10 +169,10 @@ const prepareOrderByString = (const prepareFilterString = (table: z.infer<typeof sqlInterface>["from"],- filter: z.infer<typeof sqlInterface>["filter"],+ filter: z.infer<typeof filterInterface>,columnDefinitions: ColumnDefinition[],): Prisma.Sql => {- const filters = filter.map((filter) => {+ const filters = (filter ?? []).map((filter) => {const column = columnDefinitions.find((x) => x.name === filter.column);if (!column) {console.error(`Column ${filter.column} not found`);@@ -164,9 +199,11 @@ const prepareFilterString = (const prepareGroupBy = (table: z.infer<typeof sqlInterface>["from"],- groupBy: z.infer<typeof sqlInterface>["groupBy"][number],+ groupBy: z.infer<typeof groupByInterface>[number],) => {- const internalColumn = getInternalSql(getColumnSql(table, groupBy.column));+ const internalColumn = getInternalSql(+ getColumnDefinition(table, groupBy.column),+ );if (groupBy.type === "datetime") {return Prisma.sql`date_series."date"`;} else {@@ -175,16 +212,20 @@ const prepareGroupBy = (};function isTimeRangeFilter(- filter: z.infer<typeof sqlInterface>["filter"][number],+ filter: z.infer<typeof filterInterface>[number],): filter is z.infer<typeof timeFilter> {return filter.type === "datetime";}const createDateRangeCte = (- from: z.infer<typeof sqlInterface>["from"],- filters: z.infer<typeof singleFilter>[],- groupBy: z.infer<typeof sqlInterface>["groupBy"],+ fromUnsafe: z.infer<typeof sqlInterface>["from"],+ filtersUnsafe: z.infer<typeof singleFilter>[],+ groupByUnsafe: z.infer<typeof groupByInterface>,) => {+ const from = sqlInterface.shape.from.parse(fromUnsafe);+ const groupBy = groupByInterface.parse(groupByUnsafe);+ const filters = filterInterface.parse(filtersUnsafe);+const groupByColumns = groupBy.filter((x) => x.type === "datetime");if (groupByColumns.length === 0) return undefined;@@ -220,7 +261,7 @@ const createDateRangeCte = ();}- const startColumn = getColumnSql(from, minDateColumn.column);+ const startColumn = getColumnDefinition(from, minDateColumn.column);// raw mandatory for temporal unit. From and to are parameterised values// temporal unit is typed@@ -248,16 +289,18 @@ const createDateRangeCte = (};const getTableSql = (- table: z.infer<typeof sqlInterface>["from"],+ tableUnsafe: z.infer<typeof sqlInterface>["from"],): Prisma.Sql => {- // raw required here, everyrhing is typed+ const table = sqlInterface.shape.from.parse(tableUnsafe);return Prisma.raw(tableDefinitions[table]!.table);};-const getColumnSql = (- table: z.infer<typeof sqlInterface>["from"],+const getColumnDefinition = (+ tableUnsafe: z.infer<typeof sqlInterface>["from"],column: string,): ColumnDefinition => {+ const table = sqlInterface.shape.from.parse(tableUnsafe);+const foundColumn = tableDefinitions[table]!.columns.find((c) => {return c.name === column;});@@ -303,9 +346,11 @@ function capitalizeFirstLetter(str: string) {}const getMandatoryFilter = (- table: z.infer<typeof sqlInterface>["from"],+ tableUnsafe: z.infer<typeof sqlInterface>["from"],projectId: string,) => {+ const table = sqlInterface.shape.from.parse(tableUnsafe);+const observationFilter = {type: "string" as const,column: "observationsProjectId",diff --git a/src/server/api/services/sqlInterface.ts b/src/server/api/services/sqlInterface.tsindex c19ccd01ba..abfb3bd216 100644--- a/src/server/api/services/sqlInterface.ts+++ b/src/server/api/services/sqlInterface.ts@@ -10,6 +10,32 @@ export const temporalUnit = z.enum(["minute",]);+export const aggregations = z+ .enum(["SUM", "AVG", "COUNT", "MAX", "MIN"])+ .optional();++export const groupByInterface = z.array(+ z.discriminatedUnion("type", [+ z.object({+ type: z.literal("datetime"),+ column: z.string(),+ temporalUnit: temporalUnit,+ }),+ z.object({ type: z.literal("number"), column: z.string() }),+ z.object({ type: z.literal("string"), column: z.string() }),+ ]),+);++const orderByInterface = z.array(+ z.object({+ column: z.string(),+ direction: z.enum(["ASC", "DESC"]),+ agg: aggregations,+ }),+);++export const filterInterface = z.array(singleFilter);+export const sqlInterface = z.object({from: z.enum(["traces",@@ -18,28 +44,14 @@ export const sqlInterface = z.object({"traces_scores","traces_parent_observation_scores",]),- filter: z.array(singleFilter),- groupBy: z.array(- z.discriminatedUnion("type", [- z.object({- type: z.literal("datetime"),- column: z.string(),- temporalUnit: temporalUnit,- }),- z.object({ type: z.literal("number"), column: z.string() }),- z.object({ type: z.literal("string"), column: z.string() }),- ]),- ),+ filter: filterInterface.optional(),+ groupBy: groupByInterface.optional(),select: z.array(z.object({column: z.string(),- agg: z.enum(["SUM", "AVG", "COUNT"]).nullable(),- }),- ),- orderBy: z.array(- z.object({- column: z.string(),- direction: z.enum(["ASC", "DESC"]),+ agg: aggregations,}),),+ orderBy: orderByInterface.optional(),+ limit: z.number().optional(),});diff --git a/src/server/api/services/tableDefinitions.ts b/src/server/api/services/tableDefinitions.tsindex 621d6c0f3d..00b244d6bf 100644--- a/src/server/api/services/tableDefinitions.ts+++ b/src/server/api/services/tableDefinitions.ts@@ -66,6 +66,26 @@ export const scoreId = {type: "string",internal: 's."id"',} as const;+export const traceName = {+ name: "traceName",+ type: "string",+ internal: 't."name"',+} as const;+export const totalTokens = {+ name: "totalTokens",+ type: "number",+ internal: 'o."total_tokens"',+} as const;+export const model = {+ name: "model",+ type: "string",+ internal: 'o."model"',+} as const;+export const traceUser = {+ name: "user",+ type: "string",+ internal: 't."user_id"',+} as const;export const totalTokenCost = {name: "totalTokenCost",@@ -101,7 +121,15 @@ export const totalTokenCost = {export const tableDefinitions: TableDefinitions = {traces: {table: ` traces t`,- columns: [tracesProjectId, traceVersion, release, traceId, traceTimestamp],+ columns: [+ tracesProjectId,+ traceVersion,+ release,+ traceId,+ traceTimestamp,+ traceName,+ traceUser,+ ],},traces_observations: {table: ` traces t LEFT JOIN observations o ON t.id = o.trace_id`,@@ -113,6 +141,11 @@ export const tableDefinitions: TableDefinitions = {observationsProjectId,duration,totalTokenCost,+ totalTokens,+ model,+ traceTimestamp,+ traceUser,+ startTime,],},observations: {@@ -128,13 +161,9 @@ export const tableDefinitions: TableDefinitions = {type: "number",internal: 'o."prompt_tokens"',},- {- name: "totalTokens",- type: "number",- internal: 'o."total_tokens"',- },+ totalTokens,observationId,- { name: "model", type: "string", internal: 'o."model"' },+ model,observationsProjectId,startTime,{ name: "endTime", type: "datetime", internal: 'o."end_time"' },@@ -147,7 +176,7 @@ export const tableDefinitions: TableDefinitions = {tracesProjectId,{ name: "value", type: "number", internal: 's."value"' },{- name: "name",+ name: "scoreName",type: "number",internal: 's."name"',},@@ -155,6 +184,7 @@ export const tableDefinitions: TableDefinitions = {traceVersion,traceTimestamp,scoreName,+ traceUser,tracesProjectId,],},diff --git a/src/utils/numbers.ts b/src/utils/numbers.tsindex 7983f8a14e..4979f2aa5a 100644--- a/src/utils/numbers.ts+++ b/src/utils/numbers.ts@@ -1,3 +1,16 @@export const numberFormatter = (number: number) => {- return Intl.NumberFormat("us").format(number).toString();+ return Intl.NumberFormat("us", {+ notation: "compact",+ compactDisplay: "short",+ }).format(number);};++export const usdFormatter = (number: number) =>+ new Intl.NumberFormat("en-US", {+ style: "currency",+ currency: "USD",++ // These options are needed to round to whole numbers if that's what you want.+ //minimumFractionDigits: 0, // (this suffices for whole numbers, but will print 2500.10 as $2,500.1)+ //maximumFractionDigits: 0, // (causes 2500.99 to be printed as $2,501)+ }).format(number);