Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

feat(dataset-compare): add diff view for cost/latency metrics (#10155)

marliessophie58c177948f04
diff --git a/web/src/components/ui/badge.tsx b/web/src/components/ui/badge.tsx
index b8126f9d5c..7a5fb7ec29 100644
--- a/web/src/components/ui/badge.tsx
+++ b/web/src/components/ui/badge.tsx
@@ -4,22 +4,29 @@ import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@/src/utils/tailwind";
const badgeVariants = cva(
- "inline-flex items-center rounded-md border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",
+ "inline-flex items-center rounded-md border border-transparent font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",
{
variants: {
variant: {
- default:
- "border-transparent bg-primary text-primary-foreground hover:bg-primary/80",
+ default: "bg-primary text-primary-foreground hover:bg-primary/80",
secondary:
- "border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",
+ "bg-secondary text-secondary-foreground hover:bg-secondary/80",
destructive:
- "border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",
+ "bg-destructive text-destructive-foreground hover:bg-destructive/80",
outline: "text-foreground",
tertiary: "bg-tertiary text-tertiary-foreground",
+ success: "bg-light-green text-dark-green",
+ error: "bg-light-red text-dark-red",
+ warning: "bg-light-yellow text-dark-yellow",
+ },
+ size: {
+ default: "px-2.5 py-0.5 text-xs",
+ sm: "px-1 py-0 text-xs",
},
},
defaultVariants: {
variant: "default",
+ size: "default",
},
},
);
@@ -28,9 +35,12 @@ export interface BadgeProps
extends React.HTMLAttributes<HTMLDivElement>,
VariantProps<typeof badgeVariants> {}
-function Badge({ className, variant, ...props }: BadgeProps) {
+function Badge({ className, variant, size, ...props }: BadgeProps) {
return (
- <div className={cn(badgeVariants({ variant }), className)} {...props} />
+ <div
+ className={cn(badgeVariants({ variant, size }), className)}
+ {...props}
+ />
);
}
diff --git a/web/src/features/datasets/components/DatasetAggregateTableCell.tsx b/web/src/features/datasets/components/DatasetAggregateTableCell.tsx
index 8da7aaa896..a1ff341511 100644
--- a/web/src/features/datasets/components/DatasetAggregateTableCell.tsx
+++ b/web/src/features/datasets/components/DatasetAggregateTableCell.tsx
@@ -19,8 +19,10 @@ import { useTrpcError } from "@/src/hooks/useTrpcError";
import { Card } from "@/src/components/ui/card";
import { type ScoreAggregate } from "@langfuse/shared";
import { computeScoreDiffs } from "@/src/features/datasets/lib/computeScoreDiffs";
-import { type ScoreDiff } from "@/src/features/datasets/lib/calculateScoreDiff";
import { useMemo } from "react";
+import { type BaselineDiff } from "@/src/features/datasets/lib/calculateBaselineDiff";
+import { DiffLabel } from "@/src/features/datasets/components/DiffLabel";
+import { useResourceMetricsDiff } from "@/src/features/datasets/hooks/useResourceMetricsDiff";
const DatasetAggregateCellContent = ({
projectId,
@@ -28,12 +30,14 @@ const DatasetAggregateCellContent = ({
scores,
serverScoreColumns,
scoreDiffs,
+ baselineRunValue,
}: {
projectId: string;
value: EnrichedDatasetRunItem;
scores: ScoreAggregate;
serverScoreColumns: ScoreColumn[];
- scoreDiffs?: Record<string, ScoreDiff>;
+ scoreDiffs?: Record<string, BaselineDiff>;
+ baselineRunValue?: EnrichedDatasetRunItem;
}) => {
const router = useRouter();
const silentHttpCodes = [404];
@@ -95,9 +99,8 @@ const DatasetAggregateCellContent = ({
silentHttpCodes,
);
- const latency = value.observation?.latency ?? value.trace.duration;
- const totalCost =
- value.observation?.calculatedTotalCost ?? value.trace.totalCost;
+ const { latency, totalCost, latencyDiff, totalCostDiff } =
+ useResourceMetricsDiff(value, baselineRunValue);
// Note that we implement custom handling for opening peek view from cell
const handleOpenPeek = () => {
@@ -139,33 +142,10 @@ const DatasetAggregateCellContent = ({
return (
<div
className={cn(
- "group relative flex h-full w-full flex-col gap-2 overflow-hidden rounded-md border-2 border-transparent",
+ "group flex h-full w-full flex-col overflow-hidden rounded-md border-2 border-transparent",
isActiveCell && "border-accent-dark-blue",
)}
>
- {!(isSilentError || isLoading) && (
- <div className="absolute bottom-2 right-2 z-10 flex flex-row gap-1">
- {/* Triggers review/annotation */}
- <Button
- disabled={!hasAnnotationWriteAccess}
- variant="outline"
- className="h-6 px-1 text-xs opacity-0 transition-opacity group-hover:opacity-100"
- onClick={handleOpenReview}
- >
- Annotate
- </Button>
- {/* Triggers peek view */}
- <Button
- variant="outline"
- size="icon"
- className="h-6 w-6 p-0 opacity-0 transition-opacity group-hover:opacity-100"
- title="View trace/observation"
- onClick={handleOpenPeek}
- >
- <ListTree className="h-3 w-3" />
- </Button>
- </div>
- )}
{/* Displays trace/observation output */}
<div
className={cn(
@@ -194,12 +174,12 @@ const DatasetAggregateCellContent = ({
{/* Displays scores */}
<div
className={cn(
- "flex max-h-[50%] flex-shrink overflow-hidden px-1",
+ "flex min-h-0 flex-1 overflow-hidden px-1 py-2",
!selectedFields.includes("scores") && "hidden",
)}
>
- <div className="mt-1 w-full min-w-0 overflow-hidden @container">
- <div className="grid max-h-full w-full grid-cols-1 gap-1 overflow-y-auto @[400px]:grid-cols-2">
+ <div className="w-full min-w-0 overflow-hidden @container">
+ <div className="grid max-h-full w-full grid-cols-1 gap-1 overflow-y-auto @[500px]:grid-cols-2">
{mergedScoreColumns.length > 0 ? (
mergedScoreColumns.map((scoreColumn) => (
<ScoreRow
@@ -217,31 +197,66 @@ const DatasetAggregateCellContent = ({
</div>
</div>
</div>
- {/* Displays latency and cost */}
+ {/* Displays resource metrics and action buttons */}
{!isLoading && (
- <div
- className={cn(
- "flex max-h-fit flex-shrink-0 px-1",
- !selectedFields.includes("resourceMetrics") && "hidden",
- )}
- >
- <div className="max-h-fit w-full min-w-0">
- <div className="flex w-full flex-row flex-wrap gap-1">
- {!!latency && (
- <Badge variant="tertiary" className="p-0.5 px-1 font-normal">
+ <div className="mt-auto flex min-h-6 flex-shrink-0 items-center justify-between gap-2 px-1 pb-1">
+ <div
+ className={cn(
+ "flex flex-row flex-wrap gap-1",
+ !selectedFields.includes("resourceMetrics") && "hidden",
+ )}
+ >
+ {!!latency &&
+ (latencyDiff ? (
+ <DiffLabel
+ diff={latencyDiff}
+ formatValue={(value) => formatIntervalSeconds(value)}
+ className="ml-1"
+ />
+ ) : (
+ <Badge variant="tertiary" size="sm" className="font-normal">
<ClockIcon className="mb-0.5 mr-1 h-3 w-3" />
<span className="capitalize">
{formatIntervalSeconds(latency)}
</span>
</Badge>
- )}
- {totalCost && (
- <Badge variant="tertiary" className="p-0.5 px-1 font-normal">
+ ))}
+ {totalCost &&
+ (totalCostDiff ? (
+ <DiffLabel
+ diff={totalCostDiff}
+ formatValue={(value) => usdFormatter(value, 2, 4)}
+ className="ml-1"
+ />
+ ) : (
+ <Badge variant="tertiary" size="sm" className="font-normal">
<span className="mr-0.5">{usdFormatter(totalCost)}</span>
</Badge>
- )}
- </div>
+ ))}
</div>
+ {!(isSilentError || isLoading) && (
+ <div className="flex flex-row gap-1 opacity-0 transition-opacity group-hover:opacity-100">
+ {/* Triggers review/annotation */}
+ <Button
+ disabled={!hasAnnotationWriteAccess}
+ variant="outline"
+ className="h-6 px-1 text-xs"
+ onClick={handleOpenReview}
+ >
+ Annotate
+ </Button>
+ {/* Triggers peek view */}
+ <Button
+ variant="outline"
+ size="icon"
+ className="h-6 w-6 p-0"
+ title="View trace/observation"
+ onClick={handleOpenPeek}
+ >
+ <ListTree className="h-3 w-3" />
+ </Button>
+ </div>
+ )}
</div>
)}
</div>
@@ -285,6 +300,7 @@ const DatasetAggregateCellAgainstBaseline = ({
serverScoreColumns={serverScoreColumns}
scores={displayScores}
scoreDiffs={scoreDiffs}
+ baselineRunValue={baselineRunValue}
/>
);
};
diff --git a/web/src/features/datasets/components/DiffLabel.tsx b/web/src/features/datasets/components/DiffLabel.tsx
new file mode 100644
index 0000000000..acc3be49ab
--- /dev/null
+++ b/web/src/features/datasets/components/DiffLabel.tsx
@@ -0,0 +1,39 @@
+import { Badge } from "@/src/components/ui/badge";
+import {
+ type CategoricalDiff,
+ type NumericDiff,
+} from "@/src/features/datasets/lib/calculateBaselineDiff";
+import { cn } from "@/src/utils/tailwind";
+
+/**
+ * Displays a diff value with color coding
+ * Used for scores, latency, and cost diffs in compare view
+ */
+export function DiffLabel({
+ diff,
+ formatValue,
+ className,
+}: {
+ diff: NumericDiff | CategoricalDiff;
+ formatValue: (value: number) => string;
+ className?: string;
+}) {
+ if (diff.type === "NUMERIC") {
+ return (
+ <Badge
+ size="sm"
+ variant={diff.direction === "+" ? "success" : "error"}
+ className={cn("font-semibold", className)}
+ >
+ {diff.direction}
+ {formatValue(diff.absoluteDifference)}
+ </Badge>
+ );
+ }
+ if (diff.isDifferent)
+ return (
+ <Badge size="sm" variant="warning" className="font-semibold">
+ Varies
+ </Badge>
+ );
+}
diff --git a/web/src/features/datasets/hooks/useResourceMetricsDiff.ts b/web/src/features/datasets/hooks/useResourceMetricsDiff.ts
new file mode 100644
index 0000000000..0b24a01610
--- /dev/null
+++ b/web/src/features/datasets/hooks/useResourceMetricsDiff.ts
@@ -0,0 +1,33 @@
+import { calculateNumericDiff } from "@/src/features/datasets/lib/calculateBaselineDiff";
+import { type EnrichedDatasetRunItem } from "@langfuse/shared/src/server";
+
+const getLatency = (runItem: EnrichedDatasetRunItem) => {
+ return runItem.observation?.latency ?? runItem.trace.duration;
+};
+
+const getTotalCost = (runItem: EnrichedDatasetRunItem) => {
+ return runItem.observation?.calculatedTotalCost ?? runItem.trace.totalCost;
+};
+
+export function useResourceMetricsDiff(
+ current: EnrichedDatasetRunItem,
+ baseline?: EnrichedDatasetRunItem | null,
+) {
+ const baseProps = {
+ latency: getLatency(current),
+ totalCost: getTotalCost(current),
+ latencyDiff: null,
+ totalCostDiff: null,
+ };
+
+ if (!baseline) return baseProps;
+
+ return {
+ ...baseProps,
+ latencyDiff: calculateNumericDiff(baseProps.latency, getLatency(baseline)),
+ totalCostDiff: calculateNumericDiff(
+ baseProps.totalCost,
+ getTotalCost(baseline),
+ ),
+ };
+}
diff --git a/web/src/features/datasets/lib/calculateBaselineDiff.ts b/web/src/features/datasets/lib/calculateBaselineDiff.ts
new file mode 100644
index 0000000000..b564d8c41e
--- /dev/null
+++ b/web/src/features/datasets/lib/calculateBaselineDiff.ts
@@ -0,0 +1,79 @@
+import { type AggregatedScoreData } from "@langfuse/shared";
+import type Decimal from "decimal.js";
+
+export type NumericDiff = {
+ type: "NUMERIC";
+ absoluteDifference: number;
+ direction: "+" | "-";
+};
+
+export type CategoricalDiff = {
+ type: "CATEGORICAL";
+ isDifferent: true;
+};
+
+export type BaselineDiff = NumericDiff | CategoricalDiff | null;
+
+/**
+ * Calculate numeric diff between current and baseline values
+ * Handles number, Decimal, null, undefined
+ * Returns null if diff cannot be calculated or values are equal
+ */
+export function calculateNumericDiff(
+ current: number | Decimal | null | undefined,
+ baseline: number | Decimal | null | undefined,
+): BaselineDiff | null {
+ if (current == null || baseline == null) return null;
+
+ // Convert to numbers
+ const currentNum = typeof current === "number" ? current : current.toNumber();
+ const baselineNum =
+ typeof baseline === "number" ? baseline : baseline.toNumber();
+
+ // Same value → no diff
+ const diff = currentNum - baselineNum;
+ if (diff === 0) return null;
+
+ return {
+ absoluteDifference: Math.abs(diff),
+ direction: diff > 0 ? "+" : "-",
+ type: "NUMERIC",
+ };
+}
+
+/**
+ * Calculate diff between current and baseline score aggregate
+ * Returns null if diff cannot be calculated
+ */
+export function calculateScoreDiff(
+ current: AggregatedScoreData | null,
+ baseline: AggregatedScoreData | null,
+): BaselineDiff {
+ // Missing data → no diff
+ if (!current || !baseline) return null;
+
+ // Aggregate scores (no id) → skip
+ if (!current.id || !baseline.id) return null;
+
+ // Type mismatch → no diff
+ if (current.type !== baseline.type) return null;
+
+ if (current.type === "NUMERIC" && baseline.type === "NUMERIC") {
+ return calculateNumericDiff(current.average, baseline.average);
+ }
+
+ if (current.type === "CATEGORICAL" && baseline.type === "CATEGORICAL") {
+ const currentValue = current.values[0];
+ const baselineValue = baseline.values[0];
+
+ // Same value → no diff
+ if (currentValue === baselineValue) return null;
+
+ return {
+ type: "CATEGORICAL",
+ isDifferent: true,
+ };
+ }
+
+ return null;
+}
diff --git a/web/src/features/datasets/lib/calculateScoreDiff.ts b/web/src/features/datasets/lib/calculateScoreDiff.ts
index e737c32405..d11da5fa2d 100644
--- a/web/src/features/datasets/lib/calculateScoreDiff.ts
+++ b/web/src/features/datasets/lib/calculateScoreDiff.ts
@@ -1,18 +1,6 @@
+import { type BaselineDiff } from "@/src/features/datasets/lib/calculateBaselineDiff";
import { type AggregatedScoreData } from "@langfuse/shared";
-export type NumericDiff = {
- type: "NUMERIC";
- absoluteDifference: number;
- direction: "+" | "-";
-};
-
-export type CategoricalDiff = {
- type: "CATEGORICAL";
- isDifferent: true;
-};
-
-export type ScoreDiff = NumericDiff | CategoricalDiff | null;
-
/**
* Calculate diff between current and baseline score aggregate
* Returns null if diff cannot be calculated
@@ -20,7 +8,7 @@ export type ScoreDiff = NumericDiff | CategoricalDiff | null;
export function calculateScoreDiff(
current: AggregatedScoreData | null,
baseline: AggregatedScoreData | null,
-): ScoreDiff {
+): BaselineDiff {
// Missing data → no diff
if (!current || !baseline) return null;
diff --git a/web/src/features/datasets/lib/computeScoreDiffs.ts b/web/src/features/datasets/lib/computeScoreDiffs.ts
index 008d91e839..7cc8b87a1b 100644
--- a/web/src/features/datasets/lib/computeScoreDiffs.ts
+++ b/web/src/features/datasets/lib/computeScoreDiffs.ts
@@ -1,5 +1,5 @@
import { type ScoreAggregate } from "@langfuse/shared";
-import { calculateScoreDiff, type ScoreDiff } from "./calculateScoreDiff";
+import { type BaselineDiff, calculateScoreDiff } from "./calculateBaselineDiff";
/**
* Compute diffs for all scores between current and baseline aggregates
@@ -8,10 +8,10 @@ import { calculateScoreDiff, type ScoreDiff } from "./calculateScoreDiff";
export function computeScoreDiffs(
currentScores: ScoreAggregate,
baselineScores: ScoreAggregate | null,
-): Record<string, ScoreDiff> {
+): Record<string, BaselineDiff> {
if (!baselineScores) return {};
- const diffs: Record<string, ScoreDiff> = {};
+ const diffs: Record<string, BaselineDiff> = {};
for (const [key, currentAgg] of Object.entries(currentScores)) {
const baselineAgg = baselineScores[key];
diff --git a/web/src/features/scores/components/ScoreRow.tsx b/web/src/features/scores/components/ScoreRow.tsx
index c47dd337a9..7dfcf67f15 100644
--- a/web/src/features/scores/components/ScoreRow.tsx
+++ b/web/src/features/scores/components/ScoreRow.tsx
@@ -1,5 +1,4 @@
import * as React from "react";
-import { cn } from "@/src/utils/tailwind";
import {
type ScoreSourceType,
type AggregatedScoreData,
@@ -18,7 +17,8 @@ import {
import { api } from "@/src/utils/api";
import { JSONView } from "@/src/components/ui/CodeJsonViewer";
import { Skeleton } from "@/src/components/ui/skeleton";
-import { type ScoreDiff } from "@/src/features/datasets/lib/calculateScoreDiff";
+import { type BaselineDiff } from "@/src/features/datasets/lib/calculateBaselineDiff";
+import { DiffLabel } from "@/src/features/datasets/components/DiffLabel";
const resolveScoreValue = (aggregate: AggregatedScoreData): string => {
if (aggregate.type === "NUMERIC") {
@@ -51,7 +51,7 @@ const ScoreValueSection = ({
diff,
}: {
aggregate: AggregatedScoreData | null;
- diff?: ScoreDiff | null;
+ diff?: BaselineDiff;
}) => {
return (
<div className="flex flex-shrink-0 items-center gap-1">
@@ -60,23 +60,8 @@ const ScoreValueSection = ({
<span className="line-clamp-1 font-medium">
{resolveScoreValue(aggregate)}
</span>
- {diff && diff.type === "NUMERIC" && (
- <span
- className={cn(
- "rounded px-1.5 py-0.5 text-xs font-semibold",
- diff.direction === "+"
- ? "bg-light-green text-dark-green"
- : "bg-light-red text-dark-red",
- )}
- >
- {diff.direction}
- {diff.absoluteDifference.toFixed(2)}
- </span>
- )}
- {diff && diff.type === "CATEGORICAL" && diff.isDifferent && (
- <span className="rounded bg-light-yellow px-1.5 py-0.5 text-xs font-semibold text-dark-yellow">
- Varies
- </span>
+ {diff && (
+ <DiffLabel diff={diff} formatValue={(value) => value.toFixed(2)} />
)}
</>
) : (
@@ -102,7 +87,7 @@ export const ScoreRow = ({
name: string;
source: ScoreSourceType;
aggregate: AggregatedScoreData | null;
- diff?: ScoreDiff | null;
+ diff?: BaselineDiff;
}) => {
const [isHovered, setIsHovered] = React.useState(false);
@@ -125,8 +110,10 @@ export const ScoreRow = ({
if (!aggregate) {
return (
- <div className="flex w-full items-center gap-2">
- <span className="w-32 truncate text-muted-foreground">{name}</span>
+ <div className="flex h-6 w-full items-center gap-2">
+ <span className="w-32 flex-shrink-0 truncate text-muted-foreground">
+ {name}
+ </span>
<ScoreValueSection aggregate={aggregate} diff={diff} />
</div>
);
@@ -134,8 +121,8 @@ export const ScoreRow = ({
return (
<HoverCard openDelay={700} closeDelay={100} onOpenChange={setIsHovered}>
- <div className="flex w-full items-center gap-2">
- <span className="w-32 truncate font-medium">{name}</span>
+ <div className="flex h-6 w-full items-center gap-2">
+ <span className="w-32 flex-shrink-0 truncate font-medium">{name}</span>
<HoverCardTrigger asChild>
<div className="cursor-pointer">
<ScoreValueSection aggregate={aggregate} diff={diff} />