🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
chore(events-table): properly show usage and cost on top level obs (#11900)
Nimara82c0312f964
diff --git a/web/src/components/trace2/components/ObservationDetailView/ObservationDetailView.tsx b/web/src/components/trace2/components/ObservationDetailView/ObservationDetailView.tsxindex 0d80f02e1e..c57b8a4634 100644--- a/web/src/components/trace2/components/ObservationDetailView/ObservationDetailView.tsx+++ b/web/src/components/trace2/components/ObservationDetailView/ObservationDetailView.tsx@@ -59,6 +59,10 @@ import { ObservationDetailViewHeader } from "./ObservationDetailViewHeader";import { TraceLogView } from "../TraceLogView/TraceLogView";import { TRACE_VIEW_CONFIG } from "@/src/components/trace2/config/trace-view-config";import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";+import {+ aggregateTraceMetrics,+ getDescendantIds,+} from "@/src/components/trace2/lib/trace-aggregation";export interface ObservationDetailViewProps {observation: ObservationReturnTypeWithMetadata;@@ -79,11 +83,34 @@ export function ObservationDetailView({// V4 beta mode and observations for log tabconst { isBetaEnabled: isV4BetaEnabled } = useV4Beta();- const { observations } = useTraceData();+ const { observations, roots, nodeMap } = useTraceData();const showLogViewTab = isV4BetaEnabled && observations.length > 0;const isLogViewVirtualized =observations.length >= TRACE_VIEW_CONFIG.logView.virtualizationThreshold;+ // for v4:+ // is this observation topmost in tree? we don't check for root observation here as this is not necessarily given.+ // Uses the tree's roots array which handles orphans correctly+ const treeNode = nodeMap.get(observation.id);+ const isRoot = roots.some((root) => root.id === observation.id);++ // For root observations, compute subtree metrics for badge tooltips.+ // We compute this lazily here rather than in tree-building.ts because:+ // - TreeNode.totalCost just has the aggregated cost, we use it+ // - costDetails/usageDetails (for tooltips) aren't in TreeNode, adding them causes high memory for all nodes, esp on big traces+ // - computation only runs when viewing a root observation and is memo'd+ const subtreeMetrics = useMemo(() => {+ if (!isRoot || !treeNode) return null;+ const descendantIds = getDescendantIds(treeNode);+ const descendantIdSet = new Set(descendantIds);++ const descendants = observations.filter((obs) =>+ descendantIdSet.has(obs.id),+ );+ const allObservations = [observation, ...descendants];+ return aggregateTraceMetrics(allObservations);+ }, [isRoot, treeNode, observations, observation]);+// Map global tab to observation-specific tabs (preview, log, scores)// "log" tab only available in v4 mode when there are observationsconst selectedTab = useMemo(() => {@@ -246,6 +273,8 @@ export function ObservationDetailView({onSelectionUsed={handleSelectionUsed}isCommentDrawerOpen={isCommentDrawerOpen}onCommentDrawerOpenChange={setIsCommentDrawerOpen}+ subtreeMetrics={subtreeMetrics}+ treeNodeTotalCost={treeNode?.totalCost}/>{/* Tabs section */}diff --git a/web/src/components/trace2/components/ObservationDetailView/ObservationDetailViewHeader.tsx b/web/src/components/trace2/components/ObservationDetailView/ObservationDetailViewHeader.tsxindex 3932445a94..6becb15723 100644--- a/web/src/components/trace2/components/ObservationDetailView/ObservationDetailViewHeader.tsx+++ b/web/src/components/trace2/components/ObservationDetailView/ObservationDetailViewHeader.tsx@@ -46,6 +46,8 @@ import {type MetadataDomainClient,} from "@/src/utils/clientSideDomainTypes";import { type ScoreDomain } from "@langfuse/shared";+import { type AggregatedTraceMetrics } from "@/src/components/trace2/lib/trace-aggregation";+import type Decimal from "decimal.js";export interface ObservationDetailViewHeaderProps {observation: ObservationReturnTypeWithMetadata;@@ -67,6 +69,8 @@ export interface ObservationDetailViewHeaderProps {onSelectionUsed?: () => void;isCommentDrawerOpen?: boolean;onCommentDrawerOpenChange?: (open: boolean) => void;+ subtreeMetrics?: AggregatedTraceMetrics | null;+ treeNodeTotalCost?: Decimal;}export const ObservationDetailViewHeader = memo(@@ -82,6 +86,8 @@ export const ObservationDetailViewHeader = memo(onSelectionUsed,isCommentDrawerOpen,onCommentDrawerOpenChange,+ subtreeMetrics,+ treeNodeTotalCost,}: ObservationDetailViewHeaderProps) {// Format cost and usage valuesconst totalCost = observation.totalCost;@@ -193,16 +199,35 @@ export const ObservationDetailViewHeader = memo(/><EnvironmentBadge environment={observation.environment} /><CostBadge- totalCost={totalCost}- costDetails={observation.costDetails}- />- <UsageBadge- type={observation.type}- inputUsage={inputUsage}- outputUsage={outputUsage}- totalUsage={totalUsage}- usageDetails={observation.usageDetails}+ totalCost={+ subtreeMetrics+ ? (treeNodeTotalCost?.toNumber() ?? subtreeMetrics.totalCost)+ : totalCost+ }+ costDetails={+ subtreeMetrics?.costDetails ?? observation.costDetails+ }/>+ {subtreeMetrics ? (+ subtreeMetrics.hasGenerationLike &&+ subtreeMetrics.usageDetails && (+ <UsageBadge+ type="GENERATION"+ inputUsage={subtreeMetrics.inputUsage}+ outputUsage={subtreeMetrics.outputUsage}+ totalUsage={subtreeMetrics.totalUsage}+ usageDetails={subtreeMetrics.usageDetails}+ />+ )+ ) : (+ <UsageBadge+ type={observation.type}+ inputUsage={inputUsage}+ outputUsage={outputUsage}+ totalUsage={totalUsage}+ usageDetails={observation.usageDetails}+ />+ )}<VersionBadge version={observation.version} /><ModelBadgemodel={observation.model}diff --git a/web/src/components/trace2/components/TraceDetailView/TraceDetailView.tsx b/web/src/components/trace2/components/TraceDetailView/TraceDetailView.tsxindex 14d40258d0..cd5d0258d5 100644--- a/web/src/components/trace2/components/TraceDetailView/TraceDetailView.tsx+++ b/web/src/components/trace2/components/TraceDetailView/TraceDetailView.tsx@@ -192,6 +192,7 @@ export function TraceDetailView({{/* Header section (extracted component) */}<TraceDetailViewHeadertrace={trace}+ observations={observations}projectId={projectId}traceScores={traceScores}commentCount={comments.get(trace.id)}diff --git a/web/src/components/trace2/components/TraceDetailView/TraceDetailViewHeader.tsx b/web/src/components/trace2/components/TraceDetailView/TraceDetailViewHeader.tsxindex 98380e7fff..e10705f09a 100644--- a/web/src/components/trace2/components/TraceDetailView/TraceDetailViewHeader.tsx+++ b/web/src/components/trace2/components/TraceDetailView/TraceDetailViewHeader.tsx@@ -4,12 +4,12 @@* Contains:* - Title row with ItemBadge, trace name, CopyIdsPopover* - Action buttons (Dataset, Annotate, Queue, Comments)- * - Metadata badges (timestamp, session, user, environment, release, version)+ * - Metadata badges (timestamp, latency, session, user, environment, release, version, cost, usage)** Memoized to prevent unnecessary re-renders when tab state changes.*/-import { memo } from "react";+import { memo, useMemo } from "react";import {type TraceDomain,type ScoreDomain,@@ -17,6 +17,7 @@ import {} from "@langfuse/shared";import { type SelectionData } from "@/src/features/comments/contexts/InlineCommentSelectionContext";import { type WithStringifiedMetadata } from "@/src/utils/clientSideDomainTypes";+import { type ObservationReturnTypeWithMetadata } from "@/src/server/api/routers/traces";import { ItemBadge } from "@/src/components/ItemBadge";import { LocalIsoDate } from "@/src/components/LocalIsoDate";import { CopyIdsPopover } from "@/src/components/trace2/components/_shared/CopyIdsPopover";@@ -31,6 +32,12 @@ import {ReleaseBadge,VersionBadge,} from "./TraceMetadataBadges";+import { LatencyBadge } from "../ObservationDetailView/ObservationMetadataBadgesSimple";+import {+ CostBadge,+ UsageBadge,+} from "../ObservationDetailView/ObservationMetadataBadgesTooltip";+import { aggregateTraceMetrics } from "@/src/components/trace2/lib/trace-aggregation";export interface TraceDetailViewHeaderProps {trace: Omit<WithStringifiedMetadata<TraceDomain>, "input" | "output"> & {@@ -38,6 +45,7 @@ export interface TraceDetailViewHeaderProps {input: string | null;output: string | null;};+ observations: ObservationReturnTypeWithMetadata[];projectId: string;traceScores: WithStringifiedMetadata<ScoreDomain>[];commentCount: number | undefined;@@ -50,6 +58,7 @@ export interface TraceDetailViewHeaderProps {export const TraceDetailViewHeader = memo(function TraceDetailViewHeader({trace,+ observations,projectId,traceScores,commentCount,@@ -58,6 +67,11 @@ export const TraceDetailViewHeader = memo(function TraceDetailViewHeader({isCommentDrawerOpen,onCommentDrawerOpenChange,}: TraceDetailViewHeaderProps) {+ const aggregatedMetrics = useMemo(+ () => aggregateTraceMetrics(observations),+ [observations],+ );+return (<div className="flex-shrink-0 space-y-2 border-b p-2 @container">{/* Title row with actions */}@@ -131,11 +145,26 @@ export const TraceDetailViewHeader = memo(function TraceDetailViewHeader({{/* Other badges */}<div className="flex flex-wrap items-center gap-1">+ <LatencyBadge latencySeconds={trace.latency ?? null} /><SessionBadge sessionId={trace.sessionId} projectId={projectId} /><UserIdBadge userId={trace.userId} projectId={projectId} /><EnvironmentBadge environment={trace.environment} /><ReleaseBadge release={trace.release} /><VersionBadge version={trace.version} />+ <CostBadge+ totalCost={aggregatedMetrics.totalCost}+ costDetails={aggregatedMetrics.costDetails}+ />+ {aggregatedMetrics.hasGenerationLike &&+ aggregatedMetrics.usageDetails && (+ <UsageBadge+ type="GENERATION"+ inputUsage={aggregatedMetrics.inputUsage}+ outputUsage={aggregatedMetrics.outputUsage}+ totalUsage={aggregatedMetrics.totalUsage}+ usageDetails={aggregatedMetrics.usageDetails}+ />+ )}</div></div></div>diff --git a/web/src/components/trace2/lib/trace-aggregation.ts b/web/src/components/trace2/lib/trace-aggregation.tsnew file mode 100644index 0000000000..56b6d7c36f--- /dev/null+++ b/web/src/components/trace2/lib/trace-aggregation.ts@@ -0,0 +1,95 @@+/**+ * Trace-level metrics aggregation utility+ *+ * Aggregates cost and usage data from observations for display in headers.+ * Used for both trace-level (all observations) and observation-level (descendants) aggregation.+ */++import { type ObservationReturnTypeWithMetadata } from "@/src/server/api/routers/traces";+import { type ObservationType, isGenerationLike } from "@langfuse/shared";+import { type TreeNode } from "./types";++export interface AggregatedTraceMetrics {+ totalCost: number | null;+ costDetails: Record<string, number> | undefined;+ totalUsage: number;+ inputUsage: number;+ outputUsage: number;+ usageDetails: Record<string, number> | undefined;+ hasGenerationLike: boolean;+}++/**+ * Aggregates metrics from all observations in a trace.+ *+ * - totalCost: sum of all observation costs (null if no costs)+ * - costDetails: merged breakdown from all observations+ * - usage fields: summed across all generation-like observations+ * - hasGenerationLike: true if any observation is generation-like (for showing usage badge)+ */+export function aggregateTraceMetrics(+ observations: ObservationReturnTypeWithMetadata[],+): AggregatedTraceMetrics {+ let totalCost: number | null = null;+ const costDetails: Record<string, number> = {};+ let totalUsage = 0;+ let inputUsage = 0;+ let outputUsage = 0;+ const usageDetails: Record<string, number> = {};+ let hasGenerationLike = false;++ for (const obs of observations) {+ // Aggregate cost+ if (obs.totalCost != null) {+ totalCost = (totalCost ?? 0) + Number(obs.totalCost);+ }++ // Merge cost details+ if (obs.costDetails) {+ for (const [key, value] of Object.entries(obs.costDetails)) {+ costDetails[key] = (costDetails[key] ?? 0) + value;+ }+ }++ // Only aggregate usage for generation-like observations+ if (isGenerationLike(obs.type as ObservationType)) {+ hasGenerationLike = true;+ totalUsage += obs.totalUsage ?? 0;+ inputUsage += obs.inputUsage ?? 0;+ outputUsage += obs.outputUsage ?? 0;++ // Merge usage details+ if (obs.usageDetails) {+ for (const [key, value] of Object.entries(obs.usageDetails)) {+ usageDetails[key] = (usageDetails[key] ?? 0) + value;+ }+ }+ }+ }++ return {+ totalCost,+ costDetails: Object.keys(costDetails).length > 0 ? costDetails : undefined,+ totalUsage,+ inputUsage,+ outputUsage,+ usageDetails:+ Object.keys(usageDetails).length > 0 ? usageDetails : undefined,+ hasGenerationLike,+ };+}++/**+ * Collects all descendant IDs from a TreeNode using iterative DFS.+ * Does NOT include the node itself - only its descendants.+ */+export function getDescendantIds(node: TreeNode): string[] {+ const ids: string[] = [];+ const stack = [...node.children];+ while (stack.length > 0) {+ const current = stack.pop()!;+ ids.push(current.id);+ stack.push(...current.children);+ }+ return ids;+}