🪢 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: migrate user chart to new query builder (#6262)
Steffen Schmitz3802b1849d8a
diff --git a/web/src/__tests__/queryBuilderDashboards.servertest.ts b/web/src/__tests__/queryBuilderDashboards.servertest.tsindex a83db40c6d..42f6e6cd9b 100644--- a/web/src/__tests__/queryBuilderDashboards.servertest.ts+++ b/web/src/__tests__/queryBuilderDashboards.servertest.ts@@ -10,6 +10,8 @@ import {getScoreAggregate,groupTracesByTime,getTotalObservationUsageByTimeByModel,+ getModelUsageByUser,+ getTracesGroupedByUsers,} from "@langfuse/shared/src/server";import { type FilterState } from "@langfuse/shared";import { type QueryType } from "@/src/features/query/types";@@ -1040,4 +1042,131 @@ describe("selfServeDashboards", () => {});});});++ describe("observations-usage-by-users query", () => {+ it("should return the same result with query builder as with legacy function", async () => {+ // 1. Get result using the legacy function+ const legacyResult = await getModelUsageByUser(projectId, [+ {+ type: "datetime",+ operator: ">=",+ column: "timestamp",+ value: new Date(defaultFromTime),+ },+ {+ type: "datetime",+ operator: "<=",+ column: "timestamp",+ value: new Date(defaultToTime),+ },+ ]);++ // 2. Define the equivalent query for the query builder+ const queryBuilderQuery: QueryType = {+ view: "observations",+ dimensions: [{ field: "userId" }],+ metrics: [{ measure: "totalCost", aggregation: "sum" }],+ filters: [],+ timeDimension: null,+ fromTimestamp: defaultFromTime,+ toTimestamp: defaultToTime,+ orderBy: null,+ };++ // 3. Get result using the query builder+ const queryBuilderResult = await executeQuery(+ projectId,+ queryBuilderQuery,+ );++ // 4. Verify both results+ expect(queryBuilderResult).toBeDefined();+ expect(legacyResult).toBeDefined();++ // Verify both result sets have the same number of rows+ expect(legacyResult.length).toBe(queryBuilderResult.length);++ // Create maps for easier comparison+ const legacyResultMap = new Map(+ legacyResult.map((item) => [item.userId, item]),+ );++ // Verify each user's costs and token usage match+ queryBuilderResult.forEach((row: any) => {+ const userId = row.user_id;+ const legacyData = legacyResultMap.get(userId);++ expect(legacyData).toBeDefined();+ expect(Number(row.sum_total_cost)).toBe(+ Number(legacyData?.sumCostDetails),+ );+ });+ });+ });++ describe("traces-grouped-by-user query", () => {+ it("should return the same result with query builder as with legacy function", async () => {+ // 1. Get result using the legacy function+ const legacyResult = await getTracesGroupedByUsers(+ projectId,+ [+ {+ type: "datetime",+ operator: ">=",+ column: "timestamp",+ value: new Date(defaultFromTime),+ },+ {+ type: "datetime",+ operator: "<=",+ column: "timestamp",+ value: new Date(defaultToTime),+ },+ ],+ undefined,+ 1000,+ 0,+ dashboardColumnDefinitions,+ );++ // 2. Define the equivalent query for the query builder+ const queryBuilderQuery: QueryType = {+ view: "traces",+ dimensions: [{ field: "userId" }],+ metrics: [{ measure: "count", aggregation: "count" }],+ filters: [],+ timeDimension: null,+ fromTimestamp: defaultFromTime,+ toTimestamp: defaultToTime,+ orderBy: null,+ };++ // 3. Get result using the query builder+ const queryBuilderResult = await executeQuery(+ projectId,+ queryBuilderQuery,+ );++ // 4. Verify both results+ expect(queryBuilderResult).toBeDefined();+ expect(legacyResult).toBeDefined();++ // Verify both result sets have the same number of rows+ expect(legacyResult.length).toBe(queryBuilderResult.length);++ // Create maps for easier comparison+ const legacyResultMap = new Map(+ legacyResult.map((item) => [item.user, item]),+ );++ // Verify each user's trace count matches+ queryBuilderResult.forEach((row: any) => {+ const userId = row.user_id;+ const legacyData = legacyResultMap.get(userId);++ expect(legacyData).toBeDefined();+ expect(Number(row.count_count)).toBe(Number(legacyData?.count));+ });+ });+ });});diff --git a/web/src/features/dashboard/components/UserChart.tsx b/web/src/features/dashboard/components/UserChart.tsxindex afadd82a01..3b500aef56 100644--- a/web/src/features/dashboard/components/UserChart.tsx+++ b/web/src/features/dashboard/components/UserChart.tsx@@ -7,12 +7,12 @@ import { BarList } from "@tremor/react";import { TotalMetric } from "@/src/features/dashboard/components/TotalMetric";import { ExpandListButton } from "@/src/features/dashboard/components/cards/ChevronButton";import { useState } from "react";-import {- createTracesTimeFilter,- totalCostDashboardFormatted,-} from "@/src/features/dashboard/lib/dashboard-utils";-import { env } from "@/src/env.mjs";+import { totalCostDashboardFormatted } from "@/src/features/dashboard/lib/dashboard-utils";import { NoDataOrLoading } from "@/src/components/NoDataOrLoading";+import {+ type QueryType,+ mapLegacyUiTableFilterToView,+} from "@/src/features/query";type BarChartDataPoint = {name: string;@@ -23,44 +23,46 @@ export const UserChart = ({className,projectId,globalFilterState,+ fromTimestamp,+ toTimestamp,isLoading = false,}: {className?: string;projectId: string;globalFilterState: FilterState;+ fromTimestamp: Date;+ toTimestamp: Date;isLoading?: boolean;}) => {const [isExpanded, setIsExpanded] = useState(false);- const user = api.dashboard.chart.useQuery(+ // Define the query for user cost data using the new QueryType structure+ const userCostQuery: QueryType = {+ view: "observations",+ dimensions: [{ field: "userId" }],+ metrics: [+ { measure: "totalCost", aggregation: "sum" },+ { measure: "count", aggregation: "count" },+ ],+ filters: [+ ...mapLegacyUiTableFilterToView("observations", globalFilterState),+ {+ column: "type",+ operator: "=",+ value: "GENERATION",+ type: "string",+ },+ ],+ timeDimension: null,+ fromTimestamp: fromTimestamp.toISOString(),+ toTimestamp: toTimestamp.toISOString(),+ orderBy: null,+ };++ // Execute the query using the new dashboard.executeQuery functionality+ const user = api.dashboard.executeQuery.useQuery({projectId,- from: env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION // Langfuse Cloud has already completed the cost backfill job, thus cost can be pulled directly from obs. table- ? "traces_observations"- : "traces_observationsview",- select: [- { column: "calculatedTotalCost", agg: "SUM" },- { column: "user" },- { column: "traceId", agg: "COUNT" },- ],- filter: [- ...globalFilterState,- {- type: "string",- column: "type",- operator: "=",- value: "GENERATION",- },- ],- groupBy: [- {- type: "string",- column: "user",- },- ],- orderBy: [- { column: "calculatedTotalCost", direction: "DESC", agg: "SUM" },- ],- queryName: "observations-usage-by-users",+ query: userCostQuery,},{trpc: {@@ -72,20 +74,23 @@ export const UserChart = ({},);- const traces = api.dashboard.chart.useQuery(+ // Define the query for trace count data using the new QueryType structure+ const traceCountQuery: QueryType = {+ view: "traces",+ dimensions: [{ field: "userId" }],+ metrics: [{ measure: "count", aggregation: "count" }],+ filters: mapLegacyUiTableFilterToView("traces", globalFilterState),+ timeDimension: null,+ fromTimestamp: fromTimestamp.toISOString(),+ toTimestamp: toTimestamp.toISOString(),+ orderBy: null,+ };++ // Execute the query using the new dashboard.executeQuery functionality+ const traces = api.dashboard.executeQuery.useQuery({projectId,- from: "traces",- select: [{ column: "user" }, { column: "traceId", agg: "COUNT" }],- filter: createTracesTimeFilter(globalFilterState),- groupBy: [- {- type: "string",- column: "user",- },- ],- orderBy: [{ column: "traceId", agg: "COUNT", direction: "DESC" }],- queryName: "traces-grouped-by-user",+ query: traceCountQuery,},{trpc: {@@ -99,35 +104,33 @@ export const UserChart = ({const transformedNumberOfTraces: BarChartDataPoint[] = traces.data? traces.data- .filter((item) => item.user !== undefined)+ .filter((item) => item.user_id !== undefined).map((item) => {return {- name: item.user as string,- value: item.countTraceId ? (item.countTraceId as number) : 0,+ name: item.user_id as string,+ value: item.count_count ? Number(item.count_count) : 0,};}): [];const transformedCost: BarChartDataPoint[] = user.data? user.data- .filter((item) => item.user !== undefined)+ .filter((item) => item.user_id !== undefined).map((item) => {return {- name: (item.user as string | null | undefined) ?? "Unknown",- value: item.sumCalculatedTotalCost- ? (item.sumCalculatedTotalCost as number)- : 0,+ name: (item.user_id as string | null | undefined) ?? "Unknown",+ value: item.sum_total_cost ? Number(item.sum_total_cost) : 0,};}): [];const totalCost = user.data?.reduce(- (acc, curr) => acc + (curr.sumCalculatedTotalCost as number),+ (acc, curr) => acc + (Number(curr.sum_total_cost) || 0),0,);const totalTraces = traces.data?.reduce(- (acc, curr) => acc + (curr.countTraceId as number),+ (acc, curr) => acc + (Number(curr.count_count) || 0),0,);diff --git a/web/src/features/dashboard/server/dashboard-router.ts b/web/src/features/dashboard/server/dashboard-router.tsindex 5e6c887958..a2575890d4 100644--- a/web/src/features/dashboard/server/dashboard-router.ts+++ b/web/src/features/dashboard/server/dashboard-router.ts@@ -14,8 +14,6 @@ import {getScoreAggregate,getDistinctModels,getScoresAggregateOverTime,- getTracesGroupedByUsers,- getModelUsageByUser,getModelLatenciesOverTime,getObservationLatencies,getTracesLatencies,@@ -29,7 +27,6 @@ import {queryClickhouse,} from "@langfuse/shared/src/server";import { type DatabaseRow } from "@/src/server/api/services/sqlInterface";-import { dashboardColumnDefinitions } from "@langfuse/shared";import { QueryBuilder } from "@/src/features/query/server/queryBuilder";import {type QueryType,@@ -55,8 +52,8 @@ export const dashboardRouter = createTRPCRouter({"observations-cost-by-type-timeseries","distinct-models","scores-aggregate-timeseries",- "observations-usage-by-users",- "traces-grouped-by-user",+ // "observations-usage-by-users",+ // "traces-grouped-by-user","observation-latencies-aggregated","traces-latencies-aggregated","model-latencies-over-time",@@ -167,33 +164,31 @@ export const dashboardRouter = createTRPCRouter({);return aggregatedScores as DatabaseRow[];-- case "observations-usage-by-users":- const rowsUsers = await getModelUsageByUser(- input.projectId,- input.filter ?? [],- );-- return rowsUsers.map((row) => ({- sumTotalTokens: row.sumUsageDetails,- sumCalculatedTotalCost: row.sumCostDetails,- user: row.userId,- })) as DatabaseRow[];-- case "traces-grouped-by-user":- const traces = await getTracesGroupedByUsers(- input.projectId,- input.filter ?? [],- undefined,- 1000,- 0,- dashboardColumnDefinitions,- );-- return traces.map((row) => ({- user: row.user,- countTraceId: Number(row.count),- })) as DatabaseRow[];+ // case "observations-usage-by-users":+ // const rowsUsers = await getModelUsageByUser(+ // input.projectId,+ // input.filter ?? [],+ // );+ //+ // return rowsUsers.map((row) => ({+ // sumTotalTokens: row.sumUsageDetails,+ // sumCalculatedTotalCost: row.sumCostDetails,+ // user: row.userId,+ // })) as DatabaseRow[];+ // case "traces-grouped-by-user":+ // const traces = await getTracesGroupedByUsers(+ // input.projectId,+ // input.filter ?? [],+ // undefined,+ // 1000,+ // 0,+ // dashboardColumnDefinitions,+ // );+ //+ // return traces.map((row) => ({+ // user: row.user,+ // countTraceId: Number(row.count),+ // })) as DatabaseRow[];case "observation-latencies-aggregated":const latencies = await getObservationLatencies(input.projectId,diff --git a/web/src/pages/project/[projectId]/index.tsx b/web/src/pages/project/[projectId]/index.tsxindex e7efc87061..b2b8be8c5d 100644--- a/web/src/pages/project/[projectId]/index.tsx+++ b/web/src/pages/project/[projectId]/index.tsx@@ -273,7 +273,9 @@ export default function Dashboard() {<UserChartclassName="col-span-1 xl:col-span-3"projectId={projectId}- globalFilterState={mergedFilterState}+ globalFilterState={[...userFilterState, ...environmentFilter]}+ fromTimestamp={fromTimestamp}+ toTimestamp={toTimestamp}isLoading={environmentFilterOptions.isLoading}/><ChartScores