Skip to content

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

feat(ui): improve cost and latency rendering on trace tree and preview (#3567)

Marc Klingen94d87f2a4270
diff --git a/web/src/components/token-usage-badge.tsx b/web/src/components/token-usage-badge.tsx
index ada75ab578..a1826ef4e9 100644
--- a/web/src/components/token-usage-badge.tsx
+++ b/web/src/components/token-usage-badge.tsx
@@ -3,7 +3,7 @@ import { type ObservationReturnType } from "@/src/server/api/routers/traces";
import { numberFormatter } from "@/src/utils/numbers";
import { type Observation } from "@langfuse/shared";
-export const TraceAggUsageBadge = (props: {
+export const AggUsageBadge = (props: {
observations: ObservationReturnType[];
}) => {
const usage = {
diff --git a/web/src/components/trace/ObservationPreview.tsx b/web/src/components/trace/ObservationPreview.tsx
index 282af64309..17aca302dd 100644
--- a/web/src/components/trace/ObservationPreview.tsx
+++ b/web/src/components/trace/ObservationPreview.tsx
@@ -15,7 +15,6 @@ import { IOPreview } from "@/src/components/trace/IOPreview";
import { formatIntervalSeconds } from "@/src/utils/dates";
import Link from "next/link";
import { usdFormatter } from "@/src/utils/numbers";
-import { calculateDisplayTotalCost } from "@/src/components/trace";
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";
@@ -24,6 +23,8 @@ import { JumpToPlaygroundButton } from "@/src/ee/features/playground/page/compon
import { AnnotateDrawer } from "@/src/features/scores/components/AnnotateDrawer";
import useLocalStorage from "@/src/components/useLocalStorage";
import { CommentDrawerButton } from "@/src/features/comments/CommentDrawerButton";
+import { calculateDisplayTotalCost } from "@/src/components/trace/lib/helpers";
+import { useMemo } from "react";
export const ObservationPreview = (props: {
observations: Array<ObservationReturnType>;
@@ -51,8 +52,19 @@ export const ObservationPreview = (props: {
(o) => o.id === props.currentObservationId,
);
- const totalCost = calculateDisplayTotalCost(
- preloadedObservation ? [preloadedObservation] : [],
+ const thisCost = preloadedObservation
+ ? calculateDisplayTotalCost({
+ allObservations: [preloadedObservation],
+ })
+ : undefined;
+
+ const totalCost = useMemo(
+ () =>
+ calculateDisplayTotalCost({
+ allObservations: props.observations,
+ rootObservationId: props.currentObservationId,
+ }),
+ [props.observations, props.currentObservationId],
);
if (!preloadedObservation) return <div className="flex-1">Not found</div>;
@@ -142,9 +154,14 @@ export const ObservationPreview = (props: {
{preloadedObservation.model ? (
<Badge variant="outline">{preloadedObservation.model}</Badge>
) : null}
- {totalCost ? (
+ {thisCost ? (
+ <Badge variant="outline">
+ {usdFormatter(thisCost.toNumber())}
+ </Badge>
+ ) : undefined}
+ {totalCost && totalCost !== thisCost ? (
<Badge variant="outline">
- {usdFormatter(totalCost.toNumber())}
+ ∑ {usdFormatter(totalCost.toNumber())}
</Badge>
) : undefined}
diff --git a/web/src/components/trace/ObservationTree.tsx b/web/src/components/trace/ObservationTree.tsx
index 2f7e334910..193a7f46d8 100644
--- a/web/src/components/trace/ObservationTree.tsx
+++ b/web/src/components/trace/ObservationTree.tsx
@@ -2,7 +2,7 @@ import { type NestedObservation } from "@/src/utils/types";
import { cn } from "@/src/utils/tailwind";
import { type APIScore, type Trace, type $Enums } from "@langfuse/shared";
import { GroupedScoreBadges } from "@/src/components/grouped-score-badge";
-import { Fragment } from "react";
+import { Fragment, useMemo } from "react";
import { type ObservationReturnType } from "@/src/server/api/routers/traces";
import { LevelColors } from "@/src/components/level-colors";
import { formatIntervalSeconds } from "@/src/utils/dates";
@@ -11,10 +11,13 @@ import { Toggle } from "@/src/components/ui/toggle";
import { Button } from "@/src/components/ui/button";
import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
import {
+ calculateDisplayTotalCost,
nestObservations,
treeItemColors,
} from "@/src/components/trace/lib/helpers";
import { CommentCountIcon } from "@/src/features/comments/CommentCountIcon";
+import { usdFormatter } from "@/src/utils/numbers";
+import Decimal from "decimal.js";
export const ObservationTree = (props: {
observations: ObservationReturnType[];
@@ -22,7 +25,7 @@ export const ObservationTree = (props: {
toggleCollapsedObservation: (id: string) => void;
collapseAll: () => void;
expandAll: () => void;
- trace: Trace;
+ trace: Trace & { latency?: number };
scores: APIScore[];
currentObservationId: string | undefined;
setCurrentObservationId: (id: string | undefined) => void;
@@ -32,7 +35,16 @@ export const ObservationTree = (props: {
traceCommentCounts?: Map<string, number>;
className?: string;
}) => {
- const nestedObservations = nestObservations(props.observations);
+ const nestedObservations = useMemo(
+ () => nestObservations(props.observations),
+ [props.observations],
+ );
+ const totalCost = useMemo(() => {
+ return calculateDisplayTotalCost({
+ allObservations: props.observations,
+ });
+ }, [props.observations]);
+
return (
<div className={props.className}>
<ObservationTreeTraceNode
@@ -45,6 +57,7 @@ export const ObservationTree = (props: {
setCurrentObservationId={props.setCurrentObservationId}
showMetrics={props.showMetrics}
showScores={props.showScores}
+ totalCost={totalCost}
/>
<ObservationTreeNode
observations={nestedObservations}
@@ -57,6 +70,11 @@ export const ObservationTree = (props: {
setCurrentObservationId={props.setCurrentObservationId}
showMetrics={props.showMetrics}
showScores={props.showScores}
+ colorCodeMetrics={props.observations.length >= 3}
+ parentTotalCost={totalCost}
+ parentTotalDuration={
+ props.trace.latency ? props.trace.latency * 1000 : undefined
+ }
/>
</div>
);
@@ -72,61 +90,72 @@ const ObservationTreeTraceNode = (props: {
setCurrentObservationId: (id: string | undefined) => void;
showMetrics?: boolean;
showScores?: boolean;
-}) => (
- <div
- className={cn(
- "group mb-0.5 flex cursor-pointer flex-col gap-1 rounded-sm p-1",
- props.currentObservationId === undefined ||
- props.currentObservationId === ""
- ? "bg-muted"
- : "hover:bg-primary-foreground",
- )}
- onClick={() => props.setCurrentObservationId(undefined)}
- >
- <div className="flex gap-2">
- <span className={cn("rounded-sm bg-input px-1 py-0.5 text-xs")}>
- TRACE
- </span>
- <span className="break-all text-sm">{props.trace.name}</span>
- {props.comments ? (
- <CommentCountIcon count={props.comments.get(props.trace.id)} />
- ) : null}
- <div className="flex flex-1 justify-end">
- <Button
- onClick={(ev) => (ev.stopPropagation(), props.expandAll())}
- size="xs"
- variant="ghost"
- title="Expand all"
- >
- <PlusCircleIcon className="h-4 w-4" />
- </Button>
- <Button
- onClick={(ev) => (ev.stopPropagation(), props.collapseAll())}
- size="xs"
- variant="ghost"
- title="Collapse all"
- >
- <MinusCircle className="h-4 w-4" />
- </Button>
- </div>
- </div>
-
- {props.showMetrics && props.trace.latency ? (
+ totalCost?: Decimal;
+}) => {
+ return (
+ <div
+ className={cn(
+ "group mb-0.5 flex cursor-pointer flex-col gap-1 rounded-sm p-1",
+ props.currentObservationId === undefined ||
+ props.currentObservationId === ""
+ ? "bg-muted"
+ : "hover:bg-primary-foreground",
+ )}
+ onClick={() => props.setCurrentObservationId(undefined)}
+ >
<div className="flex gap-2">
- <span className="text-xs text-muted-foreground">
- {formatIntervalSeconds(props.trace.latency)}
+ <span className={cn("rounded-sm bg-input px-1 py-0.5 text-xs")}>
+ TRACE
</span>
+ <span className="break-all text-sm">{props.trace.name}</span>
+ {props.comments ? (
+ <CommentCountIcon count={props.comments.get(props.trace.id)} />
+ ) : null}
+ <div className="flex flex-1 justify-end">
+ <Button
+ onClick={(ev) => (ev.stopPropagation(), props.expandAll())}
+ size="xs"
+ variant="ghost"
+ title="Expand all"
+ >
+ <PlusCircleIcon className="h-4 w-4" />
+ </Button>
+ <Button
+ onClick={(ev) => (ev.stopPropagation(), props.collapseAll())}
+ size="xs"
+ variant="ghost"
+ title="Collapse all"
+ >
+ <MinusCircle className="h-4 w-4" />
+ </Button>
+ </div>
</div>
- ) : null}
- {props.showScores && props.scores.find((s) => s.observationId === null) ? (
- <div className="flex flex-wrap gap-1">
- <GroupedScoreBadges
- scores={props.scores.filter((s) => s.observationId === null)}
- />
- </div>
- ) : null}
- </div>
-);
+
+ {props.showMetrics && (
+ <div className="flex gap-2">
+ {props.trace.latency ? (
+ <span className="text-xs text-muted-foreground">
+ {formatIntervalSeconds(props.trace.latency)}
+ </span>
+ ) : null}
+ {props.totalCost ? (
+ <span className="text-xs text-muted-foreground">
+ {usdFormatter(props.totalCost.toNumber())}
+ </span>
+ ) : null}
+ </div>
+ )}
+ {props.showScores &&
+ props.scores.find((s) => s.observationId === null) ? (
+ <div className="flex flex-wrap gap-1">
+ <GroupedScoreBadges
+ scores={props.scores.filter((s) => s.observationId === null)}
+ />
+ </div>
+ ) : null}
+ </div>
+ );
+};
const ObservationTreeNode = (props: {
observations: NestedObservation[];
@@ -139,6 +168,9 @@ const ObservationTreeNode = (props: {
setCurrentObservationId: (id: string | undefined) => void;
showMetrics?: boolean;
showScores?: boolean;
+ colorCodeMetrics?: boolean;
+ parentTotalCost?: Decimal;
+ parentTotalDuration?: number;
}) => {
const capture = usePostHogClientCapture();
return (
@@ -149,6 +181,13 @@ const ObservationTreeNode = (props: {
const collapsed = props.collapsedObservations.includes(
observation.id,
);
+ const unnestedObservations = unnestObservations(observation);
+ const totalCost = calculateDisplayTotalCost({
+ allObservations: unnestedObservations,
+ });
+ const duration = observation.endTime
+ ? observation.endTime.getTime() - observation.startTime.getTime()
+ : undefined;
return (
<Fragment key={observation.id}>
<div className="flex">
@@ -210,15 +249,22 @@ const ObservationTreeNode = (props: {
(observation.promptTokens ||
observation.completionTokens ||
observation.totalTokens ||
- observation.endTime) && (
+ duration ||
+ totalCost) && (
<div className="flex gap-2">
- {observation.endTime ? (
- <span className="text-xs text-muted-foreground">
- {formatIntervalSeconds(
- (observation.endTime.getTime() -
- observation.startTime.getTime()) /
- 1000,
+ {duration ? (
+ <span
+ className={cn(
+ "text-xs text-muted-foreground",
+ props.parentTotalDuration &&
+ props.colorCodeMetrics &&
+ heatMapTextColor({
+ max: props.parentTotalDuration,
+ value: duration,
+ }),
)}
+ >
+ {formatIntervalSeconds(duration / 1000)}
</span>
) : null}
{observation.promptTokens ||
@@ -230,6 +276,21 @@ const ObservationTreeNode = (props: {
{observation.totalTokens})
</span>
) : null}
+ {totalCost ? (
+ <span
+ className={cn(
+ "text-xs text-muted-foreground",
+ props.parentTotalCost &&
+ props.colorCodeMetrics &&
+ heatMapTextColor({
+ max: props.parentTotalCost,
+ value: totalCost,
+ }),
+ )}
+ >
+ {usdFormatter(totalCost.toNumber())}
+ </span>
+ ) : null}
</div>
)}
{observation.level !== "DEFAULT" ? (
@@ -271,6 +332,9 @@ const ObservationTreeNode = (props: {
setCurrentObservationId={props.setCurrentObservationId}
showMetrics={props.showMetrics}
showScores={props.showScores}
+ colorCodeMetrics={props.colorCodeMetrics}
+ parentTotalCost={props.parentTotalCost}
+ parentTotalDuration={props.parentTotalDuration}
/>
)}
</Fragment>
@@ -294,3 +358,41 @@ const ColorCodedObservationType = (props: {
</span>
);
};
+
+const unnestObservations = (nestedObservation: NestedObservation) => {
+ const unnestedObservations = [];
+ const { children, ...observation } = nestedObservation;
+ unnestedObservations.push(observation);
+ children.forEach((child) => {
+ unnestedObservations.push(...unnestObservations(child));
+ });
+ return unnestedObservations;
+};
+
+const heatMapTextColor = (p: {
+ min?: Decimal | number;
+ max: Decimal | number;
+ value: Decimal | number;
+}) => {
+ const { min, max, value } = p;
+ const minDecimal = min ? new Decimal(min) : new Decimal(0);
+ const maxDecimal = new Decimal(max);
+ const valueDecimal = new Decimal(value);
+
+ const cutOffs: [number, string][] = [
+ [0.75, "text-dark-red"], // 75%
+ [0.5, "text-dark-yellow"], // 50%
+ ];
+ const standardizedValueOnStartEndScale = valueDecimal
+ .sub(minDecimal)
+ .div(maxDecimal.sub(minDecimal));
+ const ratio = standardizedValueOnStartEndScale.toNumber();
+
+ // pick based on ratio if threshold is exceeded
+ for (const [threshold, color] of cutOffs) {
+ if (ratio >= threshold) {
+ return color;
+ }
+ }
+ return "";
+};
diff --git a/web/src/components/trace/TracePreview.tsx b/web/src/components/trace/TracePreview.tsx
index eff475c9d9..695a99a2f2 100644
--- a/web/src/components/trace/TracePreview.tsx
+++ b/web/src/components/trace/TracePreview.tsx
@@ -8,7 +8,7 @@ import {
CardHeader,
CardTitle,
} from "@/src/components/ui/card";
-import { TraceAggUsageBadge } from "@/src/components/token-usage-badge";
+import { AggUsageBadge } from "@/src/components/token-usage-badge";
import { Badge } from "@/src/components/ui/badge";
import { type ObservationReturnType } from "@/src/server/api/routers/traces";
import { IOPreview } from "@/src/components/trace/IOPreview";
@@ -21,6 +21,9 @@ import { ScoresPreview } from "@/src/components/trace/ScoresPreview";
import { AnnotateDrawer } from "@/src/features/scores/components/AnnotateDrawer";
import useLocalStorage from "@/src/components/useLocalStorage";
import { CommentDrawerButton } from "@/src/features/comments/CommentDrawerButton";
+import { useMemo } from "react";
+import { usdFormatter } from "@/src/utils/numbers";
+import { calculateDisplayTotalCost } from "@/src/components/trace/lib/helpers";
export const TracePreview = ({
trace,
@@ -50,6 +53,14 @@ export const TracePreview = ({
return acc;
}, new Map<ScoreSource, APIScore[]>());
+ const totalCost = useMemo(
+ () =>
+ calculateDisplayTotalCost({
+ allObservations: observations,
+ }),
+ [observations],
+ );
+
return (
<Card className="col-span-2 flex max-h-full flex-col overflow-hidden">
<div className="flex flex-shrink-0 flex-row justify-end gap-2">
@@ -92,13 +103,18 @@ export const TracePreview = ({
{formatIntervalSeconds(trace.latency)}
</Badge>
)}
- <TraceAggUsageBadge observations={observations} />
+ <AggUsageBadge observations={observations} />
{!!trace.release && (
<Badge variant="outline">Release: {trace.release}</Badge>
)}
{!!trace.version && (
<Badge variant="outline">Version: {trace.version}</Badge>
)}
+ {totalCost && (
+ <Badge variant="outline">
+ ∑ {usdFormatter(totalCost.toNumber())}
+ </Badge>
+ )}
</div>
</div>
<div className="flex flex-wrap gap-2">
diff --git a/web/src/components/trace/index.tsx b/web/src/components/trace/index.tsx
index 234434e455..1085a6115d 100644
--- a/web/src/components/trace/index.tsx
+++ b/web/src/components/trace/index.tsx
@@ -5,7 +5,7 @@ import { TracePreview } from "./TracePreview";
import Header from "@/src/components/layouts/header";
import { Badge } from "@/src/components/ui/badge";
-import { TraceAggUsageBadge } from "@/src/components/token-usage-badge";
+import { AggUsageBadge } from "@/src/components/token-usage-badge";
import { StringParam, useQueryParam, withDefault } from "use-query-params";
import { PublishTraceSwitch } from "@/src/components/publish-object-switch";
import { DetailPageNav } from "@/src/features/navigate-detail-pages/DetailPageNav";
@@ -26,7 +26,6 @@ import {
Network,
} from "lucide-react";
import { usdFormatter } from "@/src/utils/numbers";
-import Decimal from "decimal.js";
import { useCallback, useState } from "react";
import { DeleteButton } from "@/src/components/deleteButton";
import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
@@ -35,6 +34,7 @@ import { TraceTimelineView } from "@/src/components/trace/TraceTimelineView";
import { type APIScore } from "@langfuse/shared";
import { useSession } from "next-auth/react";
import { FullScreenPage } from "@/src/components/layouts/full-screen-page";
+import { calculateDisplayTotalCost } from "@/src/components/trace/lib/helpers";
export function Trace(props: {
observations: Array<ObservationReturnType>;
@@ -253,7 +253,9 @@ export function TracePage({ traceId }: { traceId: string }) {
const filterOptionTags = traceFilterOptions.data?.tags ?? [];
const allTags = filterOptionTags.map((t) => t.value);
- const totalCost = calculateDisplayTotalCost(trace.data?.observations ?? []);
+ const totalCost = calculateDisplayTotalCost({
+ allObservations: trace.data?.observations ?? [],
+ });
const [selectedTab, setSelectedTab] = useQueryParam(
"display",
@@ -331,11 +333,9 @@ export function TracePage({ traceId }: { traceId: string }) {
<Badge>User ID: {trace.data.userId}</Badge>
</Link>
) : null}
- <TraceAggUsageBadge observations={trace.data.observations} />
+ <AggUsageBadge observations={trace.data.observations} />
{totalCost ? (
- <Badge variant="outline">
- Total cost: {usdFormatter(totalCost.toNumber())}
- </Badge>
+ <Badge variant="outline">{usdFormatter(totalCost.toNumber())}</Badge>
) : undefined}
</div>
<div className="mt-3 rounded-lg border bg-card font-semibold text-card-foreground">
@@ -401,42 +401,3 @@ export function TracePage({ traceId }: { traceId: string }) {
</FullScreenPage>
);
}
-
-export const calculateDisplayTotalCost = (
- observations: ObservationReturnType[],
-) => {
- return observations.reduce(
- (prev: Decimal | undefined, curr: ObservationReturnType) => {
- // if we don't have any calculated costs, we can't do anything
- if (
- !curr.calculatedTotalCost &&
- !curr.calculatedInputCost &&
- !curr.calculatedOutputCost
- )
- return prev;
-
- // if we have either input or output cost, but not total cost, we can use that
- if (
- !curr.calculatedTotalCost &&
- (curr.calculatedInputCost || curr.calculatedOutputCost)
- ) {
- return prev
- ? prev.plus(
- curr.calculatedInputCost ??
- new Decimal(0).plus(
- curr.calculatedOutputCost ?? new Decimal(0),
- ),
- )
- : curr.calculatedInputCost ?? curr.calculatedOutputCost ?? undefined;
- }
-
- if (!curr.calculatedTotalCost) return prev;
-
- // if we have total cost, we can use that
- return prev
- ? prev.plus(curr.calculatedTotalCost)
- : curr.calculatedTotalCost;
- },
- undefined,
- );
-};
diff --git a/web/src/components/trace/lib/helpers.ts b/web/src/components/trace/lib/helpers.ts
index f7c873976d..dc77a72655 100644
--- a/web/src/components/trace/lib/helpers.ts
+++ b/web/src/components/trace/lib/helpers.ts
@@ -1,13 +1,14 @@
-import { $Enums } from "@langfuse/shared";
+import { ObservationType } from "@langfuse/shared";
import { type NestedObservation } from "@/src/utils/types";
import { type ObservationReturnType } from "@/src/server/api/routers/traces";
+import Decimal from "decimal.js";
-export type TreeItemType = $Enums.ObservationType | "TRACE";
+export type TreeItemType = ObservationType | "TRACE";
export const treeItemColors: Map<TreeItemType, string> = new Map([
- [$Enums.ObservationType.SPAN, "bg-muted-blue"],
- [$Enums.ObservationType.GENERATION, "bg-muted-orange"],
- [$Enums.ObservationType.EVENT, "bg-muted-green"],
+ [ObservationType.SPAN, "bg-muted-blue"],
+ [ObservationType.GENERATION, "bg-muted-orange"],
+ [ObservationType.EVENT, "bg-muted-green"],
["TRACE", "bg-input"],
]);
@@ -59,8 +60,72 @@ export function nestObservations(
obj.children.sort((a, b) => a.startTime.getTime() - b.startTime.getTime());
}
- // TODO sum token amounts per level
-
// Step 5: Return the roots.
return Array.from(roots.values());
}
+
+export function calculateDisplayTotalCost(p: {
+ allObservations: ObservationReturnType[];
+ rootObservationId?: string;
+}): Decimal | undefined {
+ // if parentObservationId is provided, only calculate cost for children of that observation
+ // need to be checked recursively for all children and children of children
+ // loop until no more children to be added
+ let observations = p.allObservations;
+
+ if (p.rootObservationId) {
+ observations = observations.filter(
+ (o) =>
+ o.parentObservationId === p.rootObservationId ||
+ o.id === p.rootObservationId,
+ );
+
+ while (true) {
+ const childrenToAdd = p.allObservations.filter(
+ (o) =>
+ o.parentObservationId &&
+ !observations.map((o2) => o2.id).includes(o.id) &&
+ observations.map((o2) => o2.id).includes(o.parentObservationId),
+ );
+ if (childrenToAdd.length === 0) break;
+ observations = [...observations, ...childrenToAdd];
+ }
+ }
+
+ const totalCost = observations.reduce(
+ (prev: Decimal | undefined, curr: ObservationReturnType) => {
+ // if we don't have any calculated costs, we can't do anything
+ if (
+ !curr.calculatedTotalCost &&
+ !curr.calculatedInputCost &&
+ !curr.calculatedOutputCost
+ )
+ return prev;
+
+ // if we have either input or output cost, but not total cost, we can use that
+ if (
+ !curr.calculatedTotalCost &&
+ (curr.calculatedInputCost || curr.calculatedOutputCost)
+ ) {
+ return prev
+ ? prev.plus(
+ curr.calculatedInputCost ??
+ new Decimal(0).plus(
+ curr.calculatedOutputCost ?? new Decimal(0),
+ ),
+ )
+ : curr.calculatedInputCost ?? curr.calculatedOutputCost ?? undefined;
+ }
+
+ if (!curr.calculatedTotalCost) return prev;
+
+ // if we have total cost, we can use that
+ return prev
+ ? prev.plus(curr.calculatedTotalCost)
+ : curr.calculatedTotalCost;
+ },
+ undefined,
+ );
+
+ return totalCost;
+}
diff --git a/web/src/features/dashboard/lib/dashboard-utils.ts b/web/src/features/dashboard/lib/dashboard-utils.ts
index 8389c0b084..c2c7383c50 100644
--- a/web/src/features/dashboard/lib/dashboard-utils.ts
+++ b/web/src/features/dashboard/lib/dashboard-utils.ts
@@ -21,7 +21,7 @@ export const createTracesTimeFilter = (
export const totalCostDashboardFormatted = (totalCost?: number) => {
return totalCost
? totalCost < 5
- ? usdFormatter(totalCost, 2, 4)
+ ? usdFormatter(totalCost, 2, 6)
: usdFormatter(totalCost, 2, 2)
: usdFormatter(0);
};
diff --git a/web/src/pages/project/[projectId]/users/[userId].tsx b/web/src/pages/project/[projectId]/users/[userId].tsx
index a7153a1fbb..3cab40e2a5 100644
--- a/web/src/pages/project/[projectId]/users/[userId].tsx
+++ b/web/src/pages/project/[projectId]/users/[userId].tsx
@@ -154,7 +154,7 @@ function OverviewTab({ userId, projectId }: TabProps) {
},
{
label: "Total Cost",
- value: usdFormatter(user.data.sumCalculatedTotalCost, 2, 2),
+ value: usdFormatter(user.data.sumCalculatedTotalCost),
},
]
: [];
diff --git a/web/src/utils/numbers.ts b/web/src/utils/numbers.ts
index 96229d8bd8..1e9e65db5c 100644
--- a/web/src/utils/numbers.ts
+++ b/web/src/utils/numbers.ts
@@ -1,3 +1,5 @@
+import Decimal from "decimal.js";
+
export const compactNumberFormatter = (number?: number | bigint) => {
return Intl.NumberFormat("en-US", {
notation: "compact",
@@ -32,10 +34,11 @@ export const latencyFormatter = (
};
export const usdFormatter = (
- number?: number | bigint,
+ number?: number | bigint | Decimal,
minimumFractionDigits: number = 2,
- maximumFractionDigits: number = 4,
+ maximumFractionDigits: number = 6,
) => {
+ const numberToFormat = number instanceof Decimal ? number.toNumber() : number;
return new Intl.NumberFormat("en-US", {
style: "currency",
currency: "USD",
@@ -44,7 +47,7 @@ export const usdFormatter = (
minimumFractionDigits,
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#maximumfractiondigits
maximumFractionDigits,
- }).format(number ?? 0);
+ }).format(numberToFormat ?? 0);
};
export function randomIntFromInterval(min: number, max: number) {