🪢 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
feat(datasets): support charts for scores and resource metrics (#4754)
marliessophie50379bd4b50a
diff --git a/web/src/ee/features/annotation-queues/components/CreateOrEditAnnotationQueueButton.tsx b/web/src/ee/features/annotation-queues/components/CreateOrEditAnnotationQueueButton.tsxindex ddf14a1189..ecc87e18f1 100644--- a/web/src/ee/features/annotation-queues/components/CreateOrEditAnnotationQueueButton.tsx+++ b/web/src/ee/features/annotation-queues/components/CreateOrEditAnnotationQueueButton.tsx@@ -31,7 +31,6 @@ import {import { api } from "@/src/utils/api";import { getScoreDataTypeIcon } from "@/src/features/scores/components/ScoreDetailColumnHelpers";import { MultiSelectKeyValues } from "@/src/features/scores/components/multi-select-key-values";-import { CommandItem } from "@/src/components/ui/command";import { useRouter } from "next/router";import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";import {@@ -39,6 +38,7 @@ import {useEntitlementLimit,} from "@/src/features/entitlements/hooks";import { ActionButton } from "@/src/components/ActionButton";+import { DropdownMenuItem } from "@/src/components/ui/dropdown-menu";export const CreateOrEditAnnotationQueueButton = ({projectId,@@ -257,7 +257,7 @@ export const CreateOrEditAnnotationQueueButton = ({};})}controlButtons={- <CommandItem+ <DropdownMenuItemonSelect={() => {capture("score_configs:manage_configs_item_click",@@ -269,7 +269,7 @@ export const CreateOrEditAnnotationQueueButton = ({}}>Manage score configs- </CommandItem>+ </DropdownMenuItem>}/></FormControl>diff --git a/web/src/ee/features/experiments/components/CreateExperimentsForm.tsx b/web/src/ee/features/experiments/components/CreateExperimentsForm.tsxindex 15bc8f7cda..b074894ee0 100644--- a/web/src/ee/features/experiments/components/CreateExperimentsForm.tsx+++ b/web/src/ee/features/experiments/components/CreateExperimentsForm.tsx@@ -77,6 +77,7 @@ import {} from "@/src/components/ui/dialog";import Link from "next/link";import { useHasEntitlement } from "@/src/features/entitlements/hooks";+import { DropdownMenuItem } from "@/src/components/ui/dropdown-menu";const CreateExperimentData = z.object({name: z@@ -790,13 +791,13 @@ export const CreateExperimentsForm = ({}hideClearButtoncontrolButtons={- <CommandItem+ <DropdownMenuItemonSelect={() => {window.open(`/project/${projectId}/evals`, "_blank");}}>Manage evaluators- </CommandItem>+ </DropdownMenuItem>}/></FormItem>diff --git a/web/src/features/dashboard/components/score-analytics/CategoricalScoreChart.tsx b/web/src/features/dashboard/components/score-analytics/CategoricalScoreChart.tsxindex 58c1253a0f..4eca1960c4 100644--- a/web/src/features/dashboard/components/score-analytics/CategoricalScoreChart.tsx+++ b/web/src/features/dashboard/components/score-analytics/CategoricalScoreChart.tsx@@ -1,31 +1,19 @@import { api } from "@/src/utils/api";--import {- type ScoreSource,- type FilterState,- type ScoreDataType,-} from "@langfuse/shared";+import { type FilterState } from "@langfuse/shared";import { createTracesTimeFilter } from "@/src/features/dashboard/lib/dashboard-utils";import {type DashboardDateRangeAggregationOption,dashboardDateRangeAggregationSettings,} from "@/src/utils/date-range-utils";import React, { useMemo } from "react";-import { BarChart } from "@tremor/react";-import { Card } from "@/src/components/ui/card";-import { getColorsForCategories } from "@/src/features/dashboard/utils/getColorsForCategories";-import {- isEmptyBarChart,- transformCategoricalScoresToChartData,-} from "@/src/features/dashboard/lib/score-analytics-utils";-import { NoDataOrLoading } from "@/src/components/NoDataOrLoading";import { useClickhouse } from "@/src/components/layouts/ClickhouseAdminToggle";+import { DashboardCategoricalScoreAdapter } from "@/src/features/scores/adapters";+import { type ScoreData } from "@/src/features/scores/types";+import { CategoricalChart } from "@/src/features/scores/components/ScoreChart";export function CategoricalScoreChart(props: {projectId: string;- name: string;- source: ScoreSource;- dataType: ScoreDataType;+ scoreData: ScoreData;globalFilterState: FilterState;agg?: DashboardDateRangeAggregationOption;}) {@@ -45,19 +33,19 @@ export function CategoricalScoreChart(props: {{type: "string",column: "scoreName",- value: props.name,+ value: props.scoreData.name,operator: "=",},{type: "string",column: "scoreSource",- value: props.source,+ value: props.scoreData.source,operator: "=",},{type: "string",column: "scoreDataType",- value: props.dataType,+ value: props.scoreData.dataType,operator: "=",},],@@ -99,40 +87,23 @@ export function CategoricalScoreChart(props: {);const { chartData, chartLabels } = useMemo(() => {- return scores.data- ? transformCategoricalScoresToChartData(- scores.data,- "scoreTimestamp",- props.agg,- )- : { chartData: [], chartLabels: [] };- }, [scores.data, props.agg]);+ if (!scores.data) return { chartData: [], chartLabels: [] };- const barCategoryGap = (chartLength: number): string => {- if (chartLength > 7) return "10%";- if (chartLength > 5) return "20%";- if (chartLength > 3) return "30%";- else return "40%";- };- const colors = getColorsForCategories(chartLabels);+ const adapter = new DashboardCategoricalScoreAdapter(+ scores.data,+ "scoreTimestamp",+ props.agg,+ );+ return adapter.toChartData();+ }, [scores.data, props.agg]);- return isEmptyBarChart({ data: chartData }) ? (- <NoDataOrLoading isLoading={scores.isLoading} />- ) : (- <Card className="min-h-[9rem] w-full flex-1 rounded-tremor-default border">- <BarChart- className="mt-4"- data={chartData}- index="binLabel"- categories={chartLabels}- colors={colors}- valueFormatter={(number: number) =>- Intl.NumberFormat("en-US").format(number).toString()- }- yAxisWidth={48}- barCategoryGap={barCategoryGap(chartData.length)}- stack={!!props.agg}- />- </Card>+ return (+ <CategoricalChart+ chartData={chartData}+ chartLabels={chartLabels}+ isLoading={scores.isLoading}+ className="min-h-[9rem] flex-1"+ stack={!!props.agg}+ />);}diff --git a/web/src/features/dashboard/components/score-analytics/ScoreAnalytics.tsx b/web/src/features/dashboard/components/score-analytics/ScoreAnalytics.tsxindex df3b8a67b7..a9d95c35a3 100644--- a/web/src/features/dashboard/components/score-analytics/ScoreAnalytics.tsx+++ b/web/src/features/dashboard/components/score-analytics/ScoreAnalytics.tsx@@ -127,19 +127,17 @@ export function ScoreAnalytics(props: {{(isCategoricalDataType(dataType) ||isBooleanDataType(dataType)) && (<CategoricalScoreChart- source={source}- name={name}- dataType={dataType}projectId={props.projectId}+ scoreData={scoreData}globalFilterState={props.globalFilterState}/>)}{isNumericDataType(dataType) && (<NumericScoreHistogram+ projectId={props.projectId}source={source}name={name}dataType={dataType}- projectId={props.projectId}globalFilterState={props.globalFilterState}/>)}@@ -154,11 +152,9 @@ export function ScoreAnalytics(props: {{(isCategoricalDataType(dataType) ||isBooleanDataType(dataType)) && (<CategoricalScoreChart- agg={props.agg}- source={source}- name={name}- dataType={dataType}projectId={props.projectId}+ agg={props.agg}+ scoreData={scoreData}globalFilterState={props.globalFilterState}/>)}diff --git a/web/src/features/dashboard/lib/score-analytics-utils.ts b/web/src/features/dashboard/lib/score-analytics-utils.tsindex 72aab7bc1e..edfb95a642 100644--- a/web/src/features/dashboard/lib/score-analytics-utils.ts+++ b/web/src/features/dashboard/lib/score-analytics-utils.ts@@ -1,16 +1,36 @@import { type DashboardDateRangeAggregationOption } from "@/src/utils/date-range-utils";import { type DatabaseRow } from "@/src/server/api/services/queryBuilder";+import {+ type CategoryCounts,+ type ChartBin,+ type HistogramBin,+} from "@/src/features/scores/types";+import { type RouterOutputs } from "@/src/utils/api";-// types-type HistogramBin = { binLabel: string; count: number };-type CategoryCounts = Record<string, number>;-type ChartBin = { binLabel: string } & CategoryCounts;+export const RESOURCE_METRICS = [+ {+ key: "latency",+ value: "Latency",+ objectKey: "avgLatency",+ label: "Latency (ms)",+ },+ {+ key: "cost",+ value: "Cost",+ objectKey: "avgTotalCost",+ label: "Average Total Cost ($)",+ },+];// numeric score analytics helpersfunction round(value: number, precision = 2) {return parseFloat(value.toFixed(precision));}+export function uniqueAndSort(labels: string[]): string[] {+ return Array.from(new Set(labels)).sort();+}+function computeBinSize(minBins: number,maxBins: number,@@ -125,8 +145,112 @@ function groupCategoricalScoreDataByTimestamp();}-function uniqueAndSort(labels: string[]): string[] {- return Array.from(new Set(labels)).sort();+type ChartAccumulator = Map<+ string,+ { chartData: ChartBin[]; chartLabels: string[] }+>;++function initializeOrGetChartData(acc: ChartAccumulator, key: string) {+ if (!acc.has(key)) {+ acc.set(key, { chartData: [], chartLabels: [] });+ }+ return acc.get(key)!;+}++function createNumericScoreData(run: string, score: number, scoreName: string) {+ return {+ chartLabels: [scoreName],+ chartBin: {+ binLabel: run,+ [scoreName]: score,+ } as ChartBin,+ };+}++function createCategoricalScoreData(+ run: string,+ valueCounts: Array<{ value: string; count: number }>,+ values: string[],+) {+ const categoryCounts = valueCounts.reduce(+ (counts, { value, count }) => ({+ ...counts,+ [value]: count,+ }),+ {} as CategoryCounts,+ );++ return {+ chartLabels: values,+ chartBin: {+ binLabel: run,+ ...categoryCounts,+ } as ChartBin,+ };+}++function addMetricToAccumulator(+ acc: ChartAccumulator,+ key: string,+ chartBin: ChartBin,+ chartLabels: string[],+) {+ const current = initializeOrGetChartData(acc, key);+ acc.set(key, {+ chartData: [...current.chartData, chartBin],+ chartLabels,+ });+}++export function transformAggregatedRunMetricsToChartData(+ runMetrics: RouterOutputs["datasets"]["runsByDatasetIdMetrics"]["runs"],+ scoreIdToName: Map<string, string>,+) {+ const reversedMetrics = runMetrics.slice().reverse();++ return reversedMetrics.reduce((acc, run) => {+ // Handle scores+ Object.entries(run.scores ?? {}).forEach(([scoreId, score]) => {+ const scoreData =+ score.type === "NUMERIC"+ ? createNumericScoreData(+ run.name,+ score.average,+ scoreIdToName.get(scoreId) ?? scoreId,+ )+ : createCategoricalScoreData(+ run.name,+ score.valueCounts,+ score.values,+ );++ addMetricToAccumulator(+ acc,+ scoreId,+ scoreData.chartBin,+ scoreData.chartLabels,+ );+ });++ // Handle resource metrics+ RESOURCE_METRICS.forEach(({ key, objectKey }) => {+ const resourceValue = run[objectKey as keyof typeof run];+ const resourceData = createNumericScoreData(+ run.name,+ !!resourceValue ? Number(resourceValue) : 0,+ key,+ );++ addMetricToAccumulator(+ acc,+ key,+ resourceData.chartBin,+ resourceData.chartLabels,+ );+ });++ return acc;+ }, new Map());}export function transformCategoricalScoresToChartData(@@ -155,11 +279,11 @@ export function transformCategoricalScoresToChartData(chartData.push({ ...categoryCounts, binLabel: timestamp } as ChartBin);});- return { chartData, chartLabels: uniqueAndSort(chartLabels) };+ return { chartData, chartLabels };}}-export function isEmptyBarChart({ data }: { data: ChartBin[] }) {+export function isEmptyChart({ data }: { data: ChartBin[] }) {return (data.length === 0 || data.every((item) => Object.keys(item).length === 1));diff --git a/web/src/features/datasets/components/DatasetAnalytics.tsx b/web/src/features/datasets/components/DatasetAnalytics.tsxnew file mode 100644index 0000000000..cf66524dbd--- /dev/null+++ b/web/src/features/datasets/components/DatasetAnalytics.tsx@@ -0,0 +1,36 @@+import { RESOURCE_METRICS } from "@/src/features/dashboard/lib/score-analytics-utils";+import { MultiSelectKeyValues } from "@/src/features/scores/components/multi-select-key-values";+import { ChartColumnBig } from "lucide-react";++export function DatasetAnalytics(props: {+ projectId: string;+ scoreOptions: { key: string; value: string }[];+ selectedMetrics: string[];+ setSelectedMetrics: (metrics: string[]) => void;+}) {+ return (+ <MultiSelectKeyValues+ className="max-w-fit"+ placeholder="Search..."+ title="Charts"+ iconLeft={<ChartColumnBig className="mr-1 h-4 w-4" />}+ hideClearButton+ onValueChange={(values, changedValue, selectedKeys) => {+ if (values.length === 0) props.setSelectedMetrics([]);++ if (changedValue) {+ if (selectedKeys?.has(changedValue)) {+ props.setSelectedMetrics([...props.selectedMetrics, changedValue]);+ } else {+ props.setSelectedMetrics(+ props.selectedMetrics.filter((key) => key !== changedValue),+ );+ }+ }+ }}+ values={props.selectedMetrics}+ options={RESOURCE_METRICS}+ groupedOptions={[{ label: "Scores", options: props.scoreOptions }]}+ />+ );+}diff --git a/web/src/features/datasets/components/DatasetRunsTable.tsx b/web/src/features/datasets/components/DatasetRunsTable.tsxindex c1e367dd53..4d271de729 100644--- a/web/src/features/datasets/components/DatasetRunsTable.tsx+++ b/web/src/features/datasets/components/DatasetRunsTable.tsx@@ -6,7 +6,7 @@ import { api } from "@/src/utils/api";import { formatIntervalSeconds } from "@/src/utils/dates";import { useQueryParams, withDefault, NumberParam } from "use-query-params";import { type RouterOutput } from "@/src/utils/types";-import { useEffect, useState } from "react";+import { useEffect, useMemo, useState } from "react";import { usdFormatter } from "../../../utils/numbers";import { DataTableToolbar } from "@/src/components/table/data-table-toolbar";import useColumnVisibility from "@/src/features/column-visibility/hooks/useColumnVisibility";@@ -14,6 +14,7 @@ import { type Prisma } from "@langfuse/shared";import { useRowHeightLocalStorage } from "@/src/components/table/data-table-row-height-switch";import { IOTableCell } from "@/src/components/ui/CodeJsonViewer";import {+ getScoreDataTypeIcon,getScoreGroupColumnProps,verifyAndPrefixScoreDataAgainstKeys,} from "@/src/features/scores/components/ScoreDetailColumnHelpers";@@ -36,6 +37,14 @@ import Link from "next/link";import { useClickhouse } from "@/src/components/layouts/ClickhouseAdminToggle";import { joinTableCoreAndMetrics } from "@/src/components/table/utils/joinTableCoreAndMetrics";import { Skeleton } from "@/src/components/ui/skeleton";+import {+ RESOURCE_METRICS,+ transformAggregatedRunMetricsToChartData,+} from "@/src/features/dashboard/lib/score-analytics-utils";+import { TimeseriesChart } from "@/src/features/scores/components/TimeseriesChart";+import { Card, CardContent } from "@/src/components/ui/card";+import { CompareViewAdapter } from "@/src/features/scores/adapters";+import { isNumericDataType } from "@/src/features/scores/lib/helpers";export type DatasetRunRowData = {id: string;@@ -93,6 +102,8 @@ const DatasetRunTableMultiSelectAction = ({export function DatasetRunsTable(props: {projectId: string;datasetId: string;+ selectedMetrics: string[];+ setScoreOptions: (options: { key: string; value: string }[]) => void;menuItems?: React.ReactNode;}) {const [paginationState, setPaginationState] = useQueryParams({@@ -105,6 +116,8 @@ export function DatasetRunsTable(props: {"datasetRuns","s",);+ const { setScoreOptions } = props;+const runs = api.datasets.runsByDatasetId.useQuery({projectId: props.projectId,datasetId: props.datasetId,@@ -149,6 +162,37 @@ export function DatasetRunsTable(props: {showAggregateViewOnly: true,});+ const scoreIdToName = useMemo(() => {+ return new Map(scoreKeysAndProps.map((obj) => [obj.key, obj.name]) ?? []);+ }, [scoreKeysAndProps]);++ const runAggregatedMetrics = useMemo(() => {+ return transformAggregatedRunMetricsToChartData(+ runsMetrics.data?.runs ?? [],+ scoreIdToName,+ );+ }, [runsMetrics.data, scoreIdToName]);++ const { scoreAnalyticsOptions, scoreKeyToData } = useMemo(() => {+ const scoreAnalyticsOptions = scoreKeysAndProps+ ? scoreKeysAndProps.map(({ key, name, dataType, source }) => ({+ key,+ value: `${getScoreDataTypeIcon(dataType)} ${name} (${source.toLowerCase()})`,+ }))+ : [];++ return {+ scoreAnalyticsOptions,+ scoreKeyToData: new Map(+ scoreKeysAndProps.map((obj) => [obj.key, obj]) ?? [],+ ),+ };+ }, [scoreKeysAndProps]);++ useEffect(() => {+ setScoreOptions(scoreAnalyticsOptions);+ }, [scoreAnalyticsOptions, setScoreOptions]);+const columns: LangfuseColumnDef<DatasetRunRowData>[] = [{id: "select",@@ -348,6 +392,51 @@ export function DatasetRunsTable(props: {return (<>+ {Boolean(props.selectedMetrics.length) &&+ Boolean(runAggregatedMetrics?.size) && (+ <Card className="my-4 max-h-[25dvh] md:max-h-[30dvh]">+ <CardContent className="mt-2 h-full">+ <div className="flex h-full w-full gap-4 overflow-x-auto">+ {props.selectedMetrics.map((key) => {+ const adapter = new CompareViewAdapter(+ runAggregatedMetrics,+ key,+ );+ const { chartData, chartLabels } = adapter.toChartData();++ const scoreData = scoreKeyToData.get(key);+ if (!scoreData)+ return (+ <TimeseriesChart+ key={key}+ chartData={chartData}+ chartLabels={chartLabels}+ title={+ RESOURCE_METRICS.find((metric) => metric.key === key)+ ?.label ?? key+ }+ type="numeric"+ />+ );++ return (+ <TimeseriesChart+ key={key}+ chartData={chartData}+ chartLabels={chartLabels}+ title={`${getScoreDataTypeIcon(scoreData.dataType)} ${scoreData.name} (${scoreData.source.toLowerCase()})`}+ type={+ isNumericDataType(scoreData.dataType)+ ? "numeric"+ : "categorical"+ }+ />+ );+ })}+ </div>+ </CardContent>+ </Card>+ )}<DataTableToolbarcolumns={columns}columnVisibility={columnVisibility}diff --git a/web/src/features/datasets/server/dataset-router.ts b/web/src/features/datasets/server/dataset-router.tsindex d40759f267..a45e50f670 100644--- a/web/src/features/datasets/server/dataset-router.ts+++ b/web/src/features/datasets/server/dataset-router.ts@@ -858,8 +858,9 @@ async function runsByDatasetIdPg(projectId: string;datasetId: string;queryClickhouse: boolean;- page: number;- limit: number;+ page?: number;+ limit?: number;+ runIds?: string[];},) {const scoresByRunId = await prisma.$queryRaw<@@ -889,10 +890,11 @@ async function runsByDatasetIdPg(runs.dataset_id = ${input.datasetId}AND runs.project_id = ${input.projectId}AND s.score IS NOT NULL+ ${input.runIds ? Prisma.sql`AND runs.id IN (${Prisma.join(input.runIds)})` : Prisma.empty}GROUP BYruns.id- LIMIT ${input.limit}- OFFSET ${input.page * input.limit}+ ${input.limit ? Prisma.sql`LIMIT ${input.limit}` : Prisma.empty}+ ${input.page && input.limit ? Prisma.sql`OFFSET ${input.page * input.limit}` : Prisma.empty}`);const runs = await prisma.$queryRaw<@@ -983,10 +985,11 @@ async function runsByDatasetIdPg(WHEREruns.dataset_id = ${input.datasetId}AND runs.project_id = ${input.projectId}+ ${input.runIds ? Prisma.sql`AND runs.id IN (${Prisma.join(input.runIds)})` : Prisma.empty}ORDER BYruns.created_at DESC- LIMIT ${input.limit}- OFFSET ${input.page * input.limit}+ ${input.limit ? Prisma.sql`LIMIT ${input.limit}` : Prisma.empty}+ ${input.page && input.limit ? Prisma.sql`OFFSET ${input.page * input.limit}` : Prisma.empty}`);const totalRuns = await prisma.datasetRuns.count({@@ -1002,7 +1005,7 @@ async function runsByDatasetIdPg(...run,scores: aggregateScores(scoresByRunId.flatMap((s) => (s.runId === run.id ? s.scores : [])),- ) as ScoreAggregate | undefined+ ) as ScoreAggregate | undefined,})),};}diff --git a/web/src/features/datasets/server/service.ts b/web/src/features/datasets/server/service.tsindex 03099a5821..2657f3dfe7 100644--- a/web/src/features/datasets/server/service.ts+++ b/web/src/features/datasets/server/service.ts@@ -1,9 +1,9 @@import {filterAndValidateDbScoreList,- paginationZod,Prisma,type PrismaClient,type DatasetRunItems,+ optionalPaginationZod,} from "@langfuse/shared";import { prisma } from "@langfuse/shared/src/db";import { v4 } from "uuid";@@ -32,7 +32,8 @@ export const datasetRunsTableSchema = z.object({projectId: z.string(),datasetId: z.string(),queryClickhouse: z.boolean().optional().default(false),- ...paginationZod,+ runIds: z.array(z.string()).optional(),+ ...optionalPaginationZod,});type PostgresRunItem = {@@ -235,10 +236,11 @@ export const getDatasetRunsFromPostgres = async (WHEREd.id = ${input.datasetId}AND d.project_id = ${input.projectId}+ ${input.runIds?.length ? Prisma.sql`AND runs.id IN (${Prisma.join(input.runIds)})` : Prisma.empty}GROUP BY runs.id, runs.name, runs.description, runs.metadata, runs.created_at, runs.updated_atORDER BY runs.created_at DESC- LIMIT ${input.limit}- OFFSET ${input.page * input.limit}+ ${input.limit ? Prisma.sql`LIMIT ${input.limit}` : Prisma.empty}+ ${input.page && input.limit ? Prisma.sql`OFFSET ${input.page * input.limit}` : Prisma.empty}`,);};diff --git a/web/src/features/scores/adapters/index.ts b/web/src/features/scores/adapters/index.tsnew file mode 100644index 0000000000..3c832b1e96--- /dev/null+++ b/web/src/features/scores/adapters/index.ts@@ -0,0 +1,49 @@+import {+ transformCategoricalScoresToChartData,+ uniqueAndSort,+} from "@/src/features/dashboard/lib/score-analytics-utils";+import {+ type ChartBin,+ type ChartData,+ type TimeseriesDataTransformer,+} from "@/src/features/scores/types";+import { type DatabaseRow } from "@/src/server/api/services/queryBuilder";+import { type DashboardDateRangeAggregationOption } from "@/src/utils/date-range-utils";++export class DashboardCategoricalScoreAdapter+ implements TimeseriesDataTransformer+{+ constructor(+ private data: DatabaseRow[],+ private timestamp: string,+ private agg?: DashboardDateRangeAggregationOption,+ ) {}++ toChartData(): ChartData {+ const { chartData, chartLabels } = transformCategoricalScoresToChartData(+ this.data,+ this.timestamp,+ this.agg,+ );+ return { chartData, chartLabels: uniqueAndSort(chartLabels) };+ }+}++export class CompareViewAdapter implements TimeseriesDataTransformer {+ constructor(+ private runMetrics: Map<+ string,+ { chartData: ChartBin[]; chartLabels: string[] }+ >,+ private key: string,+ ) {}++ toChartData(): ChartData {+ return {+ chartData: this.runMetrics.get(this.key)?.chartData ?? [],+ chartLabels: uniqueAndSort(+ this.runMetrics.get(this.key)?.chartLabels ?? [],+ ),+ };+ }+}diff --git a/web/src/features/scores/components/AnnotateDrawerContent.tsx b/web/src/features/scores/components/AnnotateDrawerContent.tsxindex f691a5a526..11b6fb3f2d 100644--- a/web/src/features/scores/components/AnnotateDrawerContent.tsx+++ b/web/src/features/scores/components/AnnotateDrawerContent.tsx@@ -61,11 +61,11 @@ import { getDefaultScoreData } from "@/src/features/scores/lib/getDefaultScoreDaimport { ToggleGroup, ToggleGroupItem } from "@/src/components/ui/toggle-group";import Header from "@/src/components/layouts/header";import { MultiSelectKeyValues } from "@/src/features/scores/components/multi-select-key-values";-import { CommandItem } from "@/src/components/ui/command";import { useRouter } from "next/router";import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";import { cn } from "@/src/utils/tailwind";import { getScoreDataTypeIcon } from "@/src/features/scores/components/ScoreDetailColumnHelpers";+import { DropdownMenuItem } from "@/src/components/ui/dropdown-menu";const AnnotationScoreDataSchema = z.object({name: z.string(),@@ -712,7 +712,7 @@ export function AnnotateDrawerContent({key: field.configId as string,}))}controlButtons={- <CommandItem+ <DropdownMenuItemonSelect={() => {capture("score_configs:manage_configs_item_click", {type: type,@@ -722,7 +722,7 @@ export function AnnotateDrawerContent({}}>Manage score configs- </CommandItem>+ </DropdownMenuItem>}/></div>diff --git a/web/src/features/scores/components/ScoreChart.tsx b/web/src/features/scores/components/ScoreChart.tsxnew file mode 100644index 0000000000..89f7cc5442--- /dev/null+++ b/web/src/features/scores/components/ScoreChart.tsx@@ -0,0 +1,80 @@+import { compactNumberFormatter } from "@/src/utils/numbers";+import { getColorsForCategories } from "@/src/features/dashboard/utils/getColorsForCategories";+import { isEmptyChart } from "@/src/features/dashboard/lib/score-analytics-utils";+import { BarChart, LineChart } from "@tremor/react";+import { NoDataOrLoading } from "@/src/components/NoDataOrLoading";+import { Card } from "@/src/components/ui/card";+import { type ChartBin } from "@/src/features/scores/types";+import { cn } from "@/src/utils/tailwind";++export function CategoricalChart(props: {+ chartData: ChartBin[];+ chartLabels: string[];+ isLoading?: boolean;+ stack?: boolean;+ showXAxis?: boolean;+ className?: string;+ chartClass?: string;+}) {+ const barCategoryGap = (chartLength: number): string => {+ if (chartLength > 7) return "10%";+ if (chartLength > 5) return "20%";+ if (chartLength > 3) return "30%";+ else return "40%";+ };+ const colors = getColorsForCategories(props.chartLabels);++ return isEmptyChart({ data: props.chartData }) ? (+ <NoDataOrLoading+ isLoading={props.isLoading ?? false}+ className={props.chartClass}+ />+ ) : (+ <Card+ className={cn("w-full rounded-tremor-default border", props.className)}+ >+ <BarChart+ className={cn("mt-4", props.chartClass)}+ data={props.chartData}+ index="binLabel"+ categories={props.chartLabels}+ colors={colors}+ valueFormatter={(number: number) =>+ Intl.NumberFormat("en-US").format(number).toString()+ }+ yAxisWidth={48}+ barCategoryGap={barCategoryGap(props.chartData.length)}+ stack={props.stack ?? true}+ showXAxis={props.showXAxis ?? true}+ />+ </Card>+ );+}++export function NumericChart(props: {+ chartData: ChartBin[];+ chartLabels: string[];+ index: string;+}) {+ const colors = getColorsForCategories(props.chartLabels);++ return isEmptyChart({ data: props.chartData }) ? (+ <NoDataOrLoading isLoading={false} />+ ) : (+ <Card className="h-full w-full rounded-tremor-default border">+ <LineChart+ className="h-full"+ data={props.chartData}+ index={props.index}+ categories={props.chartLabels}+ colors={colors}+ valueFormatter={compactNumberFormatter}+ noDataText="No data"+ showAnimation={true}+ onValueChange={() => {}}+ enableLegendSlider={true}+ showXAxis={false}+ />+ </Card>+ );+}diff --git a/web/src/features/scores/components/TimeseriesChart.tsx b/web/src/features/scores/components/TimeseriesChart.tsxnew file mode 100644index 0000000000..70e059e91c--- /dev/null+++ b/web/src/features/scores/components/TimeseriesChart.tsx@@ -0,0 +1,46 @@+import {+ CategoricalChart,+ NumericChart,+} from "@/src/features/scores/components/ScoreChart";+import { type TimeseriesChartProps } from "@/src/features/scores/types";++function ChartWrapper(props: { title: string; children: React.ReactNode }) {+ return (+ <div className="mb-2 flex w-[80%] flex-none flex-col overflow-hidden md:w-[45%]">+ <div className="shrink-0 text-sm font-medium">{props.title}</div>+ {props.children}+ </div>+ );+}++export function TimeseriesChart({+ chartData,+ chartLabels,+ title,+ type,+ index,+}: TimeseriesChartProps) {+ const chartIndex = index ?? "binLabel";++ return (+ <ChartWrapper title={title}>+ <div className="mt-2 min-h-0 flex-1">+ {type === "categorical" ? (+ <CategoricalChart+ chartLabels={chartLabels}+ chartData={chartData}+ className="h-full"+ chartClass="h-full mt-0"+ showXAxis={chartData.length < 3}+ />+ ) : (+ <NumericChart+ chartLabels={chartLabels}+ chartData={chartData}+ index={chartIndex}+ />+ )}+ </div>+ </ChartWrapper>+ );+}diff --git a/web/src/features/scores/components/multi-select-key-values.tsx b/web/src/features/scores/components/multi-select-key-values.tsxindex b3cd8df49f..7b0ecce053 100644--- a/web/src/features/scores/components/multi-select-key-values.tsx+++ b/web/src/features/scores/components/multi-select-key-values.tsx@@ -1,23 +1,21 @@import * as React from "react";-import { Archive, Check, ChevronDown } from "lucide-react";+import { Archive, ChevronDown, Component, Search } from "lucide-react";import { cn } from "@/src/utils/tailwind";import { Badge } from "@/src/components/ui/badge";import { Button } from "@/src/components/ui/button";+import { Input } from "@/src/components/ui/input";import {- Command,- CommandEmpty,- CommandGroup,- CommandInput,- CommandItem,- CommandList,- CommandSeparator,-} from "@/src/components/ui/command";-import {- Popover,- PopoverContent,- PopoverTrigger,-} from "@/src/components/ui/popover";+ DropdownMenu,+ DropdownMenuCheckboxItem,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSeparator,+ DropdownMenuSub,+ DropdownMenuSubContent,+ DropdownMenuSubTrigger,+ DropdownMenuTrigger,+} from "@/src/components/ui/dropdown-menu";import { Separator } from "@/src/components/ui/separator";type MultiSelectOptions = {@@ -28,23 +26,14 @@ type MultiSelectOptions = {isArchived?: boolean;};-export function MultiSelectKeyValues<+type MultiSelectGroup = {+ label: string;+ options: MultiSelectOptions[];+};++type MultiSelectKeyValuesProps<T extends { key: string; value: string } | string,->({- title = "Select",- placeholder,- values,- onValueChange,- options,- className,- disabled,- items = "items",- align = "center",- controlButtons,- hideClearButton = false,-}: {- title?: string;- placeholder?: string;+> = {values: T[];onValueChange: (values: T[],@@ -52,13 +41,40 @@ export function MultiSelectKeyValues<selectedKeys?: Set<string>,) => void;options: MultiSelectOptions[] | readonly MultiSelectOptions[];+ title?: string;+ placeholder?: string;+ groupedOptions?: MultiSelectGroup[];className?: string;disabled?: boolean;items?: string;align?: "center" | "end" | "start";controlButtons?: React.ReactNode;hideClearButton?: boolean;-}) {+ iconLeft?: React.ReactNode;+ iconRight?: React.ReactNode;+};++export function MultiSelectKeyValues<+ T extends { key: string; value: string } | string,+>({+ title = "Select",+ placeholder,+ values,+ onValueChange,+ options,+ groupedOptions,+ className,+ disabled,+ items = "items",+ align = "center",+ controlButtons,+ hideClearButton = false,+ iconLeft,+ iconRight,+}: MultiSelectKeyValuesProps<T>) {+ const [isOpen, setIsOpen] = React.useState(false);+ const [searchQuery, setSearchQuery] = React.useState("");+const selectedValueKeys = new Set(values.map((value) => (typeof value === "string" ? value : value.key)),);@@ -69,7 +85,11 @@ export function MultiSelectKeyValues<return Array.from(selectedValueKeys) as T[];}- return options+ const allOptions = groupedOptions+ ? groupedOptions.flatMap((group) => group.options)+ : options || [];++ return allOptions.filter((option) => !!option.key && selectedValueKeys.has(option.key)).map((option) => ({key: option.key as string,@@ -77,9 +97,77 @@ export function MultiSelectKeyValues<})) as T[];}+ const filterOptions = (options: MultiSelectOptions[]) => {+ if (!searchQuery.trim()) return options;+ const searchLower = searchQuery.toLowerCase().trim();++ return options.filter((option) => {+ const valueLower = option.value.toLowerCase();+ const keyLower = option.key?.toLowerCase() || "";+ return valueLower.includes(searchLower) || keyLower.includes(searchLower);+ });+ };++ const renderOption = (option: MultiSelectOptions) => {+ const isSelected = selectedValueKeys.has(option.key ?? option.value);+ return (+ <DropdownMenuCheckboxItem+ key={option.key ?? option.value}+ checked={isSelected}+ onSelect={(e) => e.preventDefault()}+ onCheckedChange={() => {+ const value = option.key ?? option.value;+ if (isSelected) {+ selectedValueKeys.delete(value);+ } else {+ selectedValueKeys.add(value);+ }+ const filterValues = formatFilterValues();+ onValueChange(+ filterValues.length ? filterValues : [],+ value,+ selectedValueKeys,+ );+ }}+ disabled={option.disabled}+ className="group"+ >+ <span+ className={cn(+ "capitalize",+ option.isArchived ? "text-foreground/50" : "",+ )}+ >+ {option.value}+ </span>+ {option.isArchived && (+ <Archive className="ml-2 h-4 w-4 text-foreground/50" />+ )}+ {option.count !== undefined && (+ <span className="ml-auto font-mono text-xs">{option.count}</span>+ )}+ </DropdownMenuCheckboxItem>+ );+ };++ const inputRef = React.useRef<HTMLInputElement>(null);++ const handleInputClick = (e: React.MouseEvent) => {+ e.stopPropagation();+ inputRef.current?.focus();+ };+return (- <Popover modal>- <PopoverTrigger asChild>+ <DropdownMenu+ open={isOpen}+ onOpenChange={(open) => {+ setIsOpen(open);+ if (!open) {+ setSearchQuery("");+ }+ }}+ >+ <DropdownMenuTrigger asChild><Buttonvariant="outline"className={cn(@@ -88,7 +176,9 @@ export function MultiSelectKeyValues<)}disabled={disabled}>+ {iconLeft}{title}+ {iconRight}<ChevronDown className="h-4 w-4 opacity-50" />{selectedValueKeys.size > 0 && (<>@@ -126,91 +216,84 @@ export function MultiSelectKeyValues<</>)}</Button>- </PopoverTrigger>- <PopoverContent className="w-[200px] p-0" align={align}>- <Command>- <CommandInput placeholder={placeholder} />- <CommandList>- <CommandEmpty>No results found.</CommandEmpty>- <CommandGroup>- {Boolean(options.length) ? (- options.map((option) => {- const isSelected = selectedValueKeys.has(- option.key ?? option.value,- );- return (- <CommandItem- key={option.key ?? option.value}- value={option.key ?? option.value}- keywords={[option.value]}- onSelect={(value) => {- if (isSelected) {- selectedValueKeys.delete(value);- } else {- selectedValueKeys.add(value);- }- const filterValues = formatFilterValues();-- onValueChange(- filterValues.length ? filterValues : [],- value,- selectedValueKeys,- );- }}- disabled={option.disabled}- >- <div- className={cn(- "mr-2 flex h-4 w-4 items-center justify-center rounded-sm border border-primary",- isSelected- ? "bg-primary text-primary-foreground"- : "opacity-50 [&_svg]:invisible",- option.disabled ? "opacity-50" : null,- )}- >- <Check className="h-4 w-4" />- </div>- <span- className={cn(- "overflow-x-scroll capitalize",- option.isArchived ? "text-foreground/50" : "",- )}- >- {option.value}- </span>- {option.isArchived ? (- <div className="ml-1 mt-1 flex h-4 w-4">- <Archive className="h-4 w-4 text-foreground/50"></Archive>- </div>- ) : null}- {option.count !== undefined ? (- <span className="ml-auto flex h-4 w-4 items-center justify-center pl-1 font-mono text-xs">- {option.count}- </span>- ) : null}- </CommandItem>- );- })- ) : (- <CommandItem disabled>No options found.</CommandItem>- )}- </CommandGroup>- {controlButtons || showClearItems ? (- <>- <CommandSeparator />- <CommandGroup heading="Controls">- {showClearItems && (- <CommandItem onSelect={() => onValueChange([])}>- Clear {items}- </CommandItem>- )}- {controlButtons}- </CommandGroup>- </>- ) : null}- </CommandList>- </Command>- </PopoverContent>- </Popover>+ </DropdownMenuTrigger>+ <DropdownMenuContent+ align={align}+ className="w-[200px]"+ onPointerDownOutside={() => setIsOpen(false)}+ >+ <div+ className="flex items-center border-b px-2 py-1"+ onClick={handleInputClick}+ >+ <Search className="mr-1 h-3 w-3 opacity-50" />+ <Input+ ref={inputRef}+ placeholder={placeholder}+ value={searchQuery}+ onChange={(e) => setSearchQuery(e.target.value)}+ className="h-6 border-0 bg-transparent p-0 text-sm focus-visible:ring-0"+ autoComplete="off"+ autoCorrect="off"+ spellCheck={false}+ onKeyDown={(e) => e.stopPropagation()}+ onClick={(e) => e.stopPropagation()}+ />+ </div>+ <div className="max-h-[300px] overflow-y-auto">+ {options &&+ options.length > 0 &&+ filterOptions(Array.from(options)).map(renderOption)}++ {groupedOptions?.map((group) => {+ const filteredGroupOptions = filterOptions(group.options);+ if (filteredGroupOptions.length === 0) return null;++ return (+ <DropdownMenuSub key={group.label}>+ <DropdownMenuSubTrigger className="flex w-full cursor-default select-none items-center">+ <Component className="mr-2 h-4 w-4 opacity-50" />+ <span>{group.label}</span>+ </DropdownMenuSubTrigger>+ <DropdownMenuSubContent className="max-h-[300px] overflow-y-auto">+ {filteredGroupOptions.map(renderOption)}+ </DropdownMenuSubContent>+ </DropdownMenuSub>+ );+ })}++ {searchQuery &&+ (!options || filterOptions(Array.from(options)).length === 0) &&+ (!groupedOptions ||+ !groupedOptions.some(+ (group) => filterOptions(group.options).length > 0,+ )) && (+ <div className="px-2 py-1.5 text-sm text-muted-foreground">+ No results found.+ </div>+ )}++ {showClearItems && !searchQuery && (+ <>+ <DropdownMenuSeparator />+ <DropdownMenuItem+ onSelect={(e) => {+ e.preventDefault();+ onValueChange([]);+ }}+ >+ Clear {items}+ </DropdownMenuItem>+ </>+ )}+ {controlButtons && (+ <>+ <DropdownMenuSeparator />+ {controlButtons}+ </>+ )}+ </div>+ </DropdownMenuContent>+ </DropdownMenu>);}diff --git a/web/src/features/scores/types.ts b/web/src/features/scores/types.tsnew file mode 100644index 0000000000..54601c578b--- /dev/null+++ b/web/src/features/scores/types.ts@@ -0,0 +1,30 @@+import { type ScoreDataType } from "@langfuse/shared";++export type HistogramBin = { binLabel: string; count: number };+export type CategoryCounts = Record<string, number>;+export type ChartBin = { binLabel: string } & CategoryCounts;++export type TimeseriesChartProps = {+ chartData: ChartBin[];+ chartLabels: string[];+ title: string;+ type: "numeric" | "categorical";+ index?: string;+};++export type ChartData = {+ chartData: ChartBin[];+ chartLabels: string[];+};++export type ScoreData = {+ key: string;+ name: string;+ dataType: ScoreDataType;+ source: string;+};++// Adapter interface to standardize data transformation+export interface TimeseriesDataTransformer {+ toChartData(): ChartData;+}diff --git a/web/src/pages/project/[projectId]/datasets/[datasetId]/compare.tsx b/web/src/pages/project/[projectId]/datasets/[datasetId]/compare.tsxindex 38bcbfbfe5..163661c330 100644--- a/web/src/pages/project/[projectId]/datasets/[datasetId]/compare.tsx+++ b/web/src/pages/project/[projectId]/datasets/[datasetId]/compare.tsx@@ -21,6 +21,20 @@ import {} from "@/src/components/ui/dialog";import { CreateExperimentsForm } from "@/src/ee/features/experiments/components/CreateExperimentsForm";import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";+import { DatasetAnalytics } from "@/src/features/datasets/components/DatasetAnalytics";+import { Card, CardContent } from "@/src/components/ui/card";+import { getScoreDataTypeIcon } from "@/src/features/scores/components/ScoreDetailColumnHelpers";+import { useClickhouse } from "@/src/components/layouts/ClickhouseAdminToggle";+import { TimeseriesChart } from "@/src/features/scores/components/TimeseriesChart";+import {+ isNumericDataType,+ toOrderedScoresList,+} from "@/src/features/scores/lib/helpers";+import { CompareViewAdapter } from "@/src/features/scores/adapters";+import {+ RESOURCE_METRICS,+ transformAggregatedRunMetricsToChartData,+} from "@/src/features/dashboard/lib/score-analytics-utils";export default function DatasetCompare() {const router = useRouter();@@ -29,11 +43,15 @@ export default function DatasetCompare() {const [runState, setRunState] = useQueryParams({runs: withDefault(ArrayParam, []),});+const [isCreateExperimentDialogOpen, setIsCreateExperimentDialogOpen] =useState(false);const [localRuns, setLocalRuns] = useState<Array<{ key: string; value: string }>>([]);+ const [selectedMetrics, setSelectedMetrics] = useState<string[]>(+ RESOURCE_METRICS.map((metric) => metric.key),+ );const runIds = runState.runs as undefined | string[];const hasExperimentWriteAccess = useHasProjectAccess({@@ -59,6 +77,61 @@ export default function DatasetCompare() {);const utils = api.useUtils();+ const runMetrics = api.datasets.runsByDatasetIdMetrics.useQuery(+ {+ projectId,+ datasetId,+ queryClickhouse: useClickhouse(),+ runIds: runIds,+ },+ {+ enabled: runIds && runIds.length > 1,+ },+ );++ // LFE-3236: refactor to filter query to only include scores for runs in runIds+ const scoreKeysAndProps = api.scores.getScoreKeysAndProps.useQuery(+ {+ projectId: projectId,+ selectedTimeOption: { option: "All time", filterSource: "TABLE" },+ queryClickhouse: useClickhouse(),+ },+ {+ enabled: runIds && runIds.length > 1,+ },+ );++ const scoreIdToName = useMemo(() => {+ return new Map(+ scoreKeysAndProps.data?.map((obj) => [obj.key, obj.name]) ?? [],+ );+ }, [scoreKeysAndProps.data]);++ const runAggregatedMetrics = useMemo(() => {+ return transformAggregatedRunMetricsToChartData(+ runMetrics.data?.runs.filter((run) => runIds?.includes(run.id)) ?? [],+ scoreIdToName,+ );+ }, [runMetrics.data, runIds, scoreIdToName]);++ const { scoreAnalyticsOptions, scoreKeyToData } = useMemo(() => {+ const scoreAnalyticsOptions = scoreKeysAndProps.data+ ? toOrderedScoresList(scoreKeysAndProps.data).map(+ ({ key, name, dataType, source }) => ({+ key,+ value: `${getScoreDataTypeIcon(dataType)} ${name} (${source.toLowerCase()})`,+ }),+ )+ : [];++ return {+ scoreAnalyticsOptions,+ scoreKeyToData: new Map(+ scoreKeysAndProps.data?.map((obj) => [obj.key, obj]) ?? [],+ ),+ };+ }, [scoreKeysAndProps.data]);+const handleExperimentSettled = async (data?: {success: boolean;datasetId: string;@@ -89,7 +162,7 @@ export default function DatasetCompare() {}return (- <FullScreenPage key={runIds?.join(",") ?? "empty"}>+ <FullScreenPage><Headertitle={`Compare runs: ${dataset.data?.name ?? datasetId}`}breadcrumb={[@@ -154,6 +227,15 @@ export default function DatasetCompare() {</div></PopoverContent></Popover>,+ runIds && runIds.length > 1 ? (+ <DatasetAnalytics+ key="dataset-analytics"+ projectId={projectId}+ scoreOptions={scoreAnalyticsOptions}+ selectedMetrics={selectedMetrics}+ setSelectedMetrics={setSelectedMetrics}+ />+ ) : null,<MultiSelectKeyValueskey="select-runs"title="Select runs"@@ -185,6 +267,52 @@ export default function DatasetCompare() {/>,]}/>+ {Boolean(selectedMetrics.length) &&+ Boolean(runAggregatedMetrics?.size) && (+ <Card className="my-4 max-h-[25dvh] md:max-h-[30dvh]">+ <CardContent className="mt-2 h-full">+ <div className="flex h-full w-full gap-4 overflow-x-auto">+ {selectedMetrics.map((key) => {+ const adapter = new CompareViewAdapter(+ runAggregatedMetrics,+ key,+ );+ const { chartData, chartLabels } = adapter.toChartData();++ const scoreData = scoreKeyToData.get(key);+ if (!scoreData)+ return (+ <TimeseriesChart+ key={key}+ chartData={chartData}+ chartLabels={chartLabels}+ title={+ RESOURCE_METRICS.find((metric) => metric.key === key)+ ?.label ?? key+ }+ type="numeric"+ />+ );++ return (+ <TimeseriesChart+ key={key}+ chartData={chartData}+ chartLabels={chartLabels}+ title={`${getScoreDataTypeIcon(scoreData.dataType)} ${scoreData.name} (${scoreData.source.toLowerCase()})`}+ type={+ isNumericDataType(scoreData.dataType)+ ? "numeric"+ : "categorical"+ }+ />+ );+ })}+ </div>+ </CardContent>+ </Card>+ )}+<DatasetCompareRunsTablekey={runIds?.join(",") ?? "empty"}projectId={projectId}diff --git a/web/src/pages/project/[projectId]/datasets/[datasetId]/index.tsx b/web/src/pages/project/[projectId]/datasets/[datasetId]/index.tsxindex 86a601a9b2..9c0396847d 100644--- a/web/src/pages/project/[projectId]/datasets/[datasetId]/index.tsx+++ b/web/src/pages/project/[projectId]/datasets/[datasetId]/index.tsx@@ -12,7 +12,6 @@ import { FullScreenPage } from "@/src/components/layouts/full-screen-page";import { DuplicateDatasetButton } from "@/src/features/datasets/components/DuplicateDatasetButton";import { useState } from "react";import { MultiSelectKeyValues } from "@/src/features/scores/components/multi-select-key-values";-import { CommandItem } from "@/src/components/ui/command";import { ExternalLink, FlaskConical } from "lucide-react";import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";import { useMemo } from "react";@@ -25,6 +24,9 @@ import {import { Button } from "@/src/components/ui/button";import { CreateExperimentsForm } from "@/src/ee/features/experiments/components/CreateExperimentsForm";import { showSuccessToast } from "@/src/features/notifications/showSuccessToast";+import { DropdownMenuItem } from "@/src/components/ui/dropdown-menu";+import { DatasetAnalytics } from "@/src/features/datasets/components/DatasetAnalytics";+import { RESOURCE_METRICS } from "@/src/features/dashboard/lib/score-analytics-utils";export default function Dataset() {const router = useRouter();@@ -34,6 +36,15 @@ export default function Dataset() {const hasEntitlement = useHasEntitlement("model-based-evaluations");const [isCreateExperimentDialogOpen, setIsCreateExperimentDialogOpen] =useState(false);+ const [selectedMetrics, setSelectedMetrics] = useState<string[]>(+ RESOURCE_METRICS.map((metric) => metric.key),+ );+ const [scoreOptions, setScoreOptions] = useState<+ {+ key: string;+ value: string;+ }[]+ >([]);const dataset = api.datasets.byId.useQuery({datasetId,@@ -132,6 +143,14 @@ export default function Dataset() {</DialogContent></Dialog>+ <DatasetAnalytics+ key="dataset-analytics"+ projectId={projectId}+ scoreOptions={scoreOptions}+ selectedMetrics={selectedMetrics}+ setSelectedMetrics={setSelectedMetrics}+ />+{hasReadAccess && hasEntitlement && evaluators.isSuccess && (<MultiSelectKeyValuesclassName="max-w-fit"@@ -148,14 +167,14 @@ export default function Dataset() {values={evaluatorsOptions}options={evaluatorsOptions}controlButtons={- <CommandItem+ <DropdownMenuItemonSelect={() => {window.open(`/project/${projectId}/evals`, "_blank");}}>Manage evaluators<ExternalLink className="ml-auto h-4 w-4" />- </CommandItem>+ </DropdownMenuItem>}/>)}@@ -201,6 +220,8 @@ export default function Dataset() {<DatasetRunsTableprojectId={projectId}datasetId={datasetId}+ selectedMetrics={selectedMetrics}+ setScoreOptions={setScoreOptions}menuItems={<Tabs value="runs"><TabsList>