🪢 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(data-table): break out scores to individual columns in tables (#2743)
marliessophie877bad223484
diff --git a/web/src/__tests__/aggregateScores.clienttest.ts b/web/src/__tests__/aggregateScores.clienttest.tsnew file mode 100644index 0000000000..df28df76dc--- /dev/null+++ b/web/src/__tests__/aggregateScores.clienttest.ts@@ -0,0 +1,189 @@+import { aggregateScores } from "@/src/features/scores/lib/aggregateScores";+import { type APIScore } from "@/src/features/public-api/types/scores";++describe("aggregateScores", () => {+ it("should return an empty object for an empty array", () => {+ const scores: APIScore[] = [];+ expect(aggregateScores(scores)).toEqual({});+ });++ it("should correctly aggregate a single numeric score", () => {+ const scores = [+ {+ name: "test",+ source: "API",+ dataType: "NUMERIC",+ value: 5,+ comment: "test comment",+ },+ ] as APIScore[];+ expect(aggregateScores(scores)).toEqual({+ "test-API-NUMERIC": {+ type: "NUMERIC",+ values: [5],+ average: 5,+ comment: "test comment",+ },+ });+ });++ it("should correctly aggregate multiple numeric scores with the same key", () => {+ const scores = [+ {+ name: "test",+ source: "API",+ dataType: "NUMERIC",+ value: 5,+ comment: "test comment",+ },+ {+ name: "test",+ source: "API",+ dataType: "NUMERIC",+ value: 7,+ comment: "another comment",+ },+ ] as APIScore[];+ expect(aggregateScores(scores)).toEqual({+ "test-API-NUMERIC": {+ type: "NUMERIC",+ values: [5, 7],+ average: 6,+ comment: undefined,+ },+ });+ });++ it("should correctly aggregate scores with different keys", () => {+ const scores: APIScore[] = [+ {+ name: "test1",+ source: "API",+ dataType: "NUMERIC",+ value: 5,+ comment: "test comment",+ },+ {+ name: "test1",+ source: "ANNOTATION",+ dataType: "NUMERIC",+ value: 7,+ comment: "another comment",+ },+ ] as APIScore[];+ expect(aggregateScores(scores)).toEqual({+ "test1-API-NUMERIC": {+ type: "NUMERIC",+ values: [5],+ average: 5,+ comment: "test comment",+ },+ "test1-ANNOTATION-NUMERIC": {+ type: "NUMERIC",+ values: [7],+ average: 7,+ comment: "another comment",+ },+ });+ });++ it("should correctly aggregate a single Categorical score", () => {+ const scores = [+ {+ name: "test",+ source: "ANNOTATION",+ dataType: "CATEGORICAL",+ stringValue: "good",+ comment: "test comment",+ },+ ] as APIScore[];+ expect(aggregateScores(scores)).toEqual({+ "test-ANNOTATION-CATEGORICAL": {+ type: "CATEGORICAL",+ values: ["good"],+ valueCounts: [{ value: "good", count: 1 }],+ comment: "test comment",+ },+ });+ });++ it("should correctly aggregate multiple Categorical scores with the same key", () => {+ const scores = [+ {+ name: "test",+ source: "API",+ dataType: "BOOLEAN",+ stringValue: "True",+ comment: "test comment",+ },+ {+ name: "test",+ source: "API",+ dataType: "BOOLEAN",+ stringValue: "False",+ comment: "another comment",+ },+ ] as APIScore[];+ expect(aggregateScores(scores)).toEqual({+ "test-API-BOOLEAN": {+ type: "CATEGORICAL",+ values: ["True", "False"],+ valueCounts: [+ { value: "True", count: 1 },+ { value: "False", count: 1 },+ ],+ comment: undefined,+ },+ });+ });++ it("should correctly aggregate scores with mixed types and the same name", () => {+ const scores = [+ {+ name: "test",+ source: "API",+ dataType: "NUMERIC",+ value: 5,+ comment: "test comment",+ },+ {+ name: "test",+ source: "ANNOTATION",+ dataType: "CATEGORICAL",+ stringValue: "good",+ comment: "another comment",+ },+ {+ name: "test",+ source: "ANNOTATION",+ dataType: "CATEGORICAL",+ stringValue: "bad",+ comment: "last comment",+ },+ {+ name: "test",+ source: "ANNOTATION",+ dataType: "CATEGORICAL",+ stringValue: "good",+ comment: "last comment",+ },+ ] as APIScore[];+ expect(aggregateScores(scores)).toEqual({+ "test-API-NUMERIC": {+ type: "NUMERIC",+ values: [5],+ average: 5,+ comment: "test comment",+ },+ "test-ANNOTATION-CATEGORICAL": {+ type: "CATEGORICAL",+ values: ["good", "bad", "good"],+ valueCounts: [+ { value: "good", count: 2 },+ { value: "bad", count: 1 },+ ],+ comment: undefined,+ },+ });+ });+});diff --git a/web/src/components/grouped-score-badge.tsx b/web/src/components/grouped-score-badge.tsxindex 7abc4db80f..5e9192f68a 100644--- a/web/src/components/grouped-score-badge.tsx+++ b/web/src/components/grouped-score-badge.tsx@@ -4,89 +4,61 @@ import {HoverCardContent,HoverCardTrigger,} from "@/src/components/ui/hover-card";-import {- isBooleanDataType,- isCategoricalDataType,-} from "@/src/features/manual-scoring/lib/helpers";-import { type ScoreSimplified } from "@/src/server/api/routers/generations/getAllQuery";-import { cn } from "@/src/utils/tailwind";import { MessageCircleMore } from "lucide-react";-export const GroupedScoreBadges = ({+import { type APIScore } from "@/src/features/public-api/types/scores";+import { type LastUserScore } from "@/src/features/scores/lib/types";++export const GroupedScoreBadges = <T extends APIScore | LastUserScore>({scores,- variant = "badge",}: {- scores: ScoreSimplified[];- variant?: "badge" | "headings";+ scores: T[];}) => {- const groupedScores = scores.reduce<Record<string, ScoreSimplified[]>>(- (acc, score) => {- if (!acc[score.name] || !Array.isArray(acc[score.name])) {- acc[score.name] = [score];- } else {- (acc[score.name] as ScoreSimplified[]).push(score);- }- return acc;- },- {},- );+ const groupedScores = scores.reduce<Record<string, T[]>>((acc, score) => {+ if (!acc[score.name] || !Array.isArray(acc[score.name])) {+ acc[score.name] = [score];+ } else {+ acc[score.name].push(score);+ }+ return acc;+ }, {});- const ScoresOfGroup = (props: {- scores: ScoreSimplified[];- className?: string;- }) => (- <div className={cn("text-xs", props.className)}>- {props.scores.map((s, i) => (- <span key={i} className="group/score ml-1 first:ml-0">- {isCategoricalDataType(s.dataType) || isBooleanDataType(s.dataType)- ? s.stringValue- : s.value?.toFixed(2)}- {s.comment && (- <HoverCard>- <HoverCardTrigger className="ml-1 inline-block cursor-pointer">- <MessageCircleMore size={12} />- </HoverCardTrigger>- <HoverCardContent className="overflow-hidden whitespace-normal break-normal">- <p>{s.comment}</p>- </HoverCardContent>- </HoverCard>- )}- <span className="group-last/score:hidden">,</span>- </span>- ))}- </div>- );-- if (variant === "headings")- return (- <div className="flex items-center gap-3 text-nowrap">- {Object.entries(groupedScores)- .sort(([a], [b]) => (a < b ? -1 : 1))- .map(([name, scores]) => (- <div key={name}>- <div className="text-xs text-muted-foreground">{name}</div>- <ScoresOfGroup scores={scores} />+ return (+ <>+ {Object.entries(groupedScores)+ .sort(([a], [b]) => (a < b ? -1 : 1))+ .map(([name, scores]) => (+ <Badge+ variant="outline"+ key={name}+ className="grid grid-cols-[1fr,auto] gap-1 font-normal"+ >+ <p className="truncate" title={name}>+ {name}:+ </p>+ <div className="flex items-center gap-3 text-nowrap">+ {scores.map((s, i) => (+ <span+ key={i}+ className="group/score ml-1 rounded-sm first:ml-0"+ >+ {s.stringValue ?? s.value?.toFixed(2) ?? ""}+ {s.comment && (+ <HoverCard>+ <HoverCardTrigger className="ml-1 inline-block cursor-pointer">+ <MessageCircleMore size={12} />+ </HoverCardTrigger>+ <HoverCardContent className="overflow-hidden whitespace-normal break-normal">+ <p>{s.comment}</p>+ </HoverCardContent>+ </HoverCard>+ )}+ <span className="group-last/score:hidden">,</span>+ </span>+ ))}</div>- ))}- </div>- );- else- return (- <>- {Object.entries(groupedScores)- .sort(([a], [b]) => (a < b ? -1 : 1))- .map(([name, scores]) => (- <Badge- variant="outline"- key={name}- className="grid grid-cols-[1fr,auto] gap-1 font-normal"- >- <p className="truncate" title={name}>- {name}:- </p>- <ScoresOfGroup scores={scores} />- </Badge>- ))}- </>- );+ </Badge>+ ))}+ </>+ );};diff --git a/web/src/components/scores-table-cell.tsx b/web/src/components/scores-table-cell.tsxnew file mode 100644index 0000000000..7f661ae7c0--- /dev/null+++ b/web/src/components/scores-table-cell.tsx@@ -0,0 +1,95 @@+import {+ HoverCard,+ HoverCardContent,+ HoverCardTrigger,+} from "@/src/components/ui/hover-card";+import {+ type CategoricalAggregate,+ type NumericAggregate,+} from "@/src/features/scores/lib/types";++import { numberFormatter } from "@/src/utils/numbers";+import { cn } from "@/src/utils/tailwind";+import { MessageCircleMore } from "lucide-react";++const COLOR_MAP = new Map([+ ["True", "bg-light-green p-0.5 text-dark-green"],+ ["False", "bg-light-red p-0.5 text-dark-red"],+]);+const COLLAPSE_CATEGORICAL_SCORES_AFTER = 2;++const ScoreValueCounts = ({+ valueCounts,+}: {+ valueCounts: CategoricalAggregate["valueCounts"];+}) => {+ return valueCounts.map(({ value, count }) => (+ <div key={value} className="flex flex-row">+ <span className="truncate">{value}</span>+ <span>{`: ${numberFormatter(count, 0)}`}</span>+ </div>+ ));+};++export const ScoresTableCell = ({+ aggregate,+ showSingleValue = false,+}: {+ aggregate: CategoricalAggregate | NumericAggregate;+ showSingleValue?: boolean;+}) => {+ if (showSingleValue && aggregate.values.length === 1) {+ const value =+ aggregate.type === "NUMERIC"+ ? aggregate.average.toFixed(4)+ : aggregate.values[0];++ return (+ <span className={cn("rounded-sm", COLOR_MAP.get(value))}>+ {value}+ {aggregate.comment && (+ <HoverCard>+ <HoverCardTrigger className="inline-block cursor-pointer">+ <MessageCircleMore size={12} />+ </HoverCardTrigger>+ <HoverCardContent className="overflow-hidden whitespace-normal break-normal">+ <p>{aggregate.comment}</p>+ </HoverCardContent>+ </HoverCard>+ )}+ </span>+ );+ }++ if (aggregate.type === "NUMERIC") {+ return (+ <span className="rounded-sm">{`Ø ${aggregate.average.toFixed(4)}`}</span>+ );+ }++ return (+ <div className="group">+ {aggregate.valueCounts.length > COLLAPSE_CATEGORICAL_SCORES_AFTER ? (+ <HoverCard>+ <HoverCardTrigger>+ <div className="flex cursor-pointer flex-col group-hover:text-accent-dark-blue/55">+ <ScoreValueCounts+ valueCounts={aggregate.valueCounts.slice(+ 0,+ COLLAPSE_CATEGORICAL_SCORES_AFTER,+ )}+ />+ </div>+ </HoverCardTrigger>+ <HoverCardContent className="z-20 flex max-h-[40vh] max-w-64 flex-col overflow-y-auto whitespace-normal break-normal">+ <ScoreValueCounts valueCounts={aggregate.valueCounts} />+ </HoverCardContent>+ </HoverCard>+ ) : (+ <div className="flex flex-col">+ <ScoreValueCounts valueCounts={aggregate.valueCounts} />+ </div>+ )}+ </div>+ );+};diff --git a/web/src/components/session/index.tsx b/web/src/components/session/index.tsxindex 0736149ab9..0e3661174d 100644--- a/web/src/components/session/index.tsx+++ b/web/src/components/session/index.tsx@@ -13,7 +13,7 @@ import { api } from "@/src/utils/api";import { usdFormatter } from "@/src/utils/numbers";import Link from "next/link";import { useEffect, useState } from "react";-import { AnnotateDrawer } from "@/src/features/manual-scoring/components/AnnotateDrawer";+import { AnnotateDrawer } from "@/src/features/scores/components/AnnotateDrawer";import { Button } from "@/src/components/ui/button";import useLocalStorage from "@/src/components/useLocalStorage";diff --git a/web/src/components/table/data-table-column-visibility-filter.tsx b/web/src/components/table/data-table-column-visibility-filter.tsxindex dc0dda1b01..438e37467f 100644--- a/web/src/components/table/data-table-column-visibility-filter.tsx+++ b/web/src/components/table/data-table-column-visibility-filter.tsx@@ -10,6 +10,8 @@ import {DropdownMenuContent,DropdownMenuTrigger,DropdownMenuCheckboxItem,+ DropdownMenuSeparator,+ DropdownMenuLabel,} from "@/src/components/ui/dropdown-menu";import { type VisibilityState } from "@tanstack/react-table";import { ChevronDown, Columns } from "lucide-react";@@ -23,6 +25,65 @@ interface DataTableColumnVisibilityFilterProps<TData, TValue> {setColumnVisibility: Dispatch<SetStateAction<VisibilityState>>;}+const calculateColumnCounts = <TData, TValue>(+ columns: LangfuseColumnDef<TData, TValue>[],+ columnVisibility: VisibilityState,+) => {+ return columns.reduce(+ (acc, column) => {+ if (column.columns) {+ const groupCounts = calculateColumnCounts(+ column.columns,+ columnVisibility,+ );+ acc.count += groupCounts.count;+ acc.total += groupCounts.total;+ } else if (column.enableHiding) {+ acc.total++;+ if (+ column.accessorKey in columnVisibility &&+ columnVisibility[column.accessorKey]+ ) {+ acc.count++;+ }+ }+ return acc;+ },+ { count: 0, total: 0 },+ );+};++function ColumnVisibilityDropdownItem<TData, TValue>({+ column,+ toggleColumn,+ columnVisibility,+}: {+ column: LangfuseColumnDef<TData, TValue>;+ toggleColumn: (columnId: string) => void;+ columnVisibility: VisibilityState;+}) {+ if (column.enableHiding) {+ return (+ <DropdownMenuCheckboxItem+ checked={columnVisibility[column.accessorKey]}+ onCheckedChange={() => toggleColumn(column.accessorKey)}+ >+ <span className="capitalize">+ {column.header && typeof column.header === "string"+ ? column.header+ : column.accessorKey}+ </span>+ {column.headerTooltip && (+ <DocPopup+ description={column.headerTooltip.description}+ href={column.headerTooltip.href}+ />+ )}+ </DropdownMenuCheckboxItem>+ );+ }+}+export function DataTableColumnVisibilityFilter<TData, TValue>({columns,columnVisibility,@@ -50,27 +111,6 @@ export function DataTableColumnVisibilityFilter<TData, TValue>({[setColumnVisibility],);- const calculateColumnCounts = (- columns: LangfuseColumnDef<TData, TValue>[],- columnVisibility: VisibilityState,- ) => {- return columns.reduce(- (acc, column) => {- if (column.enableHiding) {- acc.total++;- if (- column.accessorKey in columnVisibility &&- columnVisibility[column.accessorKey]- ) {- acc.count++;- }- }- return acc;- },- { count: 0, total: 0 },- );- };-const { count, total } = calculateColumnCounts(columns, columnVisibility);return (@@ -93,29 +133,38 @@ export function DataTableColumnVisibilityFilter<TData, TValue>({onPointerDownOutside={() => setIsOpen(false)}className="max-h-96 overflow-y-auto">- {columns.map(- (column, index) =>- "accessorKey" in column &&- column.enableHiding && (- <DropdownMenuCheckboxItem- key={index}- checked={columnVisibility[column.accessorKey]}- onCheckedChange={() => toggleColumn(column.accessorKey)}- >- <span className="capitalize">+ {columns.map((column, index) => {+ if (!!column.columns) {+ const isFollowingGroup = "columns" in (columns[index - 1] ?? {});+ return (+ <div key={index}>+ {!isFollowingGroup && <DropdownMenuSeparator />}+ <DropdownMenuLabel>{column.header && typeof column.header === "string"? column.header: column.accessorKey}- </span>- {column.headerTooltip && (- <DocPopup- description={column.headerTooltip.description}- href={column.headerTooltip.href}+ </DropdownMenuLabel>+ {column.columns.map((column) => (+ <ColumnVisibilityDropdownItem+ key={column.accessorKey}+ column={column}+ columnVisibility={columnVisibility}+ toggleColumn={toggleColumn}/>- )}- </DropdownMenuCheckboxItem>- ),- )}+ ))}+ <DropdownMenuSeparator />+ </div>+ );+ } else+ return (+ <ColumnVisibilityDropdownItem+ key={column.accessorKey}+ column={column}+ columnVisibility={columnVisibility}+ toggleColumn={toggleColumn}+ />+ );+ })}</DropdownMenuContent></DropdownMenu>);diff --git a/web/src/components/table/data-table.tsx b/web/src/components/table/data-table.tsxindex 5009126da1..bb83adab4b 100644--- a/web/src/components/table/data-table.tsx+++ b/web/src/components/table/data-table.tsx@@ -52,6 +52,7 @@ interface DataTableProps<TData, TValue> {className?: string;paginationClassName?: string;isBorderless?: boolean;+ shouldRenderGroupHeaders?: boolean;}export interface AsyncTableData<T> {@@ -76,6 +77,7 @@ export function DataTable<TData extends object, TValue>({className,paginationClassName,isBorderless = false,+ shouldRenderGroupHeaders = false,}: DataTableProps<TData, TValue>) {const [columnFilters, setColumnFilters] = useState<ColumnFiltersState>([]);const rowheighttw = getRowHeightTailwindClass(rowHeight);@@ -131,9 +133,15 @@ export function DataTable<TData extends object, TValue>({table.getState().columnSizingInfo,// eslint-disable-next-line react-hooks/exhaustive-depstable.getState().columnSizing,+ // eslint-disable-next-line react-hooks/exhaustive-deps+ table.getFlatHeaders(),columnVisibility,]);+ const tableHeaders = shouldRenderGroupHeaders+ ? table.getHeaderGroups()+ : [table.getHeaderGroups().slice(-1)[0]];+return (<><div@@ -151,7 +159,7 @@ export function DataTable<TData extends object, TValue>({><Table><TableHeader>- {table.getHeaderGroups().map((headerGroup) => (+ {tableHeaders.map((headerGroup) => (<TableRow key={headerGroup.id}>{headerGroup.headers.map((header) => {const columnDef = header.columndiff --git a/web/src/components/table/types.ts b/web/src/components/table/types.tsindex 4161c4ae73..c36959a41e 100644--- a/web/src/components/table/types.ts+++ b/web/src/components/table/types.ts@@ -6,14 +6,25 @@ export type TableRowOptions = {options: { label: string; value: number; icon?: LucideIcon }[];};-export type LangfuseColumnDef<- TData extends RowData,- TValue = unknown,-> = ColumnDef<TData, TValue> & {- accessorKey: string;+// extends tanstack ColumnDef to include additional properties+type ExtendedColumnDef<TData extends RowData, TValue = unknown> = ColumnDef<+ TData,+ TValue+> & {defaultHidden?: boolean;headerTooltip?: {description: string;href?: string;};};++// limits types of defined tanstack ColumnDef properties to specific subset of tanstack type union+export type LangfuseColumnDef<+ TData extends RowData,+ TValue = unknown,+> = ExtendedColumnDef<TData, TValue> & {+ // Enforce langfuse columns to be of type 'AccessorKeyColumnDefBase' with 'accessorKey' property of type string+ accessorKey: string;+ // Enforce langfuse group columns to have children of type 'LangfuseColumnDef'+ columns?: LangfuseColumnDef<TData, TValue>[];+};diff --git a/web/src/components/table/use-cases/generations.tsx b/web/src/components/table/use-cases/generations.tsxindex 49f0057c9a..8d807a1e9f 100644--- a/web/src/components/table/use-cases/generations.tsx+++ b/web/src/components/table/use-cases/generations.tsx@@ -1,9 +1,8 @@import { api, directApi } from "@/src/utils/api";-import { GroupedScoreBadges } from "@/src/components/grouped-score-badge";import { DataTable } from "@/src/components/table/data-table";import TableLink from "@/src/components/table/table-link";import { DataTableToolbar } from "@/src/components/table/data-table-toolbar";-import { useState } from "react";+import { useMemo, useState } from "react";import { TokenUsageBadge } from "@/src/components/token-usage-badge";import {DropdownMenu,@@ -39,12 +38,17 @@ import {} from "@langfuse/shared";import { useOrderByState } from "@/src/features/orderBy/hooks/useOrderByState";import type Decimal from "decimal.js";-import { type ScoreSimplified } from "@/src/server/api/routers/generations/getAllQuery";import { useRowHeightLocalStorage } from "@/src/components/table/data-table-row-height-switch";import { IOTableCell } from "@/src/components/ui/CodeJsonViewer";import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";+import {+ SCORE_GROUP_COLUMN_PROPS,+ verifyAndPrefixScoreDataAgainstKeys,+} from "@/src/features/scores/components/ScoreDetailColumnHelpers";import { useTableDateRange } from "@/src/hooks/useTableDateRange";import { useDebounce } from "@/src/hooks/useDebounce";+import { type ScoreAggregate } from "@/src/features/scores/lib/types";+import { useIndividualScoreColumns } from "@/src/features/scores/hooks/useIndividualScoreColumns";export type GenerationsTableRow = {id: string;@@ -56,6 +60,8 @@ export type GenerationsTableRow = {completionStartTime?: Date;latency?: number;timeToFirstToken?: number;+ // scores holds grouped column with individual scores+ scores: ScoreAggregate;name?: string;model?: string;// i/o and metadata not set explicitly, but fetched from the server from the cell@@ -66,7 +72,6 @@ export type GenerationsTableRow = {outputCost?: Decimal;totalCost?: Decimal;traceName?: string;- scores?: ScoreSimplified[];usage: {promptTokens: number;completionTokens: number;@@ -186,6 +191,12 @@ export default function GenerationsTable({},);+ const { scoreColumns, scoreKeysAndProps } =+ useIndividualScoreColumns<GenerationsTableRow>({+ projectId,+ scoreColumnKey: "scores",+ });+const transformFilterOptions = (filterOptions: ObservationOptions | undefined,) => {@@ -328,24 +339,7 @@ export default function GenerationsTable({);},},- {- accessorKey: "scores",- id: "scores",- header: "Scores",- size: 200,- headerTooltip: {- description:- "Scores are used to evaluate the quality of the trace. They can be automated, based on user feedback, or manually annotated. See docs to learn more.",- href: "https://langfuse.com/docs/scores",- },- cell: ({ row }) => {- const values: ScoreSimplified[] | undefined = row.getValue("scores");- return (- values && <GroupedScoreBadges scores={values} variant="headings" />- );- },- enableHiding: true,- },+ { ...SCORE_GROUP_COLUMN_PROPS, columns: scoreColumns },{accessorKey: "latency",id: "latency",@@ -656,42 +650,48 @@ export default function GenerationsTable({},},];+const [columnVisibility, setColumnVisibilityState] =useColumnVisibility<GenerationsTableRow>(- "generationsColumnVisibility",+ `generationsColumnVisibility-${projectId}`,columns,);- const rows: GenerationsTableRow[] = generations.isSuccess- ? generations.data.generations.map((generation) => {- return {- id: generation.id,- traceId: generation.traceId ?? undefined,- traceName: generation.traceName ?? "",- startTime: generation.startTime,- endTime: generation.endTime?.toLocaleString() ?? undefined,- timeToFirstToken: generation.timeToFirstToken ?? undefined,- latency: generation.latency ?? undefined,- totalCost: generation.calculatedTotalCost ?? undefined,- inputCost: generation.calculatedInputCost ?? undefined,- outputCost: generation.calculatedOutputCost ?? undefined,- name: generation.name ?? undefined,- version: generation.version ?? "",- model: generation.model ?? "",- scores: generation.scores,- level: generation.level,- statusMessage: generation.statusMessage ?? undefined,- usage: {- promptTokens: generation.promptTokens,- completionTokens: generation.completionTokens,- totalTokens: generation.totalTokens,- },- promptId: generation.promptId ?? undefined,- promptName: generation.promptName ?? undefined,- promptVersion: generation.promptVersion ?? undefined,- };- })- : [];+ const rows: GenerationsTableRow[] = useMemo(() => {+ return generations.isSuccess+ ? generations.data.generations.map((generation) => {+ return {+ id: generation.id,+ traceId: generation.traceId ?? undefined,+ traceName: generation.traceName ?? "",+ startTime: generation.startTime,+ endTime: generation.endTime?.toLocaleString() ?? undefined,+ timeToFirstToken: generation.timeToFirstToken ?? undefined,+ scores: verifyAndPrefixScoreDataAgainstKeys(+ scoreKeysAndProps,+ generation.scores,+ ),+ latency: generation.latency ?? undefined,+ totalCost: generation.calculatedTotalCost ?? undefined,+ inputCost: generation.calculatedInputCost ?? undefined,+ outputCost: generation.calculatedOutputCost ?? undefined,+ name: generation.name ?? undefined,+ version: generation.version ?? "",+ model: generation.model ?? "",+ level: generation.level,+ statusMessage: generation.statusMessage ?? undefined,+ usage: {+ promptTokens: generation.promptTokens,+ completionTokens: generation.completionTokens,+ totalTokens: generation.totalTokens,+ },+ promptId: generation.promptId ?? undefined,+ promptName: generation.promptName ?? undefined,+ promptVersion: generation.promptVersion ?? undefined,+ };+ })+ : [];+ }, [generations, scoreKeysAndProps]);return (<>diff --git a/web/src/components/table/use-cases/score-configs.tsx b/web/src/components/table/use-cases/score-configs.tsxindex 8826f727bf..116d3c7b40 100644--- a/web/src/components/table/use-cases/score-configs.tsx+++ b/web/src/components/table/use-cases/score-configs.tsx@@ -13,7 +13,7 @@ import {isBooleanDataType,isCategoricalDataType,isNumericDataType,-} from "@/src/features/manual-scoring/lib/helpers";+} from "@/src/features/scores/lib/helpers";import { Archive } from "lucide-react";import { Button } from "@/src/components/ui/button";import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";diff --git a/web/src/components/table/use-cases/scores.tsx b/web/src/components/table/use-cases/scores.tsxindex 6afeeb9f77..6c558ce98e 100644--- a/web/src/components/table/use-cases/scores.tsx+++ b/web/src/components/table/use-cases/scores.tsx@@ -7,7 +7,7 @@ import { IOTableCell } from "@/src/components/ui/CodeJsonViewer";import { Avatar, AvatarImage } from "@/src/components/ui/avatar";import useColumnVisibility from "@/src/features/column-visibility/hooks/useColumnVisibility";import { useQueryFilterState } from "@/src/features/filters/hooks/useFilterState";-import { isNumericDataType } from "@/src/features/manual-scoring/lib/helpers";+import { isNumericDataType } from "@/src/features/scores/lib/helpers";import { useOrderByState } from "@/src/features/orderBy/hooks/useOrderByState";import { useDebounce } from "@/src/hooks/useDebounce";import { useTableDateRange } from "@/src/hooks/useTableDateRange";diff --git a/web/src/components/table/use-cases/traces.tsx b/web/src/components/table/use-cases/traces.tsxindex d6b710b5e8..11379a5767 100644--- a/web/src/components/table/use-cases/traces.tsx+++ b/web/src/components/table/use-cases/traces.tsx@@ -1,4 +1,3 @@-import { GroupedScoreBadges } from "@/src/components/grouped-score-badge";import { StarTraceToggle } from "@/src/components/star-toggle";import { DataTable } from "@/src/components/table/data-table";import { TraceTableMultiSelectAction } from "@/src/components/table/data-table-multi-select-actions/trace-table-multi-select-action";@@ -12,9 +11,9 @@ import useColumnVisibility from "@/src/features/column-visibility/hooks/useColumimport { useQueryFilterState } from "@/src/features/filters/hooks/useFilterState";import { api } from "@/src/utils/api";import { formatIntervalSeconds } from "@/src/utils/dates";-import { type RouterInput, type RouterOutput } from "@/src/utils/types";+import { type RouterInput } from "@/src/utils/types";import { type RowSelectionState } from "@tanstack/react-table";-import { useEffect, useState } from "react";+import { useEffect, useMemo, useState } from "react";import {NumberParam,StringParam,@@ -37,9 +36,14 @@ import {} from "@langfuse/shared";import { useRowHeightLocalStorage } from "@/src/components/table/data-table-row-height-switch";import { IOTableCell } from "@/src/components/ui/CodeJsonViewer";-import { type APIScore } from "@/src/features/public-api/types/scores";+import {+ SCORE_GROUP_COLUMN_PROPS,+ verifyAndPrefixScoreDataAgainstKeys,+} from "@/src/features/scores/components/ScoreDetailColumnHelpers";import { useTableDateRange } from "@/src/hooks/useTableDateRange";import { useDebounce } from "@/src/hooks/useDebounce";+import { type ScoreAggregate } from "@/src/features/scores/lib/types";+import { useIndividualScoreColumns } from "@/src/features/scores/hooks/useIndividualScoreColumns";export type TracesTableRow = {bookmarked: boolean;@@ -49,6 +53,8 @@ export type TracesTableRow = {userId: string;level: ObservationLevel;observationCount: number;+ // scores holds grouped column with individual scores+ scores: ScoreAggregate;latency?: number;release?: string;version?: string;@@ -57,7 +63,6 @@ export type TracesTableRow = {input?: unknown;output?: unknown;metadata?: unknown;- scores: APIScore[];tags: string[];usage: {promptTokens: bigint;@@ -177,35 +182,12 @@ export default function TracesTable({);};- const convertToTableRow = (- trace: RouterOutput["traces"]["all"]["traces"][0],- ): TracesTableRow => {- return {- bookmarked: trace.bookmarked,- id: trace.id,- timestamp: trace.timestamp.toLocaleString(),- name: trace.name ?? "",- level: trace.level,- observationCount: trace.observationCount,- release: trace.release ?? undefined,- version: trace.version ?? undefined,- userId: trace.userId ?? "",- scores: trace.scores,- sessionId: trace.sessionId ?? undefined,- latency: trace.latency === null ? undefined : trace.latency,- tags: trace.tags,- usage: {- promptTokens: trace.promptTokens,- completionTokens: trace.completionTokens,- totalTokens: trace.totalTokens,- },- inputCost: trace.calculatedInputCost ?? undefined,- outputCost: trace.calculatedOutputCost ?? undefined,- totalCost: trace.calculatedTotalCost ?? undefined,- };- };-const [rowHeight, setRowHeight] = useRowHeightLocalStorage("traces", "s");+ const { scoreColumns, scoreKeysAndProps } =+ useIndividualScoreColumns<TracesTableRow>({+ projectId,+ scoreColumnKey: "scores",+ });const columns: LangfuseColumnDef<TracesTableRow>[] = [{@@ -408,6 +390,7 @@ export default function TracesTable({enableSorting: true,enableHiding: true,},+ { ...SCORE_GROUP_COLUMN_PROPS, columns: scoreColumns },{accessorKey: "inputCost",id: "inputCost",@@ -470,23 +453,6 @@ export default function TracesTable({enableHiding: true,enableSorting: true,},- {- accessorKey: "scores",- id: "scores",- header: "Scores",- size: 500,- headerTooltip: {- description:- "Scores are used to evaluate the quality of the trace. They can be automated, based on user feedback, or manually annotated. See docs to learn more.",- href: "https://langfuse.com/docs/scores",- },- enableColumnFilter: !omittedFilter.find((f) => f === "scores"),- cell: ({ row }) => {- const values: TracesTableRow["scores"] = row.getValue("scores");- return <GroupedScoreBadges scores={values} variant="headings" />;- },- enableHiding: true,- },{accessorKey: "input",header: "Input",@@ -652,7 +618,43 @@ export default function TracesTable({];const [columnVisibility, setColumnVisibility] =- useColumnVisibility<TracesTableRow>("tracesColumnVisibility", columns);+ useColumnVisibility<TracesTableRow>(+ `tracesColumnVisibility-${projectId}`,+ columns,+ );++ const rows = useMemo(() => {+ return traces.isSuccess+ ? traces.data.traces.map((trace) => {+ return {+ bookmarked: trace.bookmarked,+ id: trace.id,+ timestamp: trace.timestamp.toLocaleString(),+ name: trace.name ?? "",+ level: trace.level,+ observationCount: trace.observationCount,+ release: trace.release ?? undefined,+ version: trace.version ?? undefined,+ userId: trace.userId ?? "",+ sessionId: trace.sessionId ?? undefined,+ latency: trace.latency === null ? undefined : trace.latency,+ tags: trace.tags,+ usage: {+ promptTokens: trace.promptTokens,+ completionTokens: trace.completionTokens,+ totalTokens: trace.totalTokens,+ },+ scores: verifyAndPrefixScoreDataAgainstKeys(+ scoreKeysAndProps,+ trace.scores,+ ),+ inputCost: trace.calculatedInputCost ?? undefined,+ outputCost: trace.calculatedOutputCost ?? undefined,+ totalCost: trace.calculatedTotalCost ?? undefined,+ };+ })+ : [];+ }, [traces, scoreKeysAndProps]);return (<>@@ -703,7 +705,7 @@ export default function TracesTable({: {isLoading: false,isError: false,- data: traces.data.traces.map((t) => convertToTableRow(t)),+ data: rows,}}pagination={{diff --git a/web/src/components/trace/ObservationPreview.tsx b/web/src/components/trace/ObservationPreview.tsxindex 8f989bb719..3eb7c70cbd 100644--- a/web/src/components/trace/ObservationPreview.tsx+++ b/web/src/components/trace/ObservationPreview.tsx@@ -21,7 +21,7 @@ import { withDefault, StringParam, useQueryParam } from "use-query-params";import ScoresTable from "@/src/components/table/use-cases/scores";import { ScoresPreview } from "@/src/components/trace/ScoresPreview";import { JumpToPlaygroundButton } from "@/src/ee/features/playground/page/components/JumpToPlaygroundButton";-import { AnnotateDrawer } from "@/src/features/manual-scoring/components/AnnotateDrawer";+import { AnnotateDrawer } from "@/src/features/scores/components/AnnotateDrawer";import { type APIScore } from "@/src/features/public-api/types/scores";import useLocalStorage from "@/src/components/useLocalStorage";diff --git a/web/src/components/trace/TracePreview.tsx b/web/src/components/trace/TracePreview.tsxindex 01e32c4a1c..48af3b65a5 100644--- a/web/src/components/trace/TracePreview.tsx+++ b/web/src/components/trace/TracePreview.tsx@@ -18,7 +18,7 @@ import { Tabs, TabsList, TabsTrigger } from "@/src/components/ui/tabs";import { withDefault, StringParam, useQueryParam } from "use-query-params";import ScoresTable from "@/src/components/table/use-cases/scores";import { ScoresPreview } from "@/src/components/trace/ScoresPreview";-import { AnnotateDrawer } from "@/src/features/manual-scoring/components/AnnotateDrawer";+import { AnnotateDrawer } from "@/src/features/scores/components/AnnotateDrawer";import { type APIScore } from "@/src/features/public-api/types/scores";import useLocalStorage from "@/src/components/useLocalStorage";diff --git a/web/src/components/ui/table.tsx b/web/src/components/ui/table.tsxindex c11f437b89..dc5a54a747 100644--- a/web/src/components/ui/table.tsx+++ b/web/src/components/ui/table.tsx@@ -74,7 +74,7 @@ const TableHead = React.forwardRef<<thref={ref}className={cn(- "sticky top-0 z-10 rounded-t-md border-b bg-background px-4 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0",+ "sticky top-0 z-10 border-b bg-background px-4 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0",className,)}{...props}diff --git a/web/src/features/column-visibility/hooks/useColumnVisibility.ts b/web/src/features/column-visibility/hooks/useColumnVisibility.tsindex 747fe57477..d71f00cb1b 100644--- a/web/src/features/column-visibility/hooks/useColumnVisibility.ts+++ b/web/src/features/column-visibility/hooks/useColumnVisibility.ts@@ -4,20 +4,58 @@ import useLocalStorage from "@/src/components/useLocalStorage";import { useEffect } from "react";import { isEqual } from "lodash";+// returns deep copy of local storage object+const readStoredVisibilityState = (+ localStorageKey: string,+): VisibilityState => {+ if (typeof window === "undefined") {+ return {};+ }+ try {+ const storedValue = localStorage.getItem(localStorageKey);+ return storedValue ? JSON.parse(storedValue) : {};+ } catch (error) {+ console.error("Error reading from local storage", error);+ return {};+ }+};++function getColumnKeys<TData>(columns: LangfuseColumnDef<TData>[]): string[] {+ return columns+ .map(+ (column) =>+ column.columns?.map((c) => c.accessorKey) || column.accessorKey,+ )+ .flat();+}++function setVisibility<TData>(+ visibilityState: VisibilityState,+ column: LangfuseColumnDef<TData>,+) {+ if (column.columns) {+ column.columns.forEach((groupColumn) => {+ setVisibility(visibilityState, groupColumn);+ });+ } else {+ if (+ column.enableHiding &&+ !visibilityState.hasOwnProperty(column.accessorKey)+ ) {+ visibilityState[column.accessorKey] = !(column.defaultHidden === true);+ }+ }+}+function useColumnVisibility<TData>(localStorageKey: string,columns: LangfuseColumnDef<TData>[],) {const initialVisibilityState = () => {- const visibilityState: VisibilityState = {};+ const storedVisibilityState = readStoredVisibilityState(localStorageKey);+ const visibilityState: VisibilityState = storedVisibilityState;columns.forEach((column) => {- if (- "accessorKey" in column &&- typeof column.accessorKey === "string" &&- column.enableHiding- ) {- visibilityState[column.accessorKey] = !(column.defaultHidden === true);- }+ setVisibility(visibilityState, column);});return visibilityState;};@@ -27,17 +65,27 @@ function useColumnVisibility<TData>(useEffect(() => {const initialColumnVisibility = initialVisibilityState();+ const hasAllColumnsLoaded = columns.every(+ (c) => (!!c.columns && Boolean(c.columns.length)) || !c.columns,+ );+ const columnKeys = hasAllColumnsLoaded ? getColumnKeys(columns) : [];Object.keys(initialColumnVisibility).forEach((key) => {if (Object.hasOwn(columnVisibility, key)) {initialColumnVisibility[key] = columnVisibility[key];}+ if (hasAllColumnsLoaded) {+ // garbage collection in case columns are removed+ if (!columnKeys.includes(key)) {+ delete initialColumnVisibility[key];+ }+ }});if (!isEqual(initialColumnVisibility, columnVisibility)) {setColumnVisibility(initialColumnVisibility);}// eslint-disable-next-line react-hooks/exhaustive-deps- }, [columnVisibility, setColumnVisibility]);+ }, [columnVisibility, setColumnVisibility, columns]);return [columnVisibility, setColumnVisibility] as const;}diff --git a/web/src/features/datasets/components/DatasetRunItemsTable.tsx b/web/src/features/datasets/components/DatasetRunItemsTable.tsxindex 8b1e6bb17a..682650cb19 100644--- a/web/src/features/datasets/components/DatasetRunItemsTable.tsx+++ b/web/src/features/datasets/components/DatasetRunItemsTable.tsx@@ -1,24 +1,27 @@-import { GroupedScoreBadges } from "@/src/components/grouped-score-badge";import { DataTable } from "@/src/components/table/data-table";import TableLink from "@/src/components/table/table-link";import { type LangfuseColumnDef } from "@/src/components/table/types";import { api } from "@/src/utils/api";import { formatIntervalSeconds } from "@/src/utils/dates";-import { type RouterOutput } from "@/src/utils/types";import { useQueryParams, withDefault, NumberParam } from "use-query-params";-import { type APIScore } from "@/src/features/public-api/types/scores";import { usdFormatter } from "../../../utils/numbers";import useColumnVisibility from "@/src/features/column-visibility/hooks/useColumnVisibility";import { DataTableToolbar } from "@/src/components/table/data-table-toolbar";import { useDetailPageLists } from "@/src/features/navigate-detail-pages/context";-import { useEffect } from "react";+import { useEffect, useMemo } from "react";import { useRowHeightLocalStorage } from "@/src/components/table/data-table-row-height-switch";import { cn } from "@/src/utils/tailwind";import { IOTableCell } from "@/src/components/ui/CodeJsonViewer";import { ListTree } from "lucide-react";+import {+ SCORE_GROUP_COLUMN_PROPS,+ verifyAndPrefixScoreDataAgainstKeys,+} from "@/src/features/scores/components/ScoreDetailColumnHelpers";+import { type ScoreAggregate } from "@/src/features/scores/lib/types";+import { useIndividualScoreColumns } from "@/src/features/scores/hooks/useIndividualScoreColumns";-type RowData = {+export type DatasetRunItemRowData = {id: string;runAt: string;datasetItemId: string;@@ -31,7 +34,8 @@ type RowData = {output?: unknown;expectedOutput?: unknown;- scores: APIScore[];+ // scores holds grouped column with individual scores+ scores: ScoreAggregate;latency?: number;totalCost?: string;};@@ -77,7 +81,13 @@ export function DatasetRunItemsTable(// eslint-disable-next-line react-hooks/exhaustive-deps}, [runItems.isSuccess, runItems.data]);- const columns: LangfuseColumnDef<RowData>[] = [+ const { scoreColumns, scoreKeysAndProps } =+ useIndividualScoreColumns<DatasetRunItemRowData>({+ projectId: props.projectId,+ scoreColumnKey: "scores",+ });++ const columns: LangfuseColumnDef<DatasetRunItemRowData>[] = [{accessorKey: "runAt",header: "Run At",@@ -105,7 +115,7 @@ export function DatasetRunItemsTable(id: "trace",size: 60,cell: ({ row }) => {- const trace: RowData["trace"] = row.getValue("trace");+ const trace: DatasetRunItemRowData["trace"] = row.getValue("trace");if (!trace) return null;return trace.observationId ? (<TableLink@@ -129,7 +139,8 @@ export function DatasetRunItemsTable(size: 70,enableHiding: true,cell: ({ row }) => {- const latency: RowData["latency"] = row.getValue("latency");+ const latency: DatasetRunItemRowData["latency"] =+ row.getValue("latency");return <>{!!latency ? formatIntervalSeconds(latency) : null}</>;},},@@ -140,21 +151,12 @@ export function DatasetRunItemsTable(size: 60,enableHiding: true,cell: ({ row }) => {- const totalCost: RowData["totalCost"] = row.getValue("totalCost");+ const totalCost: DatasetRunItemRowData["totalCost"] =+ row.getValue("totalCost");return <>{totalCost}</>;},},- {- accessorKey: "scores",- header: "Scores",- id: "scores",- size: 150,- enableHiding: true,- cell: ({ row }) => {- const scores: RowData["scores"] = row.getValue("scores");- return <GroupedScoreBadges scores={scores} variant="headings" />;- },- },+ { ...SCORE_GROUP_COLUMN_PROPS, columns: scoreColumns },{accessorKey: "input",header: "Input",@@ -162,7 +164,7 @@ export function DatasetRunItemsTable(size: 200,enableHiding: true,cell: ({ row }) => {- const trace: RowData["trace"] = row.getValue("trace");+ const trace: DatasetRunItemRowData["trace"] = row.getValue("trace");return trace ? (<TraceObservationIOCelltraceId={trace.traceId}@@ -180,7 +182,7 @@ export function DatasetRunItemsTable(size: 200,enableHiding: true,cell: ({ row }) => {- const trace: RowData["trace"] = row.getValue("trace");+ const trace: DatasetRunItemRowData["trace"] = row.getValue("trace");return trace ? (<TraceObservationIOCelltraceId={trace.traceId}@@ -212,31 +214,38 @@ export function DatasetRunItemsTable(},];- const convertToTableRow = (- item: RouterOutput["datasets"]["runitemsByRunIdOrItemId"]["runItems"][number],- ): RowData => {- return {- id: item.id,- runAt: item.createdAt.toLocaleString(),- datasetItemId: item.datasetItemId,- trace: !!item.trace?.id- ? {- traceId: item.trace.id,- observationId: item.observation?.id,- }- : undefined,- scores: item.scores,- totalCost: !!item.observation?.calculatedTotalCost- ? usdFormatter(item.observation.calculatedTotalCost.toNumber())- : undefined,- latency: item.observation?.latency ?? item.trace?.duration ?? undefined,- };- };+ const [columnVisibility, setColumnVisibility] =+ useColumnVisibility<DatasetRunItemRowData>(+ `datasetRunsItemsColumnVisibility-${props.projectId}`,+ columns,+ );- const [columnVisibility, setColumnVisibility] = useColumnVisibility<RowData>(- "datasetRunsItemsColumnVisibility",- columns,- );+ const rows = useMemo(() => {+ return runItems.isSuccess+ ? runItems.data.runItems.map((item) => {+ return {+ id: item.id,+ runAt: item.createdAt.toLocaleString(),+ datasetItemId: item.datasetItemId,+ trace: !!item.trace?.id+ ? {+ traceId: item.trace.id,+ observationId: item.observation?.id,+ }+ : undefined,+ scores: verifyAndPrefixScoreDataAgainstKeys(+ scoreKeysAndProps,+ item.scores,+ ),+ totalCost: !!item.observation?.calculatedTotalCost+ ? usdFormatter(item.observation.calculatedTotalCost.toNumber())+ : undefined,+ latency:+ item.observation?.latency ?? item.trace?.duration ?? undefined,+ };+ })+ : [];+ }, [runItems, scoreKeysAndProps]);return (<>@@ -261,7 +270,7 @@ export function DatasetRunItemsTable(: {isLoading: false,isError: false,- data: runItems.data.runItems.map((t) => convertToTableRow(t)),+ data: rows,}}pagination={{diff --git a/web/src/features/datasets/components/DatasetRunsTable.tsx b/web/src/features/datasets/components/DatasetRunsTable.tsxindex 8a999f4199..1a1f1cf6e0 100644--- a/web/src/features/datasets/components/DatasetRunsTable.tsx+++ b/web/src/features/datasets/components/DatasetRunsTable.tsx@@ -1,4 +1,3 @@-import { GroupedScoreBadges } from "@/src/components/grouped-score-badge";import { DataTable } from "@/src/components/table/data-table";import TableLink from "@/src/components/table/table-link";import { type LangfuseColumnDef } from "@/src/components/table/types";@@ -12,11 +11,17 @@ import { useEffect } 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";-import { ScoreDataType, type Prisma } from "@langfuse/shared";+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 {+ SCORE_GROUP_COLUMN_PROPS,+ verifyAndPrefixScoreDataAgainstKeys,+} from "@/src/features/scores/components/ScoreDetailColumnHelpers";+import { type ScoreAggregate } from "@/src/features/scores/lib/types";+import { useIndividualScoreColumns } from "@/src/features/scores/hooks/useIndividualScoreColumns";-type RowData = {+export type DatasetRunRowData = {key: {id: string;name: string;@@ -25,7 +30,8 @@ type RowData = {countRunItems: string;avgLatency: number;avgTotalCost: string;- scores: RouterOutput["datasets"]["runsByDatasetId"]["runs"][number]["scores"];+ // scores holds grouped column with individual scores+ scores?: ScoreAggregate;description: string;metadata: Prisma.JsonValue;};@@ -59,14 +65,22 @@ export function DatasetRunsTable(props: {}// eslint-disable-next-line react-hooks/exhaustive-deps}, [runs.isSuccess, runs.data]);- const columns: LangfuseColumnDef<RowData>[] = [++ const { scoreColumns, scoreKeysAndProps } =+ useIndividualScoreColumns<DatasetRunRowData>({+ projectId: props.projectId,+ scoreColumnKey: "scores",+ showAggregateViewOnly: true,+ });++ const columns: LangfuseColumnDef<DatasetRunRowData>[] = [{accessorKey: "key",header: "Name",id: "key",size: 150,cell: ({ row }) => {- const key: RowData["key"] = row.getValue("key");+ const key: DatasetRunRowData["key"] = row.getValue("key");return (<TableLinkpath={`/project/${props.projectId}/datasets/${props.datasetId}/runs/${key.id}`}@@ -96,7 +110,8 @@ export function DatasetRunsTable(props: {size: 120,enableHiding: true,cell: ({ row }) => {- const avgLatency: RowData["avgLatency"] = row.getValue("avgLatency");+ const avgLatency: DatasetRunRowData["avgLatency"] =+ row.getValue("avgLatency");return <>{formatIntervalSeconds(avgLatency)}</>;},},@@ -107,31 +122,12 @@ export function DatasetRunsTable(props: {size: 130,enableHiding: true,cell: ({ row }) => {- const avgTotalCost: RowData["avgTotalCost"] =+ const avgTotalCost: DatasetRunRowData["avgTotalCost"] =row.getValue("avgTotalCost");return <>{avgTotalCost}</>;},},- {- accessorKey: "scores",- header: "Scores (avg)",- id: "scores",- size: 400,- enableHiding: true,- cell: ({ row }) => {- const scores: RowData["scores"] = row.getValue("scores");- return (- <GroupedScoreBadges- scores={Object.entries(scores).map(([k, v]) => ({- name: k,- value: v,- dataType: ScoreDataType.NUMERIC, // numeric and boolean values treated as numeric- }))}- variant="headings"- />- );- },- },+ { ...SCORE_GROUP_COLUMN_PROPS, columns: scoreColumns },{accessorKey: "createdAt",header: "Created",@@ -146,7 +142,8 @@ export function DatasetRunsTable(props: {size: 200,enableHiding: true,cell: ({ row }) => {- const metadata: RowData["metadata"] = row.getValue("metadata");+ const metadata: DatasetRunRowData["metadata"] =+ row.getValue("metadata");return !!metadata ? (<IOTableCell data={metadata} singleLine={rowHeight === "s"} />) : null;@@ -156,23 +153,27 @@ export function DatasetRunsTable(props: {const convertToTableRow = (item: RouterOutput["datasets"]["runsByDatasetId"]["runs"][number],- ): RowData => {+ ): DatasetRunRowData => {return {key: { id: item.id, name: item.name },createdAt: item.createdAt.toLocaleString(),countRunItems: item.countRunItems.toString(),avgLatency: item.avgLatency,avgTotalCost: usdFormatter(item.avgTotalCost.toNumber()),- scores: item.scores,+ scores: verifyAndPrefixScoreDataAgainstKeys(+ scoreKeysAndProps,+ item.scores,+ ),description: item.description ?? "",metadata: item.metadata,};};- const [columnVisibility, setColumnVisibility] = useColumnVisibility<RowData>(- "datasetRunsColumnVisibility",- columns,- );+ const [columnVisibility, setColumnVisibility] =+ useColumnVisibility<DatasetRunRowData>(+ `datasetRunsColumnVisibility-${props.projectId}`,+ columns,+ );return (<>diff --git a/web/src/features/datasets/server/dataset-router.ts b/web/src/features/datasets/server/dataset-router.tsindex 7a7c238f20..9597be8591 100644--- a/web/src/features/datasets/server/dataset-router.ts+++ b/web/src/features/datasets/server/dataset-router.ts@@ -14,6 +14,8 @@ import { auditLog } from "@/src/features/audit-logs/auditLog";import { DB } from "@/src/server/db";import { paginationZod } from "@langfuse/shared";import { filterAndValidateDbScoreList } from "@/src/features/public-api/types/scores";+import { aggregateScores } from "@/src/features/scores/lib/aggregateScores";+import { type ScoreSimplified } from "@/src/features/scores/lib/types";export const datasetRouter = createTRPCRouter({allDatasetMeta: protectedProjectProcedure@@ -140,13 +142,45 @@ export const datasetRouter = createTRPCRouter({}),).query(async ({ input, ctx }) => {+ const scoresByRunId = await ctx.prisma.$queryRaw<+ Array<{ scores: Array<ScoreSimplified>; runId: string }>+ >(Prisma.sql`+ SELECT+ runs.id "runId",+ array_agg(s.score) AS "scores"+ FROM+ dataset_runs runs+ JOIN datasets ON datasets.id = runs.dataset_id AND datasets.project_id = ${input.projectId}+ LEFT JOIN LATERAL (+ SELECT+ jsonb_build_object ('name', s.name, 'stringValue', s.string_value, 'value', s.value, 'source', s."source", 'dataType', s.data_type, 'comment', s.comment) AS "score"+ FROM+ dataset_run_items ri+ JOIN scores s+ ON s.trace_id = ri.trace_id+ AND (ri.observation_id IS NULL OR s.observation_id = ri.observation_id)+ AND s.project_id = ${input.projectId}+ JOIN traces t ON t.id = s.trace_id AND t.project_id = ${input.projectId}+ WHERE+ ri.project_id = ${input.projectId}+ AND ri.dataset_run_id = runs.id+ ) s ON true+ WHERE+ runs.dataset_id = ${input.datasetId}+ AND runs.project_id = ${input.projectId}+ AND s.score IS NOT NULL+ GROUP BY+ runs.id+ LIMIT ${input.limit}+ OFFSET ${input.page * input.limit}+ `);+const runs = await ctx.prisma.$queryRaw<Array<DatasetRuns & {- countRunItems: number;- scores: Record<string, number>;avgLatency: number;avgTotalCost: Prisma.Decimal;+ countRunItems: number;}>>(Prisma.sql`@@ -157,35 +191,12 @@ export const datasetRouter = createTRPCRouter({runs.metadata,runs.created_at "createdAt",runs.updated_at "updatedAt",- COALESCE(avg_scores.scores, '{}') scores,COALESCE(latency_and_total_cost."avgLatency", 0) "avgLatency",COALESCE(latency_and_total_cost."avgTotalCost", 0) "avgTotalCost",COALESCE(run_items_count.count, 0)::int "countRunItems"FROMdataset_runs runsJOIN datasets ON datasets.id = runs.dataset_id AND datasets.project_id = ${input.projectId}- LEFT JOIN LATERAL (- SELECT- jsonb_object_agg(s.name, s.avg_value) AS scores- FROM (- SELECT- s.name,- AVG(s.value) AS avg_value- FROM- dataset_run_items ri- JOIN scores s- ON s.trace_id = ri.trace_id- AND (ri.observation_id IS NULL OR s.observation_id = ri.observation_id)- AND s.project_id = ${input.projectId}- JOIN traces t ON t.id = s.trace_id AND t.project_id = ${input.projectId}- WHERE- ri.project_id = ${input.projectId}- AND s.data_type != 'CATEGORICAL'- AND s.value IS NOT NULL- AND ri.dataset_run_id = runs.id- GROUP BY s.name- ) s- ) avg_scores ON trueLEFT JOIN LATERAL (SELECTAVG(o.latency) AS "avgLatency",@@ -221,7 +232,12 @@ export const datasetRouter = createTRPCRouter({return {totalRuns,- runs,+ runs: runs.map((run) => ({+ ...run,+ scores: aggregateScores(+ scoresByRunId.flatMap((s) => (s.runId === run.id ? s.scores : [])),+ ),+ })),};}),itemById: protectedProjectProcedure@@ -645,14 +661,14 @@ export const datasetRouter = createTRPCRouter({datasetItemId: ri.datasetItemId,observation: observations.find((o) => o.id === ri.observationId),trace: traces.find((t) => t.id === ri.traceId),- scores: [+ scores: aggregateScores([...validatedTraceScores.filter((s) => s.traceId === ri.traceId),...validatedObservationScores.filter((s) =>s.observationId === ri.observationId &&s.traceId === ri.traceId,),- ],+ ]),};});diff --git a/web/src/features/prompts/server/routers/promptRouter.ts b/web/src/features/prompts/server/routers/promptRouter.tsindex 804710ca78..b44db892c9 100644--- a/web/src/features/prompts/server/routers/promptRouter.ts+++ b/web/src/features/prompts/server/routers/promptRouter.ts@@ -20,6 +20,8 @@ import {} from "@langfuse/shared";import { LATEST_PROMPT_LABEL } from "@/src/features/prompts/constants";import { PromptService, redis } from "@langfuse/shared/src/server";+import { aggregateScores } from "@/src/features/scores/lib/aggregateScores";+import { type ScoreSimplified } from "@/src/features/scores/lib/types";const PromptFilterOptions = z.object({projectId: z.string(), // Required for protectedProjectProcedure@@ -672,121 +674,89 @@ export const promptRouter = createTRPCRouter({`,);- const averageObservationScores = await ctx.prisma.$queryRaw<+ const generationScores = await ctx.prisma.$queryRaw<Array<{- prompt_id: string;- scores: Record<string, number>;+ promptId: string;+ scores: Array<ScoreSimplified>;}>- >(- Prisma.sql`- WITH avg_scores_by_prompt AS (- SELECT- o.prompt_id AS prompt_id,- s.name AS score_name,- AVG(s.value) AS average_score_value- FROM observations AS o- JOIN prompts AS p ON o.prompt_id = p.id AND p.project_id = ${input.projectId}- LEFT JOIN scores s ON o.trace_id = s.trace_id AND s.observation_id = o.id AND s.project_id = ${input.projectId}- WHERE- o.type = 'GENERATION'- AND s.data_type != 'CATEGORICAL'- AND s.value IS NOT NULL- AND o.prompt_id IS NOT NULL- AND o.project_id = ${input.projectId}- AND p.id IN (${Prisma.join(input.promptIds)})- ${filterCondition}- GROUP BY 1,2- ORDER BY 1,2- ),- json_avg_scores_by_prompt_id AS (- SELECT- prompt_id,- jsonb_object_agg(score_name,- average_score_value) AS scores- FROM- avg_scores_by_prompt AS avgs- WHERE- avgs.score_name IS NOT NULL- AND avgs.average_score_value IS NOT NULL- GROUP BY prompt_id- ORDER BY prompt_id- )- SELECT *- FROM json_avg_scores_by_prompt_id`,- );-- const averageTraceScores = await ctx.prisma.$queryRaw<- Array<{- prompt_id: string;- scores: Record<string, number>;- }>- >(- Prisma.sql`- WITH traces_by_prompt_id AS (+ >(Prisma.sql`+ SELECT+ p.id AS "promptId",+ array_agg(s.score) AS "scores"+ FROM+ prompts p+ LEFT JOIN LATERAL (SELECT- o.prompt_id,- o.trace_id+ jsonb_build_object ('name', s.name, 'stringValue', s.string_value, 'value', s.value, 'source', s."source", 'dataType', s.data_type, 'comment', s.comment) AS "score"FROM- observations o+ observations AS o+ LEFT JOIN scores s ON o.trace_id = s.trace_id+ AND s.observation_id = o.id+ AND s.project_id = ${input.projectId}WHEREo.prompt_id IS NOT NULLAND o.type = 'GENERATION'+ AND o.prompt_id = p.idAND o.project_id = ${input.projectId}- AND o.prompt_id IN (${Prisma.join(input.promptIds)})+ AND s.name IS NOT NULL+ AND p.id IN (${Prisma.join(input.promptIds)})${filterCondition}- GROUP BY- o.prompt_id,- o.trace_id- ), scores_by_trace AS (- SELECT- tp.prompt_id,- tp.trace_id,- p.version,- s.name AS score_name,- s.value AS score_value- FROM- traces_by_prompt_id tp- JOIN prompts AS p ON tp.prompt_id = p.id AND p.project_id = ${input.projectId}- LEFT JOIN scores s ON tp.trace_id = s.trace_id AND s.observation_id IS NULL AND s.project_id = ${input.projectId}- WHERE- s.data_type != 'CATEGORICAL'- AND s.value IS NOT NULL- ), average_scores_by_prompt AS (- SELECT- prompt_id,- score_name,- AVG(score_value) AS average_score_value- FROM- scores_by_trace- GROUP BY 1,2- ), json_avg_scores_by_prompt_id AS (- SELECT- prompt_id,- jsonb_object_agg(score_name,- average_score_value) AS scores- FROM- average_scores_by_prompt- WHERE- score_name IS NOT NULL- AND average_score_value IS NOT NULL- GROUP BY- prompt_id- ORDER BY- prompt_id- )- SELECT *- FROM json_avg_scores_by_prompt_id- `,- );+ ) s ON TRUE+ WHERE+ p.project_id = ${input.projectId}+ AND s.score IS NOT NULL+ GROUP BY+ p.id+ `);++ const traceScores = await ctx.prisma.$queryRaw<+ Array<{+ promptId: string;+ scores: Array<ScoreSimplified>;+ }>+ >(Prisma.sql`+ SELECT+ p.id AS "promptId",+ array_agg(s.score) AS "scores"+ FROM+ prompts p+ LEFT JOIN LATERAL (+ SELECT+ jsonb_build_object ('name', s.name, 'stringValue', s.string_value, 'value', s.value, 'source', s."source", 'dataType', s.data_type, 'comment', s.comment) AS "score"+ FROM+ scores s+ WHERE+ s.trace_id IN (+ SELECT o.trace_id+ FROM observations o+ WHERE+ o.prompt_id IS NOT NULL+ AND o.prompt_id = p.id+ AND o.type = 'GENERATION'+ AND o.project_id = ${input.projectId}+ AND o.prompt_id IN (${Prisma.join(input.promptIds)})+ ${filterCondition}+ )+ AND s.observation_id IS NULL+ AND s.project_id = ${input.projectId}+ ) s ON TRUE+ WHERE+ p.project_id = ${input.projectId}+ AND s.score IS NOT NULL+ GROUP BY+ p.id+ `);return metrics.map((metric) => ({...metric,- averageObservationScores: averageObservationScores.find(- (score) => score.prompt_id === metric.id,- )?.scores,- averageTraceScores: averageTraceScores.find(- (score) => score.prompt_id === metric.id,- )?.scores,+ observationScores: aggregateScores(+ generationScores.find((score) => score.promptId === metric.id)+ ?.scores ?? [],+ ),+ traceScores: aggregateScores(+ traceScores.find((score) => score.promptId === metric.id)?.scores ??+ [],+ ),}));}),});diff --git a/web/src/features/manual-scoring/components/AnnotateDrawer.tsx b/web/src/features/scores/components/AnnotateDrawer.tsxsimilarity index 99%rename from web/src/features/manual-scoring/components/AnnotateDrawer.tsxrename to web/src/features/scores/components/AnnotateDrawer.tsxindex 22d3a605c1..6255c4a91f 100644--- a/web/src/features/manual-scoring/components/AnnotateDrawer.tsx+++ b/web/src/features/scores/components/AnnotateDrawer.tsx@@ -59,15 +59,15 @@ import {import { Textarea } from "@/src/components/ui/textarea";import { HoverCardContent } from "@radix-ui/react-hover-card";import { HoverCard, HoverCardTrigger } from "@/src/components/ui/hover-card";-import { ScoreConfigDetails } from "@/src/features/manual-scoring/components/ScoreConfigDetails";+import { ScoreConfigDetails } from "@/src/features/scores/components/ScoreConfigDetails";import {isNumericDataType,isScoreUnsaved,-} from "@/src/features/manual-scoring/lib/helpers";-import { getDefaultScoreData } from "@/src/features/manual-scoring/lib/getDefaultScoreData";+} from "@/src/features/scores/lib/helpers";+import { getDefaultScoreData } from "@/src/features/scores/lib/getDefaultScoreData";import { ToggleGroup, ToggleGroupItem } from "@/src/components/ui/toggle-group";import Header from "@/src/components/layouts/header";-import { MultiSelectKeyValues } from "@/src/features/manual-scoring/components/multi-select-key-values";+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";diff --git a/web/src/features/manual-scoring/components/CreateScoreConfigButton.tsx b/web/src/features/scores/components/CreateScoreConfigButton.tsxsimilarity index 99%rename from web/src/features/manual-scoring/components/CreateScoreConfigButton.tsxrename to web/src/features/scores/components/CreateScoreConfigButton.tsxindex a55f3725e0..47cace907f 100644--- a/web/src/features/manual-scoring/components/CreateScoreConfigButton.tsx+++ b/web/src/features/scores/components/CreateScoreConfigButton.tsx@@ -34,7 +34,7 @@ import {isBooleanDataType,isCategoricalDataType,isNumericDataType,-} from "@/src/features/manual-scoring/lib/helpers";+} from "@/src/features/scores/lib/helpers";import { isPresent } from "@/src/utils/typeChecks";import DocPopup from "@/src/components/layouts/doc-popup";import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";diff --git a/web/src/features/manual-scoring/components/ScoreConfigDetails.tsx b/web/src/features/scores/components/ScoreConfigDetails.tsxsimilarity index 91%rename from web/src/features/manual-scoring/components/ScoreConfigDetails.tsxrename to web/src/features/scores/components/ScoreConfigDetails.tsxindex 15999814f6..b3d18aefaf 100644--- a/web/src/features/manual-scoring/components/ScoreConfigDetails.tsx+++ b/web/src/features/scores/components/ScoreConfigDetails.tsx@@ -1,4 +1,4 @@-import { isNumericDataType } from "@/src/features/manual-scoring/lib/helpers";+import { isNumericDataType } from "@/src/features/scores/lib/helpers";import { type ValidatedScoreConfig } from "@/src/features/public-api/types/score-configs";import { isPresent } from "@/src/utils/typeChecks";import React from "react";diff --git a/web/src/features/manual-scoring/components/ScoreConfigSettings.tsx b/web/src/features/scores/components/ScoreConfigSettings.tsxsimilarity index 90%rename from web/src/features/manual-scoring/components/ScoreConfigSettings.tsxrename to web/src/features/scores/components/ScoreConfigSettings.tsxindex 1d9edf81f9..61657ae7bc 100644--- a/web/src/features/manual-scoring/components/ScoreConfigSettings.tsx+++ b/web/src/features/scores/components/ScoreConfigSettings.tsx@@ -1,7 +1,7 @@import React from "react";import Header from "@/src/components/layouts/header";import { useHasAccess } from "@/src/features/rbac/utils/checkAccess";-import { CreateScoreConfigButton } from "@/src/features/manual-scoring/components/CreateScoreConfigButton";+import { CreateScoreConfigButton } from "@/src/features/scores/components/CreateScoreConfigButton";import { ScoreConfigsTable } from "@/src/components/table/use-cases/score-configs";export function ScoreConfigSettings({ projectId }: { projectId: string }) {diff --git a/web/src/features/scores/components/ScoreDetailColumnHelpers.tsx b/web/src/features/scores/components/ScoreDetailColumnHelpers.tsxnew file mode 100644index 0000000000..6176e4de8b--- /dev/null+++ b/web/src/features/scores/components/ScoreDetailColumnHelpers.tsx@@ -0,0 +1,147 @@+import { ScoresTableCell } from "@/src/components/scores-table-cell";+import { type LangfuseColumnDef } from "@/src/components/table/types";+import { type GenerationsTableRow } from "@/src/components/table/use-cases/generations";+import { type TracesTableRow } from "@/src/components/table/use-cases/traces";+import { Skeleton } from "@/src/components/ui/skeleton";+import { type DatasetRunItemRowData } from "@/src/features/datasets/components/DatasetRunItemsTable";+import { type DatasetRunRowData } from "@/src/features/datasets/components/DatasetRunsTable";+import {+ type ScoreAggregate,+ type TableRowTypesWithIndividualScoreColumns,+ type CategoricalAggregate,+ type NumericAggregate,+} from "@/src/features/scores/lib/types";+import { type PromptVersionTableRow } from "@/src/pages/project/[projectId]/prompts/[promptName]/metrics";+import { type ScoreDataType, type ScoreSource } from "@langfuse/shared";+import { type Row } from "@tanstack/react-table";+import React from "react";++type ScoreDetailColumnProps = {+ key: string;+ name: string;+ dataType: ScoreDataType;+ source: ScoreSource;+};++const prefixScoreColKey = (+ key: string,+ prefix: "Trace" | "Generation",+): string => `${prefix}-${key}`;++const getScoreDataTypeIcon = (dataType: ScoreDataType): string => {+ switch (dataType) {+ case "NUMERIC":+ default:+ return "#";+ case "CATEGORICAL":+ return "Ⓒ";+ case "BOOLEAN":+ return "Ⓑ";+ }+};++const parseScoreColumn = <+ T extends+ | TracesTableRow+ | GenerationsTableRow+ | DatasetRunRowData+ | DatasetRunItemRowData+ | PromptVersionTableRow,+>(+ col: ScoreDetailColumnProps,+ prefix?: "Trace" | "Generation",+): LangfuseColumnDef<T> => {+ const { key, name, source, dataType } = col;++ if (!!prefix) {+ return {+ header: `${prefix}: ${getScoreDataTypeIcon(dataType)} ${name} (${source.toLowerCase()})`,+ accessorKey: prefixScoreColKey(key, prefix),+ id: prefixScoreColKey(key, prefix),+ enableHiding: true,+ size: 150,+ };+ }++ return {+ header: `${getScoreDataTypeIcon(dataType)} ${name} (${source.toLowerCase()})`,+ accessorKey: key,+ id: key,+ enableHiding: true,+ size: 150,+ };+};++export function verifyAndPrefixScoreDataAgainstKeys(+ scoreKeys: ScoreDetailColumnProps[],+ scoreData: ScoreAggregate,+ prefix?: "Trace" | "Generation",+): ScoreAggregate {+ if (!Boolean(scoreKeys.length)) return {};+ let filteredScores: ScoreAggregate = {};++ const getScoreKey = (key: string) =>+ !!prefix ? prefixScoreColKey(key, prefix) : key;++ for (const key in scoreData) {+ if (scoreKeys.some((column) => column.key === key)) {+ filteredScores[getScoreKey(key)] = scoreData[key];+ }+ }++ return filteredScores;+}++export const constructIndividualScoreColumns = <+ T extends TableRowTypesWithIndividualScoreColumns,+>({+ scoreColumnProps,+ scoreColumnKey,+ showAggregateViewOnly = false,+ scoreColumnPrefix,+}: {+ scoreColumnProps: ScoreDetailColumnProps[];+ scoreColumnKey: keyof T & string;+ showAggregateViewOnly?: boolean;+ scoreColumnPrefix?: "Trace" | "Generation";+}): LangfuseColumnDef<T>[] => {+ return scoreColumnProps.map((col) => {+ const { accessorKey, header, size, enableHiding } = parseScoreColumn<T>(+ col,+ scoreColumnPrefix,+ );++ return {+ accessorKey,+ header,+ size,+ enableHiding,+ cell: ({ row }: { row: Row<T> }) => {+ const scoresData: ScoreAggregate = row.getValue(scoreColumnKey) ?? {};++ if (!Boolean(Object.keys(scoresData).length)) return null;+ if (!scoresData.hasOwnProperty(accessorKey)) return null;++ const value: CategoricalAggregate | NumericAggregate | undefined =+ scoresData[accessorKey];++ if (!value) return null;+ return (+ <ScoresTableCell+ aggregate={value}+ showSingleValue={!showAggregateViewOnly}+ />+ );+ },+ };+ });+};++export const SCORE_GROUP_COLUMN_PROPS = {+ accessorKey: "scores",+ header: "Individual Scores",+ id: "scores",+ cell: () => {+ return <Skeleton className="h-3 w-1/2"></Skeleton>;+ },+};diff --git a/web/src/features/manual-scoring/components/multi-select-key-values.tsx b/web/src/features/scores/components/multi-select-key-values.tsxsimilarity index 100%rename from web/src/features/manual-scoring/components/multi-select-key-values.tsxrename to web/src/features/scores/components/multi-select-key-values.tsxdiff --git a/web/src/features/scores/hooks/useIndividualScoreColumns.ts b/web/src/features/scores/hooks/useIndividualScoreColumns.tsnew file mode 100644index 0000000000..52441ab436--- /dev/null+++ b/web/src/features/scores/hooks/useIndividualScoreColumns.ts@@ -0,0 +1,48 @@+import { useMemo } from "react";+import { api } from "@/src/utils/api";+import { type TableRowTypesWithIndividualScoreColumns } from "@/src/features/scores/lib/types";+import { constructIndividualScoreColumns } from "@/src/features/scores/components/ScoreDetailColumnHelpers";++export function useIndividualScoreColumns<+ T extends TableRowTypesWithIndividualScoreColumns,+>({+ projectId,+ scoreColumnKey,+ showAggregateViewOnly = false,+ scoreColumnPrefix,+}: {+ projectId: string;+ scoreColumnKey: keyof T & string;+ showAggregateViewOnly?: boolean;+ scoreColumnPrefix?: "Trace" | "Generation";+}) {+ const scoreKeysAndProps = api.scores.getScoreKeysAndProps.useQuery(+ {+ projectId,+ },+ {+ trpc: {+ context: {+ skipBatch: true,+ },+ },+ refetchOnMount: false, // prevents refetching loops+ },+ );++ const scoreColumns = useMemo(() => {+ return constructIndividualScoreColumns<T>({+ scoreColumnProps: scoreKeysAndProps.data ?? [],+ scoreColumnKey,+ scoreColumnPrefix,+ showAggregateViewOnly,+ });+ }, [+ scoreKeysAndProps.data,+ scoreColumnKey,+ showAggregateViewOnly,+ scoreColumnPrefix,+ ]);++ return { scoreColumns, scoreKeysAndProps: scoreKeysAndProps.data ?? [] };+}diff --git a/web/src/features/scores/lib/aggregateScores.ts b/web/src/features/scores/lib/aggregateScores.tsnew file mode 100644index 0000000000..66619b3ef0--- /dev/null+++ b/web/src/features/scores/lib/aggregateScores.ts@@ -0,0 +1,75 @@+import {+ type ScoreAggregate,+ type ScoreSimplified,+} from "@/src/features/scores/lib/types";+import { type APIScore } from "@/src/features/public-api/types/scores";+import { type ScoreSource, type ScoreDataType } from "@langfuse/shared";++export const composeAggregateScoreKey = ({+ name,+ source,+ dataType,+}: {+ name: string;+ source: ScoreSource;+ dataType: ScoreDataType;+ keyPrefix?: string;+}): string => {+ const formattedName = name.replaceAll(/-/g, "_"); // "-" reserved for splitting in namespace+ return `${formattedName}-${source}-${dataType}`;+};++export const aggregateScores = <T extends APIScore | ScoreSimplified>(+ scores: T[],+): ScoreAggregate => {+ const groupedScores: Record<string, T[]> = scores.reduce(+ (acc, score) => {+ const key = composeAggregateScoreKey({+ name: score.name,+ source: score.source,+ dataType: score.dataType,+ });+ if (!acc[key]) {+ acc[key] = [];+ }+ acc[key].push(score);+ return acc;+ },+ {} as Record<string, T[]>,+ );++ // step 2: for each group, determine if the score is categorical or numeric & compute aggregate for group+ return Object.entries(groupedScores).reduce((acc, [key, scores]) => {+ if (scores[0].dataType === "NUMERIC") {+ const values = scores.map((score) => score.value ?? 0);+ if (!Boolean(values.length)) return acc;+ const average = values.reduce((a, b) => a + b, 0) / values.length;+ acc[key] = {+ type: "NUMERIC",+ values,+ average,+ comment: values.length === 1 ? scores[0].comment : undefined,+ };+ } else {+ const values = scores.map((score) => score.stringValue ?? "n/a");+ if (!Boolean(values.length)) return acc;+ const valueCounts = values.reduce(+ (acc, value) => {+ acc[value] = (acc[value] || 0) + 1;+ return acc;+ },+ {} as Record<string, number>,+ );+ acc[key] = {+ type: "CATEGORICAL",+ values,+ valueCounts: Object.entries(valueCounts).map(([value, count]) => ({+ value,+ count,+ })),+ comment: values.length === 1 ? scores[0].comment : undefined,+ };+ }+ return acc;+ }, {} as ScoreAggregate);+};diff --git a/web/src/features/manual-scoring/lib/getDefaultScoreData.ts b/web/src/features/scores/lib/getDefaultScoreData.tssimilarity index 100%rename from web/src/features/manual-scoring/lib/getDefaultScoreData.tsrename to web/src/features/scores/lib/getDefaultScoreData.tsdiff --git a/web/src/features/manual-scoring/lib/helpers.ts b/web/src/features/scores/lib/helpers.tssimilarity index 100%rename from web/src/features/manual-scoring/lib/helpers.tsrename to web/src/features/scores/lib/helpers.tsdiff --git a/web/src/features/scores/lib/types.ts b/web/src/features/scores/lib/types.tsnew file mode 100644index 0000000000..ddd25609db--- /dev/null+++ b/web/src/features/scores/lib/types.ts@@ -0,0 +1,49 @@+import { type ScoreDataType, type ScoreSource } from "@langfuse/shared";+import { type GenerationsTableRow } from "@/src/components/table/use-cases/generations";+import { type TracesTableRow } from "@/src/components/table/use-cases/traces";+import { type DatasetRunItemRowData } from "@/src/features/datasets/components/DatasetRunItemsTable";+import { type DatasetRunRowData } from "@/src/features/datasets/components/DatasetRunsTable";+import { type PromptVersionTableRow } from "@/src/pages/project/[projectId]/prompts/[promptName]/metrics";++export type TableRowTypesWithIndividualScoreColumns =+ | GenerationsTableRow+ | TracesTableRow+ | DatasetRunItemRowData+ | DatasetRunRowData+ | PromptVersionTableRow;++export type CategoricalAggregate = {+ type: "CATEGORICAL";+ values: string[];+ valueCounts: { value: string; count: number }[];+ comment?: string | null;+};++export type NumericAggregate = {+ type: "NUMERIC";+ values: number[];+ average: number;+ comment?: string | null;+};++export type ScoreAggregate = Record<+ string,+ CategoricalAggregate | NumericAggregate+>;++export type ScoreSimplified = {+ name: string;+ dataType: ScoreDataType;+ source: ScoreSource;+ value?: number | null;+ comment?: string | null;+ stringValue?: string | null;+};++export type LastUserScore = ScoreSimplified & {+ timestamp: string;+ traceId: string;+ observationId?: string | null;++ userId: string;+};diff --git a/web/src/pages/api/public/score-configs/index.ts b/web/src/pages/api/public/score-configs/index.tsindex cce10210d7..1ed3550999 100644--- a/web/src/pages/api/public/score-configs/index.ts+++ b/web/src/pages/api/public/score-configs/index.ts@@ -1,6 +1,6 @@import { type z } from "zod";import { Prisma, prisma } from "@langfuse/shared/src/db";-import { isBooleanDataType } from "@/src/features/manual-scoring/lib/helpers";+import { isBooleanDataType } from "@/src/features/scores/lib/helpers";import { v4 } from "uuid";import { createAuthedAPIRoute } from "@/src/features/public-api/server/createAuthedAPIRoute";import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";diff --git a/web/src/pages/project/[projectId]/prompts/[promptName]/metrics.tsx b/web/src/pages/project/[projectId]/prompts/[promptName]/metrics.tsxindex f4e0bb753c..88c26b8dcd 100644--- a/web/src/pages/project/[projectId]/prompts/[promptName]/metrics.tsx+++ b/web/src/pages/project/[projectId]/prompts/[promptName]/metrics.tsx@@ -13,13 +13,15 @@ import Link from "next/link";import TableLink from "@/src/components/table/table-link";import { usdFormatter } from "@/src/utils/numbers";import { formatIntervalSeconds } from "@/src/utils/dates";-import { GroupedScoreBadges } from "@/src/components/grouped-score-badge";import useColumnVisibility from "@/src/features/column-visibility/hooks/useColumnVisibility";import { Skeleton } from "@/src/components/ui/skeleton";-import { type FilterState, ScoreDataType } from "@langfuse/shared";+import { verifyAndPrefixScoreDataAgainstKeys } from "@/src/features/scores/components/ScoreDetailColumnHelpers";+import { type FilterState } from "@langfuse/shared";import { useTableDateRange } from "@/src/hooks/useTableDateRange";+import { type ScoreAggregate } from "@/src/features/scores/lib/types";+import { useIndividualScoreColumns } from "@/src/features/scores/hooks/useIndividualScoreColumns";-type PromptVersionTableRow = {+export type PromptVersionTableRow = {version: number;labels: string[];medianLatency?: number | null;@@ -27,8 +29,8 @@ type PromptVersionTableRow = {medianOutputTokens?: number | null;medianCost?: number | null;generationCount?: number | null;- averageObservationScores?: Record<string, number> | null;- averageTraceScores?: Record<string, number> | null;+ traceScores?: ScoreAggregate;+ generationScores?: ScoreAggregate;lastUsed?: string | null;firstUsed?: string | null;};@@ -131,6 +133,22 @@ export default function PromptVersionTable() {},);+ const { scoreColumns: traceScoreColumns, scoreKeysAndProps } =+ useIndividualScoreColumns<PromptVersionTableRow>({+ projectId,+ scoreColumnPrefix: "Trace",+ scoreColumnKey: "traceScores",+ showAggregateViewOnly: true,+ });++ const { scoreColumns: generationScoreColumns } =+ useIndividualScoreColumns<PromptVersionTableRow>({+ projectId,+ scoreColumnPrefix: "Generation",+ scoreColumnKey: "generationScores",+ showAggregateViewOnly: true,+ });+const columns: LangfuseColumnDef<PromptVersionTableRow>[] = [{accessorKey: "version",@@ -253,60 +271,22 @@ export default function PromptVersionTable() {},},{- accessorKey: "averageObservationScores",- id: "averageObservationScores",- header: "Average observation scores",- size: 250,- cell: ({ row }) => {- const scores: PromptVersionTableRow["averageObservationScores"] =- row.getValue("averageObservationScores");- if (!promptMetrics.isSuccess) {- return <Skeleton className="h-3 w-1/2" />;- }-- return (- (scores && (- <GroupedScoreBadges- scores={Object.entries(scores).map(([k, v]) => ({- name: k,- value: v,- dataType: ScoreDataType.NUMERIC, // numeric and boolean values treated as numeric- }))}- variant="headings"- />- )) ??- null- );+ accessorKey: "traceScores",+ header: "Individual Trace Scores",+ id: "traceScores",+ columns: traceScoreColumns,+ cell: () => {+ return <Skeleton className="h-3 w-1/2"></Skeleton>;},- enableHiding: true,},{- accessorKey: "averageTraceScores",- id: "averageTraceScores",- header: "Average trace scores",- size: 250,- cell: ({ row }) => {- const scores: PromptVersionTableRow["averageTraceScores"] =- row.getValue("averageTraceScores");- if (!promptMetrics.isSuccess) {- return <Skeleton className="h-3 w-1/2" />;- }-- return (- (scores && (- <GroupedScoreBadges- scores={Object.entries(scores).map(([k, v]) => ({- name: k,- value: v,- dataType: ScoreDataType.NUMERIC, // numeric and boolean values treated as numeric- }))}- variant="headings"- />- )) ??- null- );+ accessorKey: "generationScores",+ header: "Individual Generation Scores",+ id: "generationScores",+ columns: generationScoreColumns,+ cell: () => {+ return <Skeleton className="h-3 w-1/2"></Skeleton>;},- enableHiding: true,},{accessorKey: "lastUsed",@@ -350,7 +330,7 @@ export default function PromptVersionTable() {const [columnVisibility, setColumnVisibilityState] =useColumnVisibility<PromptVersionTableRow>(- "promptVersionsColumnVisibility",+ `promptVersionsColumnVisibility-${projectId}`,columns,);@@ -363,21 +343,30 @@ export default function PromptVersionTable() {const rows: PromptVersionTableRow[] =promptVersions.isSuccess && !!combinedData- ? combinedData.map((prompt) => ({- version: prompt.version,- labels: prompt.labels,- medianLatency: prompt.medianLatency,- medianInputTokens: prompt.medianInputTokens,- medianOutputTokens: prompt.medianOutputTokens,- medianCost: prompt.medianTotalCost,- generationCount: prompt.observationCount,- averageObservationScores: prompt.averageObservationScores,- averageTraceScores: prompt.averageTraceScores,- lastUsed:- prompt.lastUsed?.toLocaleString() ?? "No linked generation yet",- firstUsed:- prompt.firstUsed?.toLocaleString() ?? "No linked generation yet",- }))+ ? combinedData.map((prompt) => {+ return {+ version: prompt.version,+ labels: prompt.labels,+ medianLatency: prompt.medianLatency,+ medianInputTokens: prompt.medianInputTokens,+ medianOutputTokens: prompt.medianOutputTokens,+ medianCost: prompt.medianTotalCost,+ traceScores: verifyAndPrefixScoreDataAgainstKeys(+ scoreKeysAndProps,+ prompt.traceScores ?? {},+ "Trace",+ ),+ generationScores: verifyAndPrefixScoreDataAgainstKeys(+ scoreKeysAndProps,+ prompt.observationScores ?? {},+ "Generation",+ ),+ lastUsed:+ prompt.lastUsed?.toLocaleString() ?? "No linked generation yet",+ firstUsed:+ prompt.firstUsed?.toLocaleString() ?? "No linked generation yet",+ };+ }): [];return (diff --git a/web/src/pages/project/[projectId]/settings.tsx b/web/src/pages/project/[projectId]/settings.tsxindex 9f20cf04ce..768bfe2edd 100644--- a/web/src/pages/project/[projectId]/settings.tsx+++ b/web/src/pages/project/[projectId]/settings.tsx@@ -16,7 +16,7 @@ import { Card } from "@tremor/react";import { Button } from "@/src/components/ui/button";import Link from "next/link";import { LlmApiKeyList } from "@/src/features/public-api/components/LLMApiKeyList";-import { ScoreConfigSettings } from "@/src/features/manual-scoring/components/ScoreConfigSettings";+import { ScoreConfigSettings } from "@/src/features/scores/components/ScoreConfigSettings";export default function SettingsPage() {const router = useRouter();diff --git a/web/src/pages/project/[projectId]/users.tsx b/web/src/pages/project/[projectId]/users.tsxindex 8fde6936ee..029294d55d 100644--- a/web/src/pages/project/[projectId]/users.tsx+++ b/web/src/pages/project/[projectId]/users.tsx@@ -15,11 +15,12 @@ import { useDetailPageLists } from "@/src/features/navigate-detail-pages/contextimport { api } from "@/src/utils/api";import { compactNumberFormatter, usdFormatter } from "@/src/utils/numbers";import { type RouterInput, type RouterOutput } from "@/src/utils/types";-import { type FilterState, type Score } from "@langfuse/shared";+import { type FilterState } from "@langfuse/shared";import { usersTableCols } from "@/src/server/api/definitions/usersTable";import { joinTableCoreAndMetrics } from "@/src/components/table/utils/joinTableCoreAndMetrics";import { useTableDateRange } from "@/src/hooks/useTableDateRange";import { useDebounce } from "@/src/hooks/useDebounce";+import { type LastUserScore } from "@/src/features/scores/lib/types";export type ScoreFilterInput = Omit<RouterInput["users"]["all"], "projectId">;@@ -28,7 +29,7 @@ type RowData = {firstEvent: string;lastEvent: string;totalEvents: string;- lastScore: Score | undefined;+ lastScore: LastUserScore | undefined;totalTokens: string;totalCost: string;};@@ -218,7 +219,7 @@ export default function UsersPage() {return (<>{value ? (- <div className="flex items-center gap-4">+ <div className="grid grid-cols-[1fr,auto] items-center gap-4"><TableLinkpath={value.observationIddiff --git a/web/src/server/api/routers/generations/db/getAllGenerationsSqlQuery.ts b/web/src/server/api/routers/generations/db/getAllGenerationsSqlQuery.tsindex 4b2dff196a..ad5d15e308 100644--- a/web/src/server/api/routers/generations/db/getAllGenerationsSqlQuery.ts+++ b/web/src/server/api/routers/generations/db/getAllGenerationsSqlQuery.ts@@ -7,6 +7,8 @@ import { orderByToPrismaSql } from "@langfuse/shared";import { type ObservationView, Prisma } from "@langfuse/shared/src/db";import { prisma } from "@langfuse/shared/src/db";import { type GetAllGenerationsInput } from "../getAllQuery";+import { filterAndValidateDbScoreList } from "@/src/features/public-api/types/scores";+import { aggregateScores } from "@/src/features/scores/lib/aggregateScores";type AdditionalObservationFields = {traceName: string | null;@@ -79,7 +81,8 @@ export async function getAllGenerations({FROMscoresWHERE- project_id = ${input.projectId}+ project_id = ${input.projectId}+ AND scores."data_type" IN ('NUMERIC', 'BOOLEAN')GROUP BY1,2,@@ -147,10 +150,11 @@ export async function getAllGenerations({},},});+ const validatedScores = filterAndValidateDbScoreList(scores);const fullGenerations = generations.map((generation) => {- const filteredScores = scores.filter(- (s) => s.observationId === generation.id,+ const filteredScores = aggregateScores(+ validatedScores.filter((s) => s.observationId === generation.id),);return {...generation,diff --git a/web/src/server/api/routers/generations/filterOptionsQuery.ts b/web/src/server/api/routers/generations/filterOptionsQuery.tsindex 5525a1d8ee..59cd7fefce 100644--- a/web/src/server/api/routers/generations/filterOptionsQuery.ts+++ b/web/src/server/api/routers/generations/filterOptionsQuery.ts@@ -37,6 +37,7 @@ export const filterOptionsQuery = protectedProjectProcedurewhere: {projectId: input.projectId,timestamp: prismaStartTimeFilter,+ dataType: { in: ["NUMERIC", "BOOLEAN"] },},take: 1000,orderBy: {diff --git a/web/src/server/api/routers/generations/getAllQuery.ts b/web/src/server/api/routers/generations/getAllQuery.tsindex b05ae29ee6..b72a56e837 100644--- a/web/src/server/api/routers/generations/getAllQuery.ts+++ b/web/src/server/api/routers/generations/getAllQuery.ts@@ -2,11 +2,7 @@ import { type z } from "zod";import { protectedProjectProcedure } from "@/src/server/api/trpc";import { paginationZod } from "@langfuse/shared";-import {- type ObservationView,- Prisma,- type ScoreDataType,-} from "@langfuse/shared/src/db";+import { Prisma } from "@langfuse/shared/src/db";import { GenerationTableOptions } from "./utils/GenerationTableOptions";import { getAllGenerations } from "@/src/server/api/routers/generations/db/getAllGenerationsSqlQuery";@@ -15,24 +11,8 @@ const getAllGenerationsInput = GenerationTableOptions.extend({...paginationZod,});-export type ScoreSimplified = {- name: string;- value?: number | null;- dataType: ScoreDataType;- stringValue?: string | null;- comment?: string | null;-};-export type GetAllGenerationsInput = z.infer<typeof getAllGenerationsInput>;-export type ObservationViewWithScores = ObservationView & {- traceId: string | null;- traceName: string | null;- promptName: string | null;- promptVersion: string | null;- scores: ScoreSimplified[] | null;-};-export const getAllQuery = protectedProjectProcedure.input(getAllGenerationsInput).query(async ({ input, ctx }) => {@@ -61,7 +41,7 @@ export const getAllQuery = protectedProjectProcedurescores."project_id" = ${input.projectId}AND scores."trace_id" = t.idAND scores."observation_id" = o.id- AND scores.value IS NOT NULL+ AND scores."data_type" IN ('NUMERIC', 'BOOLEAN')GROUP BYname) tmpdiff --git a/web/src/server/api/routers/scores.ts b/web/src/server/api/routers/scores.tsindex 6a74e1bd51..54832bfc4c 100644--- a/web/src/server/api/routers/scores.ts+++ b/web/src/server/api/routers/scores.ts@@ -23,6 +23,7 @@ import {import { orderBy } from "@langfuse/shared";import { auditLog } from "@/src/features/audit-logs/auditLog";import { validateDbScore } from "@/src/features/public-api/types/scores";+import { composeAggregateScoreKey } from "@/src/features/scores/lib/aggregateScores";const ScoreFilterOptions = z.object({projectId: z.string(), // Required for protectedProjectProcedure@@ -293,6 +294,33 @@ export const scoresRouter = createTRPCRouter({},});}),+ getScoreKeysAndProps: protectedProjectProcedure+ .input(+ z.object({+ projectId: z.string(),+ }),+ )+ .query(async ({ input, ctx }) => {+ const scores = await ctx.prisma.score.groupBy({+ where: {+ projectId: input.projectId,+ },+ take: 1000,+ orderBy: {+ _count: {+ id: "desc",+ },+ },+ by: ["name", "source", "dataType"],+ });++ return scores.map(({ name, source, dataType }) => ({+ key: composeAggregateScoreKey({ name, source, dataType }),+ name: name,+ source: source,+ dataType: dataType,+ }));+ }),});const generateScoresQuery = (diff --git a/web/src/server/api/routers/traces.ts b/web/src/server/api/routers/traces.tsindex e9dd5852ae..c67d3ea55e 100644--- a/web/src/server/api/routers/traces.ts+++ b/web/src/server/api/routers/traces.ts@@ -26,6 +26,7 @@ import { instrumentAsync } from "@/src/utils/instrumentation";import type Decimal from "decimal.js";import { auditLog } from "@/src/features/audit-logs/auditLog";import { filterAndValidateDbScoreList } from "@/src/features/public-api/types/scores";+import { aggregateScores } from "@/src/features/scores/lib/aggregateScores";const TraceFilterOptions = z.object({projectId: z.string(), // Required for protectedProjectProcedure@@ -157,7 +158,9 @@ export const traceRouter = createTRPCRouter({// eslint-disable-next-line @typescript-eslint/no-unused-vars({ input, output, metadata, ...trace }) => ({...trace,- scores: validatedScores.filter((s) => s.traceId === trace.id),+ scores: aggregateScores(+ validatedScores.filter((s) => s.traceId === trace.id),+ ),}),),totalCount: totalTraceCount ? Number(totalTraceCount) : undefined,@@ -189,6 +192,7 @@ export const traceRouter = createTRPCRouter({where: {projectId: input.projectId,timestamp: prismaTimestampFilter,+ dataType: { in: ["NUMERIC", "BOOLEAN"] },},take: 1000,orderBy: {@@ -577,6 +581,7 @@ function createTracesQuery(scoresWHEREtrace_id = t.id+ AND scores."data_type" IN ('NUMERIC', 'BOOLEAN')GROUP BYname) tmpdiff --git a/web/src/server/api/routers/users.ts b/web/src/server/api/routers/users.tsindex de427c5bed..48f9a1b066 100644--- a/web/src/server/api/routers/users.ts+++ b/web/src/server/api/routers/users.ts@@ -9,8 +9,9 @@ import {singleFilter,tableColumnsToSqlFilterAndPrefix,} from "@langfuse/shared";-import { Prisma, type Score } from "@langfuse/shared/src/db";+import { Prisma } from "@langfuse/shared/src/db";import { usersTableCols } from "@/src/server/api/definitions/usersTable";+import { type LastUserScore } from "@/src/features/scores/lib/types";const UserFilterOptions = z.object({projectId: z.string(), // Required for protectedProjectProcedure@@ -153,11 +154,7 @@ export const userRouter = createTRPCRouter({}const lastScoresOfUsers = await ctx.prisma.$queryRaw<- Array<- Score & {- userId: string;- }- >+ Array<LastUserScore>>`WITH ranked_scores AS (SELECT@@ -182,7 +179,10 @@ export const userRouter = createTRPCRouter({"value",observation_id "observationId",trace_id "traceId",- "comment"+ "comment",+ "source",+ data_type "dataType",+ "string_value" "stringValue"FROMranked_scoresWHERE rn = 1@@ -250,11 +250,7 @@ export const userRouter = createTRPCRouter({`;const lastScoresOfUsers = await ctx.prisma.$queryRaw<- Array<- Score & {- userId: string;- }- >+ Array<LastUserScore>>`WITH ranked_scores AS (SELECT@@ -279,7 +275,10 @@ export const userRouter = createTRPCRouter({"value",observation_id "observationId",trace_id "traceId",- "comment"+ "comment",+ "source",+ data_type "dataType",+ "string_value" "stringValue"FROMranked_scoresWHERE rn = 1