Skip to content

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

fix(dashboards): Use correct units for charts (#13338)

Ben Bachemda0e33909564
diff --git a/web/src/__tests__/widget-metric-presentation.clienttest.ts b/web/src/__tests__/widget-metric-presentation.clienttest.ts
new file mode 100644
index 0000000000..676e6f7f7a
--- /dev/null
+++ b/web/src/__tests__/widget-metric-presentation.clienttest.ts
@@ -0,0 +1,80 @@
+import { getWidgetMetricPresentation } from "@/src/features/widgets/utils";
+
+describe("getWidgetMetricPresentation", () => {
+ it.each([
+ {
+ name: "cost widgets",
+ metric: { measure: "totalCost", agg: "sum" },
+ view: "observations",
+ label: "USD",
+ sampleValue: 1.234567,
+ formatted: { prefix: "$" },
+ },
+ {
+ name: "millisecond widgets",
+ metric: { measure: "latency", agg: "p95" },
+ view: "traces",
+ label: "Duration",
+ sampleValue: 1500,
+ formatted: { suffix: "s" },
+ },
+ ] as const)(
+ "returns $label labeling and unit formatting for $name",
+ ({ metric, view, label, sampleValue, formatted }) => {
+ const presentation = getWidgetMetricPresentation({
+ metric,
+ view,
+ version: "v1",
+ });
+
+ expect(presentation.label).toBe(label);
+ expect(presentation.metricFormatter).toBeDefined();
+ expect(
+ presentation.metricFormatter?.(sampleValue, {
+ style: "compact",
+ }),
+ ).toMatchObject(formatted);
+ },
+ );
+
+ it("returns unit labels without custom formatting for non-special units", () => {
+ const presentation = getWidgetMetricPresentation({
+ metric: { measure: "totalTokens", agg: "sum" },
+ view: "observations",
+ version: "v1",
+ });
+
+ expect(presentation.label).toBe("Tokens");
+ expect(presentation.metricFormatter).toBeUndefined();
+ });
+
+ it.each([
+ {
+ metric: { measure: "latency", agg: "count" },
+ view: "traces",
+ label: "Count Latency",
+ },
+ {
+ metric: { measure: "totalCost", agg: "uniq" },
+ view: "observations",
+ label: "Uniq Total Cost",
+ },
+ {
+ metric: { measure: "count", agg: "count" },
+ view: "traces",
+ label: "Count",
+ },
+ ] as const)(
+ "falls back to the default presentation for $metric.agg aggregations",
+ ({ metric, view, label }) => {
+ const presentation = getWidgetMetricPresentation({
+ metric,
+ view,
+ version: "v1",
+ });
+
+ expect(presentation.label).toBe(label);
+ expect(presentation.metricFormatter).toBeUndefined();
+ },
+ );
+});
diff --git a/web/src/features/dashboard/components/LatencyChart.tsx b/web/src/features/dashboard/components/LatencyChart.tsx
index 9fee86d900..119aee3449 100644
--- a/web/src/features/dashboard/components/LatencyChart.tsx
+++ b/web/src/features/dashboard/components/LatencyChart.tsx
@@ -6,7 +6,6 @@ import {
} from "@/src/features/dashboard/components/hooks";
import { DashboardCard } from "@/src/features/dashboard/components/cards/DashboardCard";
import { TabComponent } from "@/src/features/dashboard/components/TabsComponent";
-import { latencyFormatter } from "@/src/utils/numbers";
import {
type DashboardDateRangeAggregationOption,
dashboardDateRangeAggregationSettings,
@@ -193,12 +192,17 @@ export const GenerationLatencyChart = ({
<Chart
chartType="LINE_TIME_SERIES"
data={timeSeriesToDataPoints(item.data, agg)}
+ config={{
+ metric: {
+ label: "Latency",
+ },
+ }}
rowLimit={100}
chartConfig={{
type: "LINE_TIME_SERIES",
+ unit: "millisecond",
show_data_point_dots: false,
}}
- valueFormatter={latencyFormatter}
legendPosition="above"
/>
</div>
diff --git a/web/src/features/dashboard/components/ModelCostTable.tsx b/web/src/features/dashboard/components/ModelCostTable.tsx
index 0b3bf7bf28..fb34f2d2aa 100644
--- a/web/src/features/dashboard/components/ModelCostTable.tsx
+++ b/web/src/features/dashboard/components/ModelCostTable.tsx
@@ -6,7 +6,7 @@ import { DashboardTable } from "@/src/features/dashboard/components/cards/Dashbo
import { type FilterState, getGenerationLikeTypes } from "@langfuse/shared";
import { compactNumberFormatter } from "@/src/utils/numbers";
import { TotalMetric } from "./TotalMetric";
-import { totalCostDashboardFormatted } from "@/src/features/dashboard/lib/dashboard-utils";
+import { costFormatter } from "@/src/utils/numbers";
import { truncate } from "@/src/utils/string";
import {
type QueryType,
@@ -97,7 +97,7 @@ export const ModelCostTable = ({
</RightAlignedCell>,
<RightAlignedCell key={`${i}-cost`}>
{item.sum_totalCost
- ? totalCostDashboardFormatted(item.sum_totalCost as number)
+ ? costFormatter(item.sum_totalCost as number)
: "$0"}
</RightAlignedCell>,
])
@@ -120,7 +120,7 @@ export const ModelCostTable = ({
collapse={{ collapsed: 5, expanded: 20 }}
>
<TotalMetric
- metric={totalCostDashboardFormatted(totalTokenCost)}
+ metric={costFormatter(totalTokenCost)}
description="Total cost"
>
<DocPopup
diff --git a/web/src/features/dashboard/components/ModelUsageChart.tsx b/web/src/features/dashboard/components/ModelUsageChart.tsx
index 94e35aa845..bef5bb6d0e 100644
--- a/web/src/features/dashboard/components/ModelUsageChart.tsx
+++ b/web/src/features/dashboard/components/ModelUsageChart.tsx
@@ -7,7 +7,7 @@ import {
} from "@/src/features/dashboard/components/hooks";
import { TabComponent } from "@/src/features/dashboard/components/TabsComponent";
import { TotalMetric } from "@/src/features/dashboard/components/TotalMetric";
-import { totalCostDashboardFormatted } from "@/src/features/dashboard/lib/dashboard-utils";
+import { costFormatter } from "@/src/utils/numbers";
import { api } from "@/src/utils/api";
import {
type DashboardDateRangeAggregationOption,
@@ -302,16 +302,18 @@ export const ModelUsageChart = ({
{
tabTitle: "Cost by model",
data: costByModel,
- totalMetric: totalCostDashboardFormatted(totalCost),
+ totalMetric: costFormatter(totalCost),
metricDescription: `Cost`,
- formatter: totalCostDashboardFormatted,
+ chartMetricLabel: "USD",
+ chartUnit: "USD",
},
{
tabTitle: "Cost by type",
data: costByType,
- totalMetric: totalCostDashboardFormatted(totalCost),
+ totalMetric: costFormatter(totalCost),
metricDescription: `Cost`,
- formatter: totalCostDashboardFormatted,
+ chartMetricLabel: "USD",
+ chartUnit: "USD",
},
{
tabTitle: "Usage by model",
@@ -320,6 +322,8 @@ export const ModelUsageChart = ({
? compactNumberFormatter(totalTokens)
: compactNumberFormatter(0),
metricDescription: `Units`,
+ chartMetricLabel: "Tokens",
+ chartUnit: "tokens",
},
{
tabTitle: "Usage by type",
@@ -328,6 +332,8 @@ export const ModelUsageChart = ({
? compactNumberFormatter(totalTokens)
: compactNumberFormatter(0),
metricDescription: `Units`,
+ chartMetricLabel: "Tokens",
+ chartUnit: "tokens",
},
];
@@ -373,12 +379,17 @@ export const ModelUsageChart = ({
<Chart
chartType="LINE_TIME_SERIES"
data={timeSeriesToDataPoints(item.data, agg)}
+ config={{
+ metric: {
+ label: item.chartMetricLabel,
+ },
+ }}
rowLimit={100}
chartConfig={{
type: "LINE_TIME_SERIES",
+ unit: item.chartUnit,
show_data_point_dots: false,
}}
- valueFormatter={item.formatter}
legendPosition="above"
/>
</div>
diff --git a/web/src/features/dashboard/components/TracesBarListChart.tsx b/web/src/features/dashboard/components/TracesBarListChart.tsx
index f97098ee28..951dd4e8fc 100644
--- a/web/src/features/dashboard/components/TracesBarListChart.tsx
+++ b/web/src/features/dashboard/components/TracesBarListChart.tsx
@@ -3,10 +3,11 @@ import { ExpandListButton } from "@/src/features/dashboard/components/cards/Chev
import { useState } from "react";
import { DashboardCard } from "@/src/features/dashboard/components/cards/DashboardCard";
import { TotalMetric } from "@/src/features/dashboard/components/TotalMetric";
-import { compactNumberFormatter, numberFormatter } from "@/src/utils/numbers";
+import { compactNumberFormatter } from "@/src/utils/numbers";
import { NoDataOrLoading } from "@/src/components/NoDataOrLoading";
import { type QueryType, type ViewVersion } from "@/src/features/query";
import { Chart } from "@/src/features/widgets/chart-library/Chart";
+import { formatMetric } from "@/src/features/widgets/chart-library/utils";
import { barListToDataPoints } from "@/src/features/dashboard/lib/chart-data-adapters";
import { traceViewQuery } from "@/src/features/dashboard/lib/dashboard-utils";
import { useScheduledDashboardExecuteQuery } from "@/src/hooks/useDashboardQueryScheduler";
@@ -146,14 +147,22 @@ export const TracesBarListChart = ({
<Chart
chartType="HORIZONTAL_BAR"
data={barListToDataPoints(adjustedData)}
+ metricFormatter={(value) =>
+ formatMetric(value, { style: "full" })
+ }
+ config={{
+ metric: {
+ label: "Traces",
+ },
+ }}
rowLimit={maxNumberOfEntries.expanded}
chartConfig={{
type: "HORIZONTAL_BAR",
row_limit: maxNumberOfEntries.expanded,
+ unit: "traces",
subtle_fill: true,
show_value_labels: true,
}}
- valueFormatter={(n) => numberFormatter(n, 0)}
/>
</div>
) : (
diff --git a/web/src/features/dashboard/components/TracesTimeSeriesChart.tsx b/web/src/features/dashboard/components/TracesTimeSeriesChart.tsx
index e01ba92f53..b3c5bcf5b4 100644
--- a/web/src/features/dashboard/components/TracesTimeSeriesChart.tsx
+++ b/web/src/features/dashboard/components/TracesTimeSeriesChart.tsx
@@ -160,6 +160,7 @@ export const TracesAndObservationsTimeSeriesChart = ({
data: transformedObservations,
totalMetric: totalObservations,
metricDescription: `Observations tracked`,
+ chartMetricLabel: "Observations",
},
]
: [
@@ -168,12 +169,14 @@ export const TracesAndObservationsTimeSeriesChart = ({
data: transformedTraces,
totalMetric: total,
metricDescription: `Traces tracked`,
+ chartMetricLabel: "Traces",
},
{
tabTitle: "Observations by Level",
data: transformedObservations,
totalMetric: totalObservations,
metricDescription: `Observations tracked`,
+ chartMetricLabel: "Observations",
},
];
@@ -205,6 +208,11 @@ export const TracesAndObservationsTimeSeriesChart = ({
<Chart
chartType="LINE_TIME_SERIES"
data={timeSeriesToDataPoints(item.data, agg)}
+ config={{
+ metric: {
+ label: item.chartMetricLabel,
+ },
+ }}
rowLimit={100}
chartConfig={{
type: "LINE_TIME_SERIES",
diff --git a/web/src/features/dashboard/components/UserChart.tsx b/web/src/features/dashboard/components/UserChart.tsx
index c6d9f68d2e..5810ee4395 100644
--- a/web/src/features/dashboard/components/UserChart.tsx
+++ b/web/src/features/dashboard/components/UserChart.tsx
@@ -5,7 +5,7 @@ import { TabComponent } from "@/src/features/dashboard/components/TabsComponent"
import { TotalMetric } from "@/src/features/dashboard/components/TotalMetric";
import { ExpandListButton } from "@/src/features/dashboard/components/cards/ChevronButton";
import { useState } from "react";
-import { totalCostDashboardFormatted } from "@/src/features/dashboard/lib/dashboard-utils";
+import { costFormatter } from "@/src/utils/numbers";
import { NoDataOrLoading } from "@/src/components/NoDataOrLoading";
import {
type QueryType,
@@ -165,18 +165,16 @@ export const UserChart = ({
const BAR_ROW_HEIGHT = 36;
const CHART_AXIS_PADDING = 32;
- const localUsdFormatter = (value: number) =>
- totalCostDashboardFormatted(value);
-
const data = [
{
tabTitle: "Token cost",
data: isExpanded
? transformedCost.slice(0, maxNumberOfEntries.expanded)
: transformedCost.slice(0, maxNumberOfEntries.collapsed),
- totalMetric: totalCostDashboardFormatted(totalCost),
+ totalMetric: costFormatter(totalCost),
metricDescription: "Total cost",
- formatter: localUsdFormatter,
+ chartMetricLabel: "USD",
+ chartUnit: "USD",
},
{
tabTitle: "Count of Traces",
@@ -187,8 +185,10 @@ export const UserChart = ({
? compactNumberFormatter(totalTraces)
: compactNumberFormatter(0),
metricDescription: "Total traces",
+ chartMetricLabel: "Traces",
+ chartUnit: "traces",
},
- ];
+ ] as const;
return (
<DashboardCard
@@ -222,14 +222,19 @@ export const UserChart = ({
<Chart
chartType="HORIZONTAL_BAR"
data={barListToDataPoints(item.data)}
+ config={{
+ metric: {
+ label: item.chartMetricLabel,
+ },
+ }}
rowLimit={maxNumberOfEntries.expanded}
chartConfig={{
type: "HORIZONTAL_BAR",
row_limit: maxNumberOfEntries.expanded,
+ unit: item.chartUnit,
show_value_labels: true,
subtle_fill: true,
}}
- valueFormatter={item.formatter}
/>
</div>
</div>
diff --git a/web/src/features/dashboard/lib/chart-data-adapters.ts b/web/src/features/dashboard/lib/chart-data-adapters.ts
index 856730e065..27ce047b6c 100644
--- a/web/src/features/dashboard/lib/chart-data-adapters.ts
+++ b/web/src/features/dashboard/lib/chart-data-adapters.ts
@@ -142,29 +142,51 @@ export function scoreChartDataToDataPoints(
});
}
+const compareViewMetricUnits = {
+ cost: "USD",
+ latency: "millisecond",
+} as const;
+
+export function getCompareViewChartUnit(metricKey: string): string | undefined {
+ return compareViewMetricUnits[
+ metricKey as keyof typeof compareViewMetricUnits
+ ];
+}
+
+const normalizeCompareViewMetric = (metricKey: string, metric: number) =>
+ // TODO: remove when revamping the datasets api for it to directly return ms.
+ metricKey === "latency" ? metric * 1000 : metric;
+
/**
* Converts dataset run compare-view chartData (ChartBin[] from CompareViewAdapter) to DataPoint[].
- * - Single series (chartLabels.length === 1): one row per run → HORIZONTAL_BAR / VERTICAL_BAR.
- * - Multi series (categorical): one row per (run, category) → BAR_TIME_SERIES.
+ * - Single series: one row per run as a time-series point.
+ * - Multi series: one row per (run, category) as a bar time-series point.
*/
export function compareViewChartDataToDataPoints(
chartData: ChartBin[],
chartLabels: string[],
+ metricKey: string,
): DataPoint[] {
if (chartLabels.length === 0) return [];
if (chartLabels.length === 1) {
const label = chartLabels[0]!;
return chartData.map((bin) => ({
- dimension: bin.binLabel,
- metric: (bin as Record<string, number>)[label] ?? 0,
- time_dimension: undefined,
+ time_dimension: bin.binLabel,
+ dimension: label,
+ metric: normalizeCompareViewMetric(
+ metricKey,
+ (bin as Record<string, number>)[label] ?? 0,
+ ),
}));
}
return chartData.flatMap((bin) =>
chartLabels.map((label) => ({
time_dimension: bin.binLabel,
dimension: label,
- metric: (bin as Record<string, number>)[label] ?? 0,
+ metric: normalizeCompareViewMetric(
+ metricKey,
+ (bin as Record<string, number>)[label] ?? 0,
+ ),
})),
);
}
diff --git a/web/src/features/dashboard/lib/dashboard-utils.ts b/web/src/features/dashboard/lib/dashboard-utils.ts
index 98ad37a89e..4326b2a133 100644
--- a/web/src/features/dashboard/lib/dashboard-utils.ts
+++ b/web/src/features/dashboard/lib/dashboard-utils.ts
@@ -1,6 +1,5 @@
import { type z } from "zod";
import { type FilterState, type singleFilter } from "@langfuse/shared";
-import { usdFormatter } from "@/src/utils/numbers";
import {
type QueryType,
type ViewVersion,
@@ -24,14 +23,6 @@ export const createTracesTimeFilter = (
});
};
-export const totalCostDashboardFormatted = (totalCost?: number) => {
- return totalCost
- ? totalCost < 5
- ? usdFormatter(totalCost, 2, 6)
- : usdFormatter(totalCost, 2, 2)
- : usdFormatter(0);
-};
-
/** Filter to exclude events with empty trace_name (observations view only). */
export const TRACE_NAME_NOT_NULL_FILTER: z.infer<typeof singleFilter> = {
type: "null",
diff --git a/web/src/features/dashboard/lib/score-analytics-utils.ts b/web/src/features/dashboard/lib/score-analytics-utils.ts
index 2740f3088b..0a71cb891c 100644
--- a/web/src/features/dashboard/lib/score-analytics-utils.ts
+++ b/web/src/features/dashboard/lib/score-analytics-utils.ts
@@ -12,7 +12,7 @@ export const RESOURCE_METRICS = [
key: "latency",
value: "Latency",
objectKey: "avgLatency",
- label: "Latency (s)",
+ label: "Latency",
maxFractionDigits: 2,
},
{
diff --git a/web/src/features/datasets/components/DatasetRunsTable.tsx b/web/src/features/datasets/components/DatasetRunsTable.tsx
index 25fa6bbe44..5dedd66c01 100644
--- a/web/src/features/datasets/components/DatasetRunsTable.tsx
+++ b/web/src/features/datasets/components/DatasetRunsTable.tsx
@@ -7,7 +7,7 @@ import { formatIntervalSeconds } from "@/src/utils/dates";
import { useQueryParams, withDefault, NumberParam } from "use-query-params";
import { type RouterOutput } from "@/src/utils/types";
import { useEffect, useMemo, useState } from "react";
-import { compactNumberFormatter, usdFormatter } from "@/src/utils/numbers";
+import { usdFormatter } from "@/src/utils/numbers";
import { DataTableToolbar } from "@/src/components/table/data-table-toolbar";
import useColumnVisibility from "@/src/features/column-visibility/hooks/useColumnVisibility";
import { type Prisma, datasetRunsTableColsWithOptions } from "@langfuse/shared";
@@ -36,7 +36,10 @@ import {
RESOURCE_METRICS,
transformAggregatedRunMetricsToChartData,
} from "@/src/features/dashboard/lib/score-analytics-utils";
-import { compareViewChartDataToDataPoints } from "@/src/features/dashboard/lib/chart-data-adapters";
+import {
+ compareViewChartDataToDataPoints,
+ getCompareViewChartUnit,
+} from "@/src/features/dashboard/lib/chart-data-adapters";
import { Chart } from "@/src/features/widgets/chart-library/Chart";
import { CompareViewAdapter } from "@/src/features/scores/adapters";
import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
@@ -644,25 +647,12 @@ export function DatasetRunsTable(props: {
);
const { chartData, chartLabels } = adapter.toChartData();
- // TODO: remove when revamping the datasets api for it to directly return ms
- const valueFormatter =
- key === "latency"
- ? formatIntervalSeconds
- : key === "cost"
- ? usdFormatter
- : compactNumberFormatter;
+ const dataPoints = compareViewChartDataToDataPoints(
+ chartData,
+ chartLabels,
+ key,
+ );
- const dataPoints =
- chartLabels.length === 1
- ? chartData.map((d) => ({
- time_dimension: d.binLabel,
- dimension: chartLabels[0]!,
- metric: (d[chartLabels[0]!] as number) ?? 0,
- }))
- : compareViewChartDataToDataPoints(
- chartData,
- chartLabels,
- );
const chartType =
chartLabels.length === 1
? "LINE_TIME_SERIES"
@@ -699,8 +689,10 @@ export function DatasetRunsTable(props: {
chartType={chartType}
data={dataPoints}
rowLimit={Math.max(dataPoints.length, 1)}
- chartConfig={{ type: chartType }}
- valueFormatter={valueFormatter}
+ chartConfig={{
+ type: chartType,
+ unit: getCompareViewChartUnit(key),
+ }}
legendPosition={
chartLabels.length > 1 ? "above" : "none"
}
diff --git a/web/src/features/widgets/chart-library/AreaChartTimeSeries.tsx b/web/src/features/widgets/chart-library/AreaChartTimeSeries.tsx
index 06187bf37b..bad18fd805 100644
--- a/web/src/features/widgets/chart-library/AreaChartTimeSeries.tsx
+++ b/web/src/features/widgets/chart-library/AreaChartTimeSeries.tsx
@@ -8,10 +8,11 @@ import {
import { Area, AreaChart, CartesianGrid, XAxis, YAxis } from "recharts";
import { type ChartProps } from "@/src/features/widgets/chart-library/chart-props";
import {
+ formatMetric,
getUniqueDimensions,
groupDataByTimeDimension,
+ toFullMetricString,
} from "@/src/features/widgets/chart-library/utils";
-import { compactNumberFormatter } from "@/src/utils/numbers";
import { cn } from "@/src/utils/tailwind";
export const AreaChartTimeSeries: React.FC<ChartProps> = ({
@@ -25,7 +26,7 @@ export const AreaChartTimeSeries: React.FC<ChartProps> = ({
},
},
accessibilityLayer = true,
- valueFormatter,
+ metricFormatter = (value, options) => formatMetric(value, options),
legendPosition = "none",
subtleFill = false,
}) => {
@@ -36,7 +37,8 @@ export const AreaChartTimeSeries: React.FC<ChartProps> = ({
const groupedData = useMemo(() => groupDataByTimeDimension(data), [data]);
const dimensions = useMemo(() => getUniqueDimensions(data), [data]);
- const tooltipFormatter = valueFormatter ?? compactNumberFormatter;
+ const tooltipFormatter = (value: number) =>
+ toFullMetricString(metricFormatter(value, { style: "compact" }));
const handleLegendClick = (dimension: string) => {
setHighlightedDimension((prev) => (prev === dimension ? null : dimension));
diff --git a/web/src/features/widgets/chart-library/BigNumber.tsx b/web/src/features/widgets/chart-library/BigNumber.tsx
index 1d383129e7..124ffc2ebe 100644
--- a/web/src/features/widgets/chart-library/BigNumber.tsx
+++ b/web/src/features/widgets/chart-library/BigNumber.tsx
@@ -2,112 +2,53 @@ import React, { useEffect, useRef, useState, useMemo } from "react";
import { cn } from "@/src/utils/tailwind";
import { type ChartProps } from "@/src/features/widgets/chart-library/chart-props";
-// Helper function to strip trailing zeros after decimal point while preserving integer zeros
-const stripTrailingDecimalZeros = (numStr: string): string =>
- numStr.replace(/(\.\d*?)0+$/, "$1").replace(/\.$/, "");
-
-// Format large numbers with appropriate units and dynamic decimal places
-const formatBigNumber = (
- value: number,
- maxCharacters?: number,
-): { formatted: string; unit: string } => {
- const absValue = Math.abs(value);
-
- // Calculate how many decimal places we can afford based on available space
- const getOptimalDecimalPlaces = (
- baseNumber: number,
- unit: string,
- maxChars?: number,
- ): number => {
- if (!maxChars) return 1; // Default to 1 decimal place
-
- const baseStr = Math.floor(Math.abs(baseNumber)).toString();
- const signLength = value < 0 ? 1 : 0;
- const availableForDecimals =
- maxChars - baseStr.length - unit.length - signLength - 1; // -1 for decimal point
-
- return Math.max(0, Math.min(3, availableForDecimals)); // Max 3 decimal places, min 0
- };
-
- if (absValue >= 1e12) {
- const baseValue = value / 1e12;
- const decimals = getOptimalDecimalPlaces(baseValue, "T", maxCharacters);
- return {
- formatted: stripTrailingDecimalZeros(baseValue.toFixed(decimals)),
- unit: "T",
- };
- } else if (absValue >= 1e9) {
- const baseValue = value / 1e9;
- const decimals = getOptimalDecimalPlaces(baseValue, "B", maxCharacters);
- return {
- formatted: stripTrailingDecimalZeros(baseValue.toFixed(decimals)),
- unit: "B",
- };
- } else if (absValue >= 1e6) {
- const baseValue = value / 1e6;
- const decimals = getOptimalDecimalPlaces(baseValue, "M", maxCharacters);
- return {
- formatted: stripTrailingDecimalZeros(baseValue.toFixed(decimals)),
- unit: "M",
- };
- } else if (absValue >= 1e3) {
- const baseValue = value / 1e3;
- const decimals = getOptimalDecimalPlaces(baseValue, "K", maxCharacters);
- return {
- formatted: stripTrailingDecimalZeros(baseValue.toFixed(decimals)),
- unit: "K",
- };
- } else if (absValue >= 1) {
- // For numbers >= 1, show dynamic decimal places based on space
- const decimals = maxCharacters
- ? Math.min(
- 3,
- Math.max(
- 0,
- maxCharacters -
- Math.floor(absValue).toString().length -
- (value < 0 ? 1 : 0) -
- 1,
- ),
- )
- : 2;
- return {
- formatted: stripTrailingDecimalZeros(
- value.toFixed(Math.max(0, Math.min(3, decimals))),
- ),
- unit: "",
- };
- } else if (absValue > 0) {
- // For small numbers, show as many meaningful decimal places as space allows
- // Find the first significant digit and show a few more places
- const str = absValue.toString();
- const firstSignificantIndex = str.search(/[1-9]/);
-
- if (firstSignificantIndex === -1) return { formatted: "0", unit: "" };
-
- // Calculate how many decimal places we need to show meaningful digits
- const neededDecimals = firstSignificantIndex + 2; // Show 2 significant digits
- const maxAllowedDecimals = maxCharacters ? maxCharacters - 2 : 6; // Account for "0."
- const decimals = Math.min(neededDecimals, maxAllowedDecimals, 8); // Max 8 decimal places
-
- return {
- formatted: stripTrailingDecimalZeros(
- value.toFixed(Math.max(0, Math.min(3, decimals))),
- ),
- unit: "",
- };
- } else {
- return { formatted: "0", unit: "" };
- }
+// This should ideally be read based on the actual font sizes defined in Tailwind
+const baseFontSizeLookup = {
+ "text-8xl": 128,
+ "text-7xl": 96,
+ "text-6xl": 72,
+ "text-5xl": 60,
+ "text-4xl": 48,
+ "text-3xl": 36,
+ "text-2xl": 24,
+ "text-xl": 20,
+ "text-lg": 18,
+ "text-base": 16,
+ "text-sm": 14,
+} as const;
+
+type FontSizeClass = keyof typeof baseFontSizeLookup;
+
+const baseFontSizes = Object.entries(baseFontSizeLookup)
+ .sort(([, leftPx], [, rightPx]) => rightPx - leftPx)
+ .map(([fontClass, px]) => ({ class: fontClass as FontSizeClass, px }));
+
+const affixFontSizeLookup: Record<FontSizeClass, string> = {
+ "text-8xl": "text-4xl",
+ "text-7xl": "text-3xl",
+ "text-6xl": "text-2xl",
+ "text-5xl": "text-xl",
+ "text-4xl": "text-lg",
+ "text-3xl": "text-base",
+ "text-2xl": "text-sm",
+ "text-xl": "text-sm",
+ "text-lg": "text-xs",
+ "text-base": "text-xs",
+ "text-sm": "text-xs",
+};
+
+const getAffixFontSize = (size: FontSizeClass) => {
+ return affixFontSizeLookup[size];
};
export const BigNumber: React.FC<ChartProps> = ({
data,
className,
+ metricFormatter,
}: ChartProps & { className?: string }) => {
const containerRef = useRef<HTMLDivElement>(null);
const textRef = useRef<HTMLSpanElement>(null);
- const [fontSize, setFontSize] = useState("text-6xl");
+ const [fontSize, setFontSize] = useState<FontSizeClass>("text-6xl");
const [maxCharacters, setMaxCharacters] = useState<number>();
// Calculate metric value from data - show loading if no data
@@ -127,9 +68,25 @@ export const BigNumber: React.FC<ChartProps> = ({
}, 0);
}, [data, isLoading]);
- const displayValue = !isLoading
- ? formatBigNumber(calculatedMetric, maxCharacters)
- : { formatted: "0", unit: "" };
+ const displayValue = useMemo(() => {
+ if (isLoading) {
+ return { main: "0" };
+ }
+
+ return metricFormatter
+ ? metricFormatter(
+ calculatedMetric,
+ maxCharacters
+ ? {
+ style: "compact",
+ maxCharacters,
+ }
+ : { style: "compact" },
+ )
+ : {
+ main: calculatedMetric.toString(),
+ };
+ }, [calculatedMetric, isLoading, maxCharacters, metricFormatter]);
useEffect(() => {
const resizeObserver = new ResizeObserver(() => {
@@ -144,21 +101,7 @@ export const BigNumber: React.FC<ChartProps> = ({
const availableHeight = containerHeight * 0.9; // Use more height (was 0.8)
// Start with a large font size and scale down
- const baseFontSizes = [
- { class: "text-8xl", px: 128 },
- { class: "text-7xl", px: 96 },
- { class: "text-6xl", px: 72 },
- { class: "text-5xl", px: 60 },
- { class: "text-4xl", px: 48 },
- { class: "text-3xl", px: 36 },
- { class: "text-2xl", px: 24 },
- { class: "text-xl", px: 20 },
- { class: "text-lg", px: 18 },
- { class: "text-base", px: 16 },
- { class: "text-sm", px: 14 },
- ];
-
- let selectedFontSize = "text-sm";
+ let selectedFontSize: FontSizeClass = "text-sm";
let calculatedMaxChars = 0;
// Test each font size to find the largest that fits
@@ -169,11 +112,20 @@ export const BigNumber: React.FC<ChartProps> = ({
// Quick test with current display value
const testDisplayValue = !isLoading
- ? formatBigNumber(calculatedMetric, maxChars)
- : { formatted: "0", unit: "" };
-
- const textLength = (testDisplayValue.formatted + testDisplayValue.unit)
- .length;
+ ? metricFormatter
+ ? metricFormatter(calculatedMetric, {
+ style: "compact",
+ maxCharacters: maxChars,
+ })
+ : { main: "0" }
+ : { main: "0" };
+
+ const textLength = (
+ (testDisplayValue.negative ? "-" : "") +
+ (testDisplayValue.prefix ?? "") +
+ testDisplayValue.main +
+ (testDisplayValue.suffix ?? "")
+ ).length;
const estimatedWidth = textLength * charWidth;
const estimatedHeight = px * 1.1; // Less conservative line height (was 1.2)
@@ -196,7 +148,7 @@ export const BigNumber: React.FC<ChartProps> = ({
}
return () => resizeObserver.disconnect();
- }, [calculatedMetric, isLoading]);
+ }, [calculatedMetric, isLoading, metricFormatter]);
if (isLoading) {
return null;
@@ -211,37 +163,42 @@ export const BigNumber: React.FC<ChartProps> = ({
)}
>
<div className="flex items-baseline justify-center gap-1">
+ {displayValue.prefix && (
+ <span
+ className={cn(
+ "text-muted-foreground font-bold",
+ getAffixFontSize(fontSize),
+ )}
+ >
+ {displayValue.negative && (
+ <span
+ className={cn(
+ "text-foreground font-extrabold tracking-tight",
+ fontSize,
+ )}
+ >
+ -
+ </span>
+ )}
+ {displayValue.prefix}
+ </span>
+ )}
<span
ref={textRef}
className={cn("text-center font-extrabold tracking-tight", fontSize)}
title={calculatedMetric.toString()}
>
- {displayValue.formatted}
+ {displayValue.negative && !displayValue.prefix ? "-" : ""}
+ {displayValue.main}
</span>
- {displayValue.unit && (
+ {displayValue.suffix && (
<span
className={cn(
"text-muted-foreground font-bold",
- fontSize === "text-8xl"
- ? "text-4xl"
- : fontSize === "text-7xl"
- ? "text-3xl"
- : fontSize === "text-6xl"
- ? "text-2xl"
- : fontSize === "text-5xl"
- ? "text-xl"
- : fontSize === "text-4xl"
- ? "text-lg"
- : fontSize === "text-3xl"
- ? "text-base"
- : fontSize === "text-2xl"
- ? "text-sm"
- : fontSize === "text-xl"
- ? "text-sm"
- : "text-xs",
+ getAffixFontSize(fontSize),
)}
>
- {displayValue.unit}
+ {displayValue.suffix}
</span>
)}
</div>
diff --git a/web/src/features/widgets/chart-library/Chart.tsx b/web/src/features/widgets/chart-library/Chart.tsx
index 743cb83a89..12b0ba69f2 100644
--- a/web/src/features/widgets/chart-library/Chart.tsx
+++ b/web/src/features/widgets/chart-library/Chart.tsx
@@ -1,6 +1,10 @@
import React, { useState, useMemo } from "react";
-import { type DataPoint } from "@/src/features/widgets/chart-library/chart-props";
-import { valueFormatter as valueFormatterByUnit } from "@/src/features/widgets/chart-library/utils";
+import {
+ type FormatMetricOptions,
+ type MetricFormatterFunction,
+ type DataPoint,
+} from "@/src/features/widgets/chart-library/chart-props";
+import { formatMetric } from "@/src/features/widgets/chart-library/utils";
import { CardContent } from "@/src/components/ui/card";
import LineChartTimeSeries from "@/src/features/widgets/chart-library/LineChartTimeSeries";
import AreaChartTimeSeries from "@/src/features/widgets/chart-library/AreaChartTimeSeries";
@@ -15,18 +19,25 @@ import { AlertCircle } from "lucide-react";
import { BigNumber } from "@/src/features/widgets/chart-library/BigNumber";
import { PivotTable } from "@/src/features/widgets/chart-library/PivotTable";
import { type OrderByState } from "@langfuse/shared";
+import { type ChartConfig } from "@/src/components/ui/chart";
+
+const DEFAULT_METRIC_THEME = {
+ light: "hsl(var(--chart-1))",
+ dark: "hsl(var(--chart-1))",
+} as const;
export const Chart = ({
chartType,
data,
rowLimit,
chartConfig,
+ config,
sortState,
onSortChange,
isLoading = false,
legendPosition,
overrideWarning = false,
- valueFormatter: valueFormatterOverride,
+ metricFormatter: metricFormatterOverride,
}: {
chartType: DashboardWidgetChartType;
data: DataPoint[];
@@ -44,21 +55,23 @@ export const Chart = ({
show_data_point_dots?: boolean;
subtle_fill?: boolean;
};
+ config?: ChartConfig;
sortState?: OrderByState | null;
onSortChange?: (sortState: OrderByState | null) => void;
isLoading?: boolean;
legendPosition?: "above" | "none";
overrideWarning?: boolean;
- valueFormatter?: (value: number) => string;
+ metricFormatter?: MetricFormatterFunction;
}) => {
const [forceRender, setForceRender] = useState(overrideWarning);
const shouldWarn = data.length > 2000 && !forceRender;
- const valueFormatter = useMemo(
+ const metricFormatter = useMemo(
() =>
- valueFormatterOverride ??
- ((v: number) => valueFormatterByUnit(v, chartConfig?.unit, true)),
- [valueFormatterOverride, chartConfig?.unit],
+ metricFormatterOverride ??
+ ((value: number, options: FormatMetricOptions) =>
+ formatMetric(value, { ...options, unit: chartConfig?.unit })),
+ [metricFormatterOverride, chartConfig?.unit],
);
const renderedData = useMemo(() => {
@@ -94,13 +107,34 @@ export const Chart = ({
});
}, [data]);
+ const resolvedConfig = useMemo(() => {
+ if (!config) return undefined;
+
+ return Object.fromEntries(
+ Object.entries(config).map(([key, value]) => {
+ if (value.theme || value.color) {
+ return [key, value];
+ }
+
+ return [
+ key,
+ {
+ ...value,
+ theme: DEFAULT_METRIC_THEME,
+ },
+ ];
+ }),
+ ) as ChartConfig;
+ }, [config]);
+
const renderChart = () => {
switch (chartType) {
case "LINE_TIME_SERIES":
return (
<LineChartTimeSeries
data={renderedData}
- valueFormatter={valueFormatter}
+ config={resolvedConfig}
+ metricFormatter={metricFormatter}
legendPosition={legendPosition}
showDataPointDots={chartConfig?.show_data_point_dots ?? true}
/>
@@ -109,7 +143,8 @@ export const Chart = ({
return (
<AreaChartTimeSeries
data={renderedData}
- valueFormatter={valueFormatter}
+ config={resolvedConfig}
+ metricFormatter={metricFormatter}
legendPosition={legendPosition}
subtleFill={chartConfig?.subtle_fill}
/>
@@ -118,7 +153,8 @@ export const Chart = ({
return (
<VerticalBarChartTimeSeries
data={renderedData}
- valueFormatter={valueFormatter}
+ config={resolvedConfig}
+ metricFormatter={metricFormatter}
subtleFill={chartConfig?.subtle_fill}
/>
);
@@ -126,8 +162,9 @@ export const Chart = ({
return (
<HorizontalBarChart
data={renderedData.slice(0, rowLimit)}
+ config={resolvedConfig}
showValueLabels={chartConfig?.show_value_labels}
- valueFormatter={valueFormatter}
+ metricFormatter={metricFormatter}
subtleFill={chartConfig?.subtle_fill}
/>
);
@@ -135,7 +172,8 @@ export const Chart = ({
return (
<VerticalBarChart
data={renderedData.slice(0, rowLimit)}
- valueFormatter={valueFormatter}
+ config={resolvedConfig}
+ metricFormatter={metricFormatter}
subtleFill={chartConfig?.subtle_fill}
/>
);
@@ -143,7 +181,8 @@ export const Chart = ({
return (
<PieChart
data={renderedData.slice(0, rowLimit)}
- valueFormatter={valueFormatter}
+ config={resolvedConfig}
+ metricFormatter={metricFormatter}
subtleFill={chartConfig?.subtle_fill}
/>
);
@@ -151,12 +190,19 @@ export const Chart = ({
return (
<HistogramChart
data={renderedData}
- valueFormatter={valueFormatter}
+ config={resolvedConfig}
+ metricFormatter={metricFormatter}
subtleFill={chartConfig?.subtle_fill}
/>
);
case "NUMBER": {
- return <BigNumber data={renderedData} />;
+ return (
+ <BigNumber
+ data={renderedData}
+ config={resolvedConfig}
+ metricFormatter={metricFormatter}
+ />
+ );
}
case "PIVOT_TABLE": {
// Extract pivot table configuration from chartConfig
@@ -182,7 +228,7 @@ export const Chart = ({
<HorizontalBarChart
data={renderedData.slice(0, rowLimit)}
showValueLabels={chartConfig?.show_value_labels}
- valueFormatter={valueFormatter}
+ metricFormatter={metricFormatter}
/>
);
}
diff --git a/web/src/features/widgets/chart-library/HistogramChart.tsx b/web/src/features/widgets/chart-library/HistogramChart.tsx
index a67052ccd8..e0577c9267 100644
--- a/web/src/features/widgets/chart-library/HistogramChart.tsx
+++ b/web/src/features/widgets/chart-library/HistogramChart.tsx
@@ -1,12 +1,19 @@
import React from "react";
-import { type DataPoint } from "@/src/features/widgets/chart-library/chart-props";
+import {
+ type DataPoint,
+ type MetricFormatterFunction,
+} from "@/src/features/widgets/chart-library/chart-props";
+import {
+ formatMetric,
+ toFullMetricString,
+} from "@/src/features/widgets/chart-library/utils";
import { BarChart, Bar, XAxis, YAxis } from "recharts";
import {
+ type ChartConfig,
ChartContainer,
ChartTooltip,
ChartTooltipContent,
} from "@/src/components/ui/chart";
-import { compactSmallNumberFormatter } from "@/src/utils/numbers";
interface HistogramDataPoint {
binLabel: string;
@@ -18,14 +25,22 @@ interface HistogramDataPoint {
const HistogramChart = ({
data,
+ config = {
+ count: {
+ label: "Count",
+ color: "hsl(var(--chart-1))",
+ },
+ },
subtleFill = false,
- valueFormatter,
+ metricFormatter = (value, options) => formatMetric(value, options),
}: {
data: DataPoint[];
+ config?: ChartConfig;
subtleFill?: boolean;
- valueFormatter?: (value: number) => string;
+ metricFormatter?: MetricFormatterFunction;
}) => {
- const formatBinEdge = valueFormatter ?? compactSmallNumberFormatter;
+ const formatBinEdge = (value: number) =>
+ toFullMetricString(metricFormatter(value, { style: "compact" }));
const transformHistogramData = (data: DataPoint[]): HistogramDataPoint[] => {
if (!data.length) return [];
@@ -54,14 +69,6 @@ const HistogramChart = ({
const histogramData = transformHistogramData(data);
- // Chart configuration
- const config = {
- count: {
- label: "Count",
- color: "hsl(var(--chart-1))",
- },
- };
-
if (!histogramData.length) {
return (
<div className="text-muted-foreground flex h-full items-center justify-center">
@@ -110,7 +117,11 @@ const HistogramChart = ({
active={active}
payload={payload}
label={label}
- valueFormatter={(v) => compactSmallNumberFormatter(Number(v))}
+ valueFormatter={(v) =>
+ toFullMetricString(
+ formatMetric(Number(v), { style: "compact" }),
+ )
+ }
nameFormatter={(name) => (name === "count" ? "Count" : name)}
labelFormatter={(label) => `Bin: ${label}`}
/>
diff --git a/web/src/features/widgets/chart-library/HorizontalBarChart.tsx b/web/src/features/widgets/chart-library/HorizontalBarChart.tsx
index b45776965e..695cf0b3c6 100644
--- a/web/src/features/widgets/chart-library/HorizontalBarChart.tsx
+++ b/web/src/features/widgets/chart-library/HorizontalBarChart.tsx
@@ -1,4 +1,4 @@
-import React, { useMemo } from "react";
+import React, { useCallback, useMemo } from "react";
import {
ChartContainer,
ChartTooltip,
@@ -13,8 +13,11 @@ import {
YAxis,
} from "recharts";
import { type ChartProps } from "@/src/features/widgets/chart-library/chart-props";
-import { formatAxisLabel } from "@/src/features/widgets/chart-library/utils";
-import { compactNumberFormatter } from "@/src/utils/numbers";
+import {
+ formatAxisLabel,
+ formatMetric,
+ toFullMetricString,
+} from "@/src/features/widgets/chart-library/utils";
const CHAR_WIDTH_PX = 7;
const LABEL_PADDING_PX = 16;
@@ -37,23 +40,29 @@ export const HorizontalBarChart: React.FC<ChartProps> = ({
},
accessibilityLayer = true,
showValueLabels = false,
- valueFormatter = compactNumberFormatter,
+ metricFormatter = (value, options) => formatMetric(value, options),
subtleFill = false,
}) => {
+ const formatValue = useCallback(
+ (value: number) =>
+ toFullMetricString(metricFormatter(value, { style: "compact" })),
+ [metricFormatter],
+ );
+
const rightMargin = useMemo(() => {
if (!showValueLabels || !data?.length) return 8;
const maxLabelLength = Math.max(
...data.map((d) => {
const value =
typeof d.metric === "number" ? d.metric : Number(d.metric ?? 0);
- return valueFormatter(value).length;
+ return formatValue(value).length;
}),
);
return Math.min(
120,
Math.max(20, maxLabelLength * CHAR_WIDTH_PX + LABEL_PADDING_PX),
);
- }, [showValueLabels, data, valueFormatter]);
+ }, [showValueLabels, data, formatValue]);
return (
<ChartContainer
@@ -80,7 +89,7 @@ export const HorizontalBarChart: React.FC<ChartProps> = ({
tickLine={false}
axisLine={false}
niceTicks="auto"
- tickFormatter={(value) => valueFormatter(Number(value))}
+ tickFormatter={(value) => formatValue(Number(value))}
/>
<YAxis
type="category"
@@ -124,7 +133,7 @@ export const HorizontalBarChart: React.FC<ChartProps> = ({
dataKey="metric"
position="right"
formatter={(value: RenderableText) =>
- valueFormatter(Number(value ?? 0))
+ formatValue(Number(value ?? 0))
}
className="fill-muted-foreground"
style={{ fontSize: 12 }}
@@ -139,7 +148,7 @@ export const HorizontalBarChart: React.FC<ChartProps> = ({
active={active}
payload={payload}
label={label}
- valueFormatter={(v) => valueFormatter(Number(v))}
+ valueFormatter={(v) => formatValue(Number(v))}
/>
)}
/>
diff --git a/web/src/features/widgets/chart-library/LineChartTimeSeries.tsx b/web/src/features/widgets/chart-library/LineChartTimeSeries.tsx
index e2076f67b4..7c897aef32 100644
--- a/web/src/features/widgets/chart-library/LineChartTimeSeries.tsx
+++ b/web/src/features/widgets/chart-library/LineChartTimeSeries.tsx
@@ -8,10 +8,11 @@ import {
import { CartesianGrid, Line, LineChart, XAxis, YAxis } from "recharts";
import { type ChartProps } from "@/src/features/widgets/chart-library/chart-props";
import {
+ formatMetric,
getUniqueDimensions,
groupDataByTimeDimension,
+ toFullMetricString,
} from "@/src/features/widgets/chart-library/utils";
-import { compactNumberFormatter } from "@/src/utils/numbers";
import { cn } from "@/src/utils/tailwind";
/**
@@ -31,7 +32,7 @@ export const LineChartTimeSeries: React.FC<ChartProps> = ({
},
},
accessibilityLayer = true,
- valueFormatter,
+ metricFormatter = (value, options) => formatMetric(value, options),
legendPosition = "none",
showDataPointDots = true,
}) => {
@@ -42,7 +43,8 @@ export const LineChartTimeSeries: React.FC<ChartProps> = ({
const groupedData = useMemo(() => groupDataByTimeDimension(data), [data]);
const dimensions = useMemo(() => getUniqueDimensions(data), [data]);
- const tooltipFormatter = valueFormatter ?? compactNumberFormatter;
+ const tooltipFormatter = (value: number) =>
+ toFullMetricString(metricFormatter(value, { style: "compact" }));
const handleLegendClick = (dimension: string) => {
setHighlightedDimension((prev) => (prev === dimension ? null : dimension));
diff --git a/web/src/features/widgets/chart-library/PieChart.tsx b/web/src/features/widgets/chart-library/PieChart.tsx
index 62b3d33f3f..b70dfe2830 100644
--- a/web/src/features/widgets/chart-library/PieChart.tsx
+++ b/web/src/features/widgets/chart-library/PieChart.tsx
@@ -12,7 +12,10 @@ import {
type PieSectorShapeProps,
} from "recharts";
import { type ChartProps } from "@/src/features/widgets/chart-library/chart-props";
-import { compactNumberFormatter } from "@/src/utils/numbers";
+import {
+ formatMetric,
+ toFullMetricString,
+} from "@/src/features/widgets/chart-library/utils";
/**
* PieChart component
@@ -31,9 +34,12 @@ export const PieChart: React.FC<ChartProps> = ({
},
},
accessibilityLayer = true,
- valueFormatter = compactNumberFormatter,
+ metricFormatter = (value, options) => formatMetric(value, options),
subtleFill = false,
}) => {
+ const formatValue = (value: number) =>
+ toFullMetricString(metricFormatter(value, { style: "compact" }));
+
// Calculate total metric value for center label
const totalValue = useMemo(() => {
return data.reduce((acc, curr) => acc + (curr.metric as number), 0);
@@ -76,7 +82,7 @@ export const PieChart: React.FC<ChartProps> = ({
active={active}
payload={payload}
label={label}
- valueFormatter={(v) => valueFormatter(Number(v))}
+ valueFormatter={(v) => formatValue(Number(v))}
/>
)}
/>
@@ -109,7 +115,7 @@ export const PieChart: React.FC<ChartProps> = ({
y={viewBox.cy}
className="fill-foreground text-3xl font-bold"
>
- {valueFormatter(totalValue)}
+ {formatValue(totalValue)}
</tspan>
<tspan
x={viewBox.cx}
diff --git a/web/src/features/widgets/chart-library/VerticalBarChart.tsx b/web/src/features/widgets/chart-library/VerticalBarChart.tsx
index a66afb2f3c..88e020cf15 100644
--- a/web/src/features/widgets/chart-library/VerticalBarChart.tsx
+++ b/web/src/features/widgets/chart-library/VerticalBarChart.tsx
@@ -6,7 +6,10 @@ import {
} from "@/src/components/ui/chart";
import { Bar, BarChart, XAxis, YAxis } from "recharts";
import { type ChartProps } from "@/src/features/widgets/chart-library/chart-props";
-import { compactNumberFormatter } from "@/src/utils/numbers";
+import {
+ formatMetric,
+ toFullMetricString,
+} from "@/src/features/widgets/chart-library/utils";
/**
* VerticalBarChart component
@@ -25,9 +28,12 @@ export const VerticalBarChart: React.FC<ChartProps> = ({
},
},
accessibilityLayer = true,
- valueFormatter = compactNumberFormatter,
+ metricFormatter = (value, options) => formatMetric(value, options),
subtleFill = false,
}) => {
+ const formatValue = (value: number) =>
+ toFullMetricString(metricFormatter(value, { style: "compact" }));
+
return (
<ChartContainer
config={config}
@@ -49,7 +55,7 @@ export const VerticalBarChart: React.FC<ChartProps> = ({
fontSize={12}
tickLine={false}
axisLine={false}
- tickFormatter={(value) => valueFormatter(Number(value))}
+ tickFormatter={(value) => formatValue(Number(value))}
/>
<Bar
dataKey="metric"
@@ -65,7 +71,7 @@ export const VerticalBarChart: React.FC<ChartProps> = ({
active={active}
payload={payload}
label={label}
- valueFormatter={(v) => valueFormatter(Number(v))}
+ valueFormatter={(v) => formatValue(Number(v))}
/>
)}
/>
diff --git a/web/src/features/widgets/chart-library/VerticalBarChartTimeSeries.tsx b/web/src/features/widgets/chart-library/VerticalBarChartTimeSeries.tsx
index cf87d743bf..3c2fcfd687 100644
--- a/web/src/features/widgets/chart-library/VerticalBarChartTimeSeries.tsx
+++ b/web/src/features/widgets/chart-library/VerticalBarChartTimeSeries.tsx
@@ -8,10 +8,11 @@ import {
import { Bar, BarChart, XAxis, YAxis } from "recharts";
import { type ChartProps } from "@/src/features/widgets/chart-library/chart-props";
import {
+ formatMetric,
getUniqueDimensions,
groupDataByTimeDimension,
+ toFullMetricString,
} from "@/src/features/widgets/chart-library/utils";
-import { compactNumberFormatter } from "@/src/utils/numbers";
/**
* VerticalBarChartTimeSeries component
@@ -30,11 +31,13 @@ export const VerticalBarChartTimeSeries: React.FC<ChartProps> = ({
},
},
accessibilityLayer = true,
- valueFormatter = compactNumberFormatter,
+ metricFormatter = (value, options) => formatMetric(value, options),
subtleFill = false,
}) => {
const groupedData = useMemo(() => groupDataByTimeDimension(data), [data]);
const dimensions = useMemo(() => getUniqueDimensions(data), [data]);
+ const formatValue = (value: number) =>
+ toFullMetricString(metricFormatter(value, { style: "compact" }));
return (
<ChartContainer
@@ -58,7 +61,7 @@ export const VerticalBarChartTimeSeries: React.FC<ChartProps> = ({
tickLine={false}
axisLine={false}
niceTicks="auto"
- tickFormatter={(value) => valueFormatter(Number(value))}
+ tickFormatter={(value) => formatValue(Number(value))}
/>
{dimensions.map((dimension, index) => (
<Bar
@@ -79,7 +82,7 @@ export const VerticalBarChartTimeSeries: React.FC<ChartProps> = ({
active={active}
payload={payload}
label={label}
- valueFormatter={valueFormatter}
+ valueFormatter={formatValue}
sortPayloadByValue="desc"
/>
)}
diff --git a/web/src/features/widgets/chart-library/chart-props.ts b/web/src/features/widgets/chart-library/chart-props.ts
index 738f2be371..a302b00851 100644
--- a/web/src/features/widgets/chart-library/chart-props.ts
+++ b/web/src/features/widgets/chart-library/chart-props.ts
@@ -8,11 +8,29 @@ export interface DataPoint {
export type LegendPosition = "above" | "none";
+export interface FormattedMetric {
+ negative?: boolean;
+ prefix?: string;
+ main: string;
+ suffix?: string;
+}
+
+export type FormatMetricOptions = {
+ unit?: string;
+ style: "full" | "compact";
+ maxCharacters?: number;
+};
+
+export type MetricFormatterFunction = (
+ value: number,
+ options: FormatMetricOptions,
+) => FormattedMetric;
+
export interface ChartProps {
data: DataPoint[];
config?: ChartConfig;
accessibilityLayer?: boolean;
- valueFormatter?: (value: number) => string;
+ metricFormatter?: MetricFormatterFunction;
legendPosition?: LegendPosition;
showValueLabels?: boolean;
showDataPointDots?: boolean;
diff --git a/web/src/features/widgets/chart-library/utils.clienttest.ts b/web/src/features/widgets/chart-library/utils.clienttest.ts
new file mode 100644
index 0000000000..8d53230166
--- /dev/null
+++ b/web/src/features/widgets/chart-library/utils.clienttest.ts
@@ -0,0 +1,195 @@
+import { formatMetric } from "@/src/features/widgets/chart-library/utils";
+
+describe("formatMetric", () => {
+ it("keeps compact numeric formatting within maxCharacters", () => {
+ expect(
+ formatMetric(12_345, { style: "compact", maxCharacters: 4 }),
+ ).toEqual({
+ main: "12",
+ suffix: "K",
+ });
+ expect(
+ formatMetric(1_234_567, { style: "compact", maxCharacters: 4 }),
+ ).toEqual({
+ main: "1.2",
+ suffix: "M",
+ });
+ expect(
+ formatMetric(-987_654_321, { style: "compact", maxCharacters: 5 }),
+ ).toEqual({
+ negative: true,
+ main: "988",
+ suffix: "M",
+ });
+ expect(
+ formatMetric(12.3456, { style: "compact", maxCharacters: 4 }),
+ ).toEqual({
+ main: "12.3",
+ });
+ });
+
+ it("normalizes compact units when constrained rounding reaches the next suffix", () => {
+ expect(
+ formatMetric(999_999, { style: "compact", maxCharacters: 4 }),
+ ).toEqual({
+ main: "1",
+ suffix: "M",
+ });
+ expect(
+ formatMetric(999_999_999, { style: "compact", maxCharacters: 4 }),
+ ).toEqual({
+ main: "1",
+ suffix: "B",
+ });
+ expect(
+ formatMetric(-999_999, { style: "compact", maxCharacters: 4 }),
+ ).toEqual({
+ negative: true,
+ main: "1",
+ suffix: "M",
+ });
+ });
+
+ it("trims USD precision to fit maxCharacters", () => {
+ expect(
+ formatMetric(1.234567, {
+ unit: "USD",
+ style: "compact",
+ maxCharacters: 4,
+ }),
+ ).toEqual({
+ prefix: "$",
+ main: "1.2",
+ });
+ expect(
+ formatMetric(-1.234567, {
+ unit: "USD",
+ style: "compact",
+ maxCharacters: 5,
+ }),
+ ).toEqual({
+ negative: true,
+ prefix: "$",
+ main: "1.2",
+ });
+ });
+
+ it("keeps negative currency sign ahead of the currency prefix", () => {
+ expect(formatMetric(-1.234567, { unit: "USD", style: "compact" })).toEqual({
+ negative: true,
+ prefix: "$",
+ main: "1.234567",
+ });
+ expect(formatMetric(-10.123456, { unit: "USD", style: "compact" })).toEqual(
+ {
+ negative: true,
+ prefix: "$",
+ main: "10.12",
+ },
+ );
+ });
+
+ it("trims duration precision to fit maxCharacters", () => {
+ expect(
+ formatMetric(1_500, {
+ unit: "millisecond",
+ style: "compact",
+ maxCharacters: 3,
+ }),
+ ).toEqual({
+ main: "2",
+ suffix: "s",
+ });
+ });
+
+ it("uses compact formatting for full-style sub-unit values above 1e-3", () => {
+ expect(formatMetric(0.01234, { style: "full" })).toEqual({
+ main: "0.012",
+ });
+ expect(formatMetric(-0.04567, { style: "full" })).toEqual({
+ negative: true,
+ main: "0.046",
+ });
+ });
+
+ it("uses exponential formatting for very small full-style values", () => {
+ expect(formatMetric(0.00012, { style: "full" })).toEqual({
+ main: "1.20e-4",
+ });
+ expect(formatMetric(-0.00012, { style: "full" })).toEqual({
+ negative: true,
+ main: "1.20e-4",
+ });
+ });
+
+ it("uses decimal formatting for compact sub-unit values above 1e-3", () => {
+ expect(formatMetric(0.01234, { style: "compact" })).toEqual({
+ main: "0.01234",
+ });
+ expect(
+ formatMetric(-0.04567, { style: "compact", maxCharacters: 7 }),
+ ).toEqual({
+ negative: true,
+ main: "0.0457",
+ });
+ expect(
+ formatMetric(0.01234, { style: "compact", maxCharacters: 5 }),
+ ).toEqual({
+ main: "0.012",
+ });
+ expect(
+ formatMetric(0.01234, { style: "compact", maxCharacters: 4 }),
+ ).toEqual({
+ main: "0.01",
+ });
+ });
+
+ it("keeps zero as plain zero in compact formatting", () => {
+ expect(formatMetric(0, { style: "compact" })).toEqual({
+ main: "0",
+ });
+ });
+
+ it("uses exponential formatting for compact very small values and shortens for maxCharacters", () => {
+ expect(formatMetric(0.00012, { style: "compact" })).toEqual({
+ main: "1.20e-4",
+ });
+ expect(
+ formatMetric(0.00012, { style: "compact", maxCharacters: 6 }),
+ ).toEqual({
+ main: "1.2e-4",
+ });
+ expect(
+ formatMetric(0.00012, { style: "compact", maxCharacters: 5 }),
+ ).toEqual({
+ main: "1e-4",
+ });
+ });
+
+ it("applies maxCharacters to full formatting too", () => {
+ expect(formatMetric(12.3456, { style: "full", maxCharacters: 4 })).toEqual({
+ main: "12.3",
+ });
+ expect(formatMetric(12.3456, { style: "full", maxCharacters: 5 })).toEqual({
+ main: "12.35",
+ });
+ expect(formatMetric(0.01234, { style: "full", maxCharacters: 5 })).toEqual({
+ main: "0.012",
+ });
+ expect(formatMetric(0.01234, { style: "full", maxCharacters: 6 })).toEqual({
+ main: "0.0123",
+ });
+ expect(formatMetric(0.01234, { style: "full", maxCharacters: 7 })).toEqual({
+ main: "0.01234",
+ });
+ expect(formatMetric(0.00012, { style: "full", maxCharacters: 5 })).toEqual({
+ main: "1e-4",
+ });
+ expect(formatMetric(0.00012, { style: "full", maxCharacters: 6 })).toEqual({
+ main: "1.2e-4",
+ });
+ expect(formatMetric(0.00012, { style: "full", maxCharacters: 7 })).toEqual({
+ main: "1.20e-4",
+ });
+ });
+});
diff --git a/web/src/features/widgets/chart-library/utils.ts b/web/src/features/widgets/chart-library/utils.ts
index b253d661a0..8b61cc667f 100644
--- a/web/src/features/widgets/chart-library/utils.ts
+++ b/web/src/features/widgets/chart-library/utils.ts
@@ -1,12 +1,13 @@
-import { type DataPoint } from "./chart-props";
-import { type DashboardWidgetChartType } from "@langfuse/shared/src/db";
import {
- compactNumberFormatter,
- compactSmallNumberFormatter,
- latencyFormatter,
- numberFormatter,
- usdFormatter,
-} from "@/src/utils/numbers";
+ type DataPoint,
+ type FormatMetricOptions,
+ type FormattedMetric,
+} from "./chart-props";
+import { type DashboardWidgetChartType } from "@langfuse/shared/src/db";
+import { compactNumberFormatter, numberFormatter } from "@/src/utils/numbers";
+
+export const toFullMetricString = (metric: FormattedMetric): string =>
+ `${metric.negative ? "-" : ""}${metric.prefix ?? ""}${metric.main}${metric.suffix ?? ""}`;
/**
* Groups data by dimension to prepare it for time series breakdowns
@@ -100,39 +101,293 @@ export function getChartTypeDisplayName(
}
}
-/**
- * Formats a metric value for display, dispatching on the result unit returned
- * by getResultUnit. String values pass through unchanged.
- *
- * - "millisecond" → latencyFormatter (auto-scales ms/s/min/h/d)
- * - "USD" → usdFormatter
- * - any other unit (or undefined):
- * - sub-unit magnitudes (|value| < 1, non-zero) → compactSmallNumberFormatter
- * regardless of `compact`, since the regular formatters round small
- * values toward "0" and lose precision
- * - else `compact` true → compactNumberFormatter (e.g. "12K") for axis
- * ticks
- * - else → numberFormatter with up to 2 fractional digits and no
- * trailing-zero padding
- *
- * `compact` is intended for axis ticks where space matters; tooltips and
- * tables should leave it off so values keep full precision.
- */
export function valueFormatter(
value: number | string,
unit?: string,
compact?: boolean,
): string {
- if (typeof value === "string") return value;
- switch (unit) {
- case "millisecond":
- return latencyFormatter(value);
- case "USD":
- return usdFormatter(value);
- default:
- if (value !== 0 && Math.abs(value) < 1)
- return compactSmallNumberFormatter(value);
- if (compact) return compactNumberFormatter(value);
- return numberFormatter(value, 0, 2);
+ if (typeof value === "string") {
+ return value;
+ }
+
+ return toFullMetricString(
+ formatMetric(value, {
+ unit,
+ style: compact ? "compact" : "full",
+ }),
+ );
+}
+
+const stripTrailingDecimalZeros = (numStr: string): string =>
+ numStr.replace(/(\.\d*?)0+$/, "$1").replace(/\.$/, "");
+
+const formatFixedMetric = (
+ value: number,
+ maxFractionDigits: number,
+ suffix = "",
+ maxCharacters?: number,
+): FormattedMetric => {
+ for (
+ let fractionDigits = maxFractionDigits;
+ fractionDigits >= 0;
+ fractionDigits--
+ ) {
+ const main = stripTrailingDecimalZeros(value.toFixed(fractionDigits));
+ const formatted = suffix ? { main, suffix } : { main };
+
+ if (
+ !maxCharacters ||
+ toFullMetricString(formatted).length <= maxCharacters
+ ) {
+ return formatted;
+ }
+ }
+
+ const main = Math.round(value).toString();
+ return suffix ? { main, suffix } : { main };
+};
+
+const formatExponentialMetric = (
+ value: number,
+ maxCharacters?: number,
+): FormattedMetric => {
+ const main = value.toExponential(2);
+ const formatted = { main };
+
+ if (!maxCharacters || toFullMetricString(formatted).length <= maxCharacters) {
+ return formatted;
}
+
+ for (let significantDigits = 2; significantDigits >= 1; significantDigits--) {
+ const shortened = value.toExponential(significantDigits - 1);
+ const shortenedFormatted = { main: shortened };
+ if (toFullMetricString(shortenedFormatted).length <= maxCharacters) {
+ return shortenedFormatted;
+ }
+ }
+
+ return formatted;
+};
+
+const compactUnits = [
+ [1e12, "T"],
+ [1e9, "B"],
+ [1e6, "M"],
+ [1e3, "K"],
+] as const;
+
+const formatCompactMetric = (
+ value: number,
+ maxCharacters?: number,
+): FormattedMetric => {
+ for (let i = 0; i < compactUnits.length; i++) {
+ const [divisor, suffix] = compactUnits[i];
+ if (value < divisor) {
+ continue;
+ }
+
+ const formatted = formatFixedMetric(
+ value / divisor,
+ 3,
+ suffix,
+ maxCharacters,
+ );
+
+ if (Number(formatted.main) >= 1000 && i > 0) {
+ const [nextDivisor, nextSuffix] = compactUnits[i - 1];
+ return formatFixedMetric(
+ value / nextDivisor,
+ 3,
+ nextSuffix,
+ maxCharacters,
+ );
+ }
+
+ return formatted;
+ }
+
+ if (value >= 1) {
+ return formatFixedMetric(value, 3, "", maxCharacters);
+ }
+
+ if (value >= 1e-3) {
+ return formatFixedMetric(value, 6, "", maxCharacters);
+ }
+
+ return formatExponentialMetric(value, maxCharacters);
+};
+
+const durationDivisors = [1, 1_000, 60_000, 3_600_000, 86_400_000] as const;
+const durationUnits = [
+ "millisecond",
+ "second",
+ "minute",
+ "hour",
+ "day",
+] as const;
+
+const formatWithConstrainedDecimals = ({
+ value,
+ maxCharacters,
+ maxFractionDigits,
+ createFormatter,
+}: {
+ value: number;
+ maxCharacters?: number;
+ maxFractionDigits: number;
+ createFormatter: (fractionDigits: number) => Intl.NumberFormat;
+}): FormattedMetric => {
+ let fallback: FormattedMetric | undefined;
+
+ for (
+ let fractionDigits = maxFractionDigits;
+ fractionDigits >= 0;
+ fractionDigits--
+ ) {
+ let prefix = "";
+ let main = "";
+ let suffix = "";
+
+ for (const part of createFormatter(fractionDigits).formatToParts(value)) {
+ switch (part.type) {
+ case "currency":
+ prefix += part.value;
+ break;
+ case "unit":
+ suffix += part.value;
+ break;
+ case "literal":
+ break;
+ default:
+ main += part.value;
+ }
+ }
+
+ const formatted: FormattedMetric = {
+ ...(prefix ? { prefix } : {}),
+ main: main || `${prefix}${suffix}`,
+ ...(suffix ? { suffix } : {}),
+ };
+
+ fallback = formatted;
+
+ if (
+ !maxCharacters ||
+ toFullMetricString(formatted).length <= maxCharacters
+ ) {
+ return formatted;
+ }
+ }
+
+ return fallback ?? { main: value.toString() };
+};
+
+/**
+ * Formats a metric into structured parts for chart labels, axes, and tooltips.
+ *
+ * - `unit === "millisecond"` auto-scales across ms/s/min/h/d and can reduce
+ * fractional precision to satisfy `maxCharacters`.
+ * - `unit === "USD"` formats with a currency prefix and can reduce fractional
+ * precision to satisfy `maxCharacters`.
+ * - `style === "compact"` uses compact suffixes for large values (`K`, `M`,
+ * `B`, `T`), decimal formatting for `1e-3 <= |value| < 1`, and exponential
+ * notation below `1e-3`.
+ * - `style === "full"` preserves more detail for non-zero sub-unit values by
+ * using compact decimal formatting for `1e-3 <= |value| < 1` and exponential
+ * notation below `1e-3`; otherwise it falls back to `numberFormatter`.
+ *
+ * `maxCharacters` is an optional space constraint that may reduce fractional
+ * digits or exponential precision for either style.
+ */
+export function formatMetric(
+ value: number,
+ options: FormatMetricOptions,
+): FormattedMetric {
+ const { unit, style, maxCharacters } = options;
+
+ const negative = value < 0;
+ const absValue = Math.abs(value);
+
+ const magnitudeMaxCharacters =
+ negative && maxCharacters ? maxCharacters - 1 : maxCharacters;
+
+ const applyNegative = (formatted: FormattedMetric): FormattedMetric =>
+ negative ? { negative: true, ...formatted } : formatted;
+
+ if (unit === "millisecond") {
+ const tier = durationDivisors.reduce(
+ (acc, divisor, i) => (absValue >= divisor ? i : acc),
+ 0,
+ );
+
+ const normalizedValue = absValue / durationDivisors[tier];
+
+ return applyNegative(
+ formatWithConstrainedDecimals({
+ value: normalizedValue,
+ maxCharacters: magnitudeMaxCharacters,
+ maxFractionDigits: 2,
+ createFormatter: (fractionDigits) =>
+ new Intl.NumberFormat("en-US", {
+ style: "unit",
+ unit: durationUnits[tier],
+ unitDisplay: "narrow",
+ notation: "compact",
+ minimumFractionDigits: 0,
+ maximumFractionDigits: fractionDigits,
+ }),
+ }),
+ );
+ }
+
+ if (unit === "USD") {
+ const maxFractionDigits = value && absValue < 5 ? 6 : 2;
+
+ return applyNegative(
+ formatWithConstrainedDecimals({
+ value: absValue,
+ maxCharacters: magnitudeMaxCharacters,
+ maxFractionDigits,
+ createFormatter: (fractionDigits) =>
+ new Intl.NumberFormat("en-US", {
+ style: "currency",
+ currency: "USD",
+ minimumFractionDigits: Math.min(2, fractionDigits),
+ maximumFractionDigits: Math.max(0, fractionDigits),
+ }),
+ }),
+ );
+ }
+
+ if (style === "compact") {
+ if (value === 0) {
+ return { main: "0" };
+ }
+
+ return applyNegative(formatCompactMetric(absValue, magnitudeMaxCharacters));
+ }
+
+ if (value !== 0 && absValue < 1e-3) {
+ return applyNegative(
+ formatExponentialMetric(absValue, magnitudeMaxCharacters),
+ );
+ }
+
+ if (value !== 0 && absValue < 1) {
+ if (maxCharacters) {
+ return applyNegative(
+ formatFixedMetric(absValue, 6, "", magnitudeMaxCharacters),
+ );
+ }
+
+ return applyNegative({ main: compactNumberFormatter(absValue, 3) });
+ }
+
+ if (maxCharacters) {
+ return applyNegative(
+ formatFixedMetric(absValue, 2, "", magnitudeMaxCharacters),
+ );
+ }
+
+ return applyNegative({ main: numberFormatter(absValue, 0, 2) });
}
diff --git a/web/src/features/widgets/components/DashboardWidget.tsx b/web/src/features/widgets/components/DashboardWidget.tsx
index d0ada57e74..550197b656 100644
--- a/web/src/features/widgets/components/DashboardWidget.tsx
+++ b/web/src/features/widgets/components/DashboardWidget.tsx
@@ -25,6 +25,7 @@ import {
formatMetricName,
shouldUseWidgetSSE,
sanitizePivotTableDefaultSort,
+ getWidgetMetricPresentation,
} from "@/src/features/widgets/utils";
import { ChartLoadingState } from "@/src/features/widgets/chart-library/ChartLoadingState";
import {
@@ -93,9 +94,11 @@ export function DashboardWidget({
// If widget requires v2 features (minVersion >= 2), must use v2.
// Otherwise follow the beta toggle.
const metricsVersion: ViewVersion =
- widgetRequiresV2 || (widget.data?.minVersion ?? 1) >= 2 || isBetaEnabled
+ widgetRequiresV2 || (widget.data?.minVersion ?? 1) >= 2
? "v2"
- : "v1";
+ : isBetaEnabled && (widget.data?.view ?? "traces") !== "traces"
+ ? "v2"
+ : "v1";
const hasCUDAccess =
useHasProjectAccess({ projectId, scope: "dashboards:CUD" }) &&
dashboardOwner !== "LANGFUSE";
@@ -297,6 +300,27 @@ export function DashboardWidget({
});
}, [queryResult.data, widget.data]);
+ const chartPresentation = useMemo(() => {
+ if (!widget.data) {
+ return undefined;
+ }
+
+ if (widget.data.chartType === "PIVOT_TABLE") {
+ return undefined;
+ }
+
+ const metric = widget.data.metrics[0];
+ if (!metric) {
+ return undefined;
+ }
+
+ return getWidgetMetricPresentation({
+ metric,
+ view: widget.data.view,
+ version: metricsVersion,
+ });
+ }, [metricsVersion, widget.data]);
+
const handleEdit = () => {
router.push(
`/project/${projectId}/widgets/${placement.widgetId}?dashboardId=${dashboardId}`,
@@ -427,6 +451,15 @@ export function DashboardWidget({
<Chart
chartType={widget.data.chartType}
data={transformedData}
+ config={
+ chartPresentation
+ ? {
+ metric: {
+ label: chartPresentation.label,
+ },
+ }
+ : undefined
+ }
rowLimit={
widget.data.chartConfig.type === "LINE_TIME_SERIES" ||
widget.data.chartConfig.type === "BAR_TIME_SERIES" ||
@@ -468,6 +501,7 @@ export function DashboardWidget({
widget.data.chartType === "PIVOT_TABLE" ? updateSort : undefined
}
isLoading={queryResult.isPending}
+ metricFormatter={chartPresentation?.metricFormatter}
/>
<ChartLoadingState
isLoading={chartLoadingState.isLoading}
diff --git a/web/src/features/widgets/components/WidgetForm.tsx b/web/src/features/widgets/components/WidgetForm.tsx
index 78382ff35c..8e84de0880 100644
--- a/web/src/features/widgets/components/WidgetForm.tsx
+++ b/web/src/features/widgets/components/WidgetForm.tsx
@@ -72,6 +72,7 @@ import {
buildWidgetName,
buildWidgetDescription,
formatMetricName,
+ getWidgetMetricPresentation,
sanitizePivotTableDefaultSort,
} from "@/src/features/widgets/utils";
import {
@@ -310,11 +311,11 @@ export function WidgetForm({
filters: initialValues.filters ?? [],
});
const viewVersion: ViewVersion =
- (isBetaEnabled && selectedView !== "traces") ||
- (initialValues.minVersion ?? 1) >= 2 ||
- initialWidgetRequiresV2
+ initialWidgetRequiresV2 || (initialValues.minVersion ?? 1) >= 2
? "v2"
- : "v1";
+ : isBetaEnabled && selectedView !== "traces"
+ ? "v2"
+ : "v1";
const availableViewOptions = viewVersion === "v2" ? viewsV2 : views;
// For regular charts: single metric selection
@@ -1070,6 +1071,24 @@ export function WidgetForm({
],
);
+ const chartPresentation = useMemo(() => {
+ if (selectedChartType === "PIVOT_TABLE") {
+ return undefined;
+ }
+
+ return getWidgetMetricPresentation({
+ metric: { measure: selectedMeasure, agg: selectedAggregation },
+ view: selectedView,
+ version: viewVersion,
+ });
+ }, [
+ selectedAggregation,
+ selectedChartType,
+ selectedMeasure,
+ selectedView,
+ viewVersion,
+ ]);
+
const handleSaveWidget = () => {
if (!queryValidation.valid) {
showErrorToast("Invalid query", queryValidation.reason);
@@ -1971,6 +1990,15 @@ export function WidgetForm({
<Chart
chartType={selectedChartType as DashboardWidgetChartType}
data={transformedData}
+ config={
+ chartPresentation
+ ? {
+ metric: {
+ label: chartPresentation.label,
+ },
+ }
+ : undefined
+ }
rowLimit={rowLimit}
chartConfig={
selectedChartType === "PIVOT_TABLE"
@@ -2024,6 +2052,7 @@ export function WidgetForm({
}
onSortChange={undefined}
isLoading={queryResult.isPending}
+ metricFormatter={chartPresentation?.metricFormatter}
/>
<ChartLoadingState
isLoading={chartLoadingState.isLoading}
diff --git a/web/src/features/widgets/utils.ts b/web/src/features/widgets/utils.ts
index c248d972b8..148265c5fc 100644
--- a/web/src/features/widgets/utils.ts
+++ b/web/src/features/widgets/utils.ts
@@ -1,6 +1,13 @@
import startCase from "lodash/startCase";
import { type FilterState } from "@langfuse/shared";
import { type DashboardWidgetChartType } from "@langfuse/shared/src/db";
+import {
+ type ViewVersion,
+ views,
+ getViewDeclaration,
+} from "@/src/features/query";
+import { formatMetric } from "@/src/features/widgets/chart-library/utils";
+import { type MetricFormatterFunction } from "@/src/features/widgets/chart-library/chart-props";
// Shared widget chart configuration types
export type WidgetChartConfig = {
@@ -194,3 +201,60 @@ export function shouldUseWidgetSSE({
}): boolean {
return isV4Enabled && version === "v2";
}
+
+const widgetUnitLabels: Record<string, string> = {
+ USD: "USD",
+ millisecond: "Duration",
+ tokens: "Tokens",
+ "tokens/s": "Tokens/s",
+ traces: "Traces",
+ observations: "Observations",
+ scores: "Scores",
+ users: "Users",
+ sessions: "Sessions",
+ tools: "Tools",
+ calls: "Calls",
+};
+
+export function getWidgetMetricPresentation(params: {
+ metric: { measure: string; agg: string };
+ view: string;
+ version: ViewVersion;
+}): {
+ label: string;
+ metricFormatter?: MetricFormatterFunction;
+} {
+ const viewDeclaration = getViewDeclaration(
+ views.parse(params.view),
+ params.version,
+ );
+
+ const measureDefinition = viewDeclaration.measures[params.metric.measure];
+
+ const usesCountStyleAggregation =
+ params.metric.agg === "count" || params.metric.agg === "uniq";
+
+ if (
+ !usesCountStyleAggregation &&
+ (measureDefinition?.unit === "USD" ||
+ measureDefinition?.unit === "millisecond")
+ ) {
+ return {
+ label: widgetUnitLabels[measureDefinition.unit],
+ metricFormatter: (value, options) =>
+ formatMetric(value, { ...options, unit: measureDefinition.unit }),
+ };
+ }
+
+ if (!usesCountStyleAggregation && measureDefinition?.unit) {
+ return {
+ label:
+ widgetUnitLabels[measureDefinition.unit] ??
+ formatMetricName(measureDefinition.unit),
+ };
+ }
+
+ return {
+ label: formatMetricName(`${params.metric.agg}_${params.metric.measure}`),
+ };
+}
diff --git a/web/src/pages/project/[projectId]/datasets/[datasetId]/compare/charts.tsx b/web/src/pages/project/[projectId]/datasets/[datasetId]/compare/charts.tsx
index beca52d7d0..481340d408 100644
--- a/web/src/pages/project/[projectId]/datasets/[datasetId]/compare/charts.tsx
+++ b/web/src/pages/project/[projectId]/datasets/[datasetId]/compare/charts.tsx
@@ -17,10 +17,11 @@ import {
RESOURCE_METRICS,
isEmptyChart,
} from "@/src/features/dashboard/lib/score-analytics-utils";
-import { compareViewChartDataToDataPoints } from "@/src/features/dashboard/lib/chart-data-adapters";
+import {
+ compareViewChartDataToDataPoints,
+ getCompareViewChartUnit,
+} from "@/src/features/dashboard/lib/chart-data-adapters";
import { Chart } from "@/src/features/widgets/chart-library/Chart";
-import { compactNumberFormatter, usdFormatter } from "@/src/utils/numbers";
-import { formatIntervalSeconds } from "@/src/utils/dates";
import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
import Page from "@/src/components/layouts/page";
import { SubHeaderLabel } from "@/src/components/layouts/header";
@@ -260,19 +261,6 @@ export default function DatasetCompare() {
: (RESOURCE_METRICS.find((metric) => metric.key === key)
?.label ?? key);
- // TODO: remove when revamping the datasets api for it to directly return ms
- const valueFormatter =
- key === "latency"
- ? formatIntervalSeconds
- : key === "cost"
- ? usdFormatter
- : (v: number) =>
- compactNumberFormatter(
- v,
- RESOURCE_METRICS.find((m) => m.key === key)
- ?.maxFractionDigits,
- );
-
if (isEmptyChart({ data: chartData })) {
return (
<div
@@ -290,17 +278,12 @@ export default function DatasetCompare() {
);
}
- const dataPoints =
- chartLabels.length === 1
- ? chartData.map((d) => ({
- time_dimension: d.binLabel,
- dimension: chartLabels[0]!,
- metric: (d[chartLabels[0]!] as number) ?? 0,
- }))
- : compareViewChartDataToDataPoints(
- chartData,
- chartLabels,
- );
+ const dataPoints = compareViewChartDataToDataPoints(
+ chartData,
+ chartLabels,
+ key,
+ );
+
const chartType =
chartLabels.length === 1
? "LINE_TIME_SERIES"
@@ -319,8 +302,10 @@ export default function DatasetCompare() {
chartType={chartType}
data={dataPoints}
rowLimit={Math.max(dataPoints.length, 1)}
- chartConfig={{ type: chartType }}
- valueFormatter={valueFormatter}
+ chartConfig={{
+ type: chartType,
+ unit: getCompareViewChartUnit(key),
+ }}
legendPosition={
chartLabels.length > 1 ? "above" : "none"
}
diff --git a/web/src/utils/numbers.ts b/web/src/utils/numbers.ts
index 357598468a..587a161e59 100644
--- a/web/src/utils/numbers.ts
+++ b/web/src/utils/numbers.ts
@@ -11,29 +11,6 @@ export const compactNumberFormatter = (
}).format(number ?? 0);
};
-/**
- * Specialized formatter for very small numbers (10^-3 to 10^-15 range)
- * Uses scientific notation for compact representation with ~3 significant digits
- */
-export const compactSmallNumberFormatter = (
- number?: number | bigint,
- significantDigits: number = 3,
-) => {
- const num = Number(number ?? 0);
-
- if (num === 0) return "0";
-
- const absNum = Math.abs(num);
-
- // For numbers >= 1e-3, use standard compact formatting
- if (absNum >= 1e-3) {
- return compactNumberFormatter(num, significantDigits);
- }
-
- // For very small numbers, use scientific notation
- return num.toExponential(significantDigits - 1);
-};
-
export const numberFormatter = (
number?: number | bigint,
fractionDigits?: number,
@@ -99,6 +76,14 @@ export const usdFormatter = (
}).format(numberToFormat ?? 0);
};
+export const costFormatter = (totalCost?: number) => {
+ return totalCost
+ ? totalCost < 5
+ ? usdFormatter(totalCost, 2, 6)
+ : usdFormatter(totalCost, 2, 2)
+ : usdFormatter(0);
+};
+
export const formatTokenCounts = (
inputUsage?: number | null,
outputUsage?: number | null,