🪢 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
perf: improve user metrics for large projects (#4568)
Max Deichmann99e9825e6659
diff --git a/packages/shared/src/server/repositories/traces.ts b/packages/shared/src/server/repositories/traces.tsindex 139637ed9d..3369c5ef58 100644--- a/packages/shared/src/server/repositories/traces.ts+++ b/packages/shared/src/server/repositories/traces.ts@@ -630,59 +630,95 @@ export const getUserMetrics = async (projectId: string, userIds: string[]) => {if (userIds.length === 0) {return [];}+ // this query uses window functions on observations + traces to always get only the first row and thereby remove deduplicates+ // we filter wherever possible by project id and user idconst query = `- WITH observations_agg AS (- SELECT o.trace_id,- count(*) as obs_count,- sumMap(usage_details) as sum_usage_details,- sum(total_cost) as sum_total_cost,- anyLast(project_id) as project_id- FROM observations o FINAL- WHERE o.project_id = {projectId: String}- GROUP BY o.trace_id- ),- user_metric_data AS (- SELECT t.user_id,- max(t.timestamp) as max_timestamp,- min(t.timestamp) as min_timestamp,- count(*) as trace_count,- sum(o.obs_count) as total_observations,- sum(o.sum_total_cost) as session_total_cost,- sumMap(o.sum_usage_details)['input'] as session_input_usage,- sumMap(o.sum_usage_details)['output'] as session_output_usage,- sumMap(o.sum_usage_details)['total'] as session_total_usage- FROM traces t FINAL- LEFT JOIN observations_agg o- ON t.id = o.trace_id- AND t.project_id = o.project_id- WHERE t.user_id IS NOT NULL- AND t.user_id != ''- AND t.user_id IN ({userIds: Array(String)})- AND t.project_id = {projectId: String}- GROUP BY t.user_id+ WITH stats as (+ SELECT+ t.user_id as user_id,+ count(distinct o.id) as obs_count,+ sumMap(usage_details) as sum_usage_details,+ sum(total_cost) as sum_total_cost,+ max(t.timestamp) as max_timestamp,+ min(t.timestamp) as min_timestamp,+ count(distinct t.id) as trace_count+ FROM+ (+ SELECT+ o.project_id,+ o.trace_id,+ o.usage_details,+ o.total_cost,+ id,+ ROW_NUMBER() OVER (+ PARTITION BY id+ ORDER BY+ event_ts DESC+ ) AS rn+ FROM+ observations o+ WHERE+ o.project_id = {projectId: String }+ AND o.trace_id in (+ SELECT+ distinct id+ from+ traces+ where+ user_id IN ({userIds: Array(String) })+ AND project_id = {projectId: String }+ )+ AND o.type = 'GENERATION'+ ) as o+ JOIN (+ SELECT+ t.id,+ t.user_id,+ t.project_id,+ t.timestamp,+ ROW_NUMBER() OVER (+ PARTITION BY id+ ORDER BY+ event_ts DESC+ ) AS rn+ FROM+ traces t+ WHERE+ t.user_id IN ({userIds: Array(String) })+ AND t.project_id = {projectId: String }+ ) as t on t.id = o.trace_id+ and t.project_id = o.project_id+ WHERE+ o.rn = 1+ and t.rn = 1+ group by+ t.user_id)- SELECT user_id AS userId,- min_timestamp as firstTrace,- max_timestamp as lastTrace,- trace_count as totalTraces,- total_observations as totalObservations,- session_input_usage as totalPromptTokens,- session_output_usage as totalCompletionTokens,- session_total_usage as totalTokens,- session_total_cost as sumCalculatedTotalCost- FROM user_metric_data umd+ SELECT+ sum_usage_details [ 'input' ] as input_usage,+ sum_usage_details [ 'output' ] as output_usage,+ sum_usage_details [ 'total' ] as total_usage,+ obs_count,+ trace_count,+ user_id,+ sum_total_cost,+ max_timestamp,+ min_timestamp+ FROM+ stats+`;- return queryClickhouse<{- userId: string;- firstTrace: Date | null;- lastTrace: Date | null;- totalPromptTokens: bigint;- totalCompletionTokens: bigint;- totalTokens: bigint;- totalObservations: bigint;- totalTraces: bigint;- sumCalculatedTotalCost: number;+ const rows = await queryClickhouse<{+ user_id: string;+ max_timestamp: string;+ min_timestamp: string;+ input_usage: string;+ output_usage: string;+ total_usage: string;+ obs_count: string;+ trace_count: string;+ sum_total_cost: string;}>({query,params: {@@ -690,4 +726,15 @@ export const getUserMetrics = async (projectId: string, userIds: string[]) => {userIds,},});+ return rows.map((row) => ({+ userId: row.user_id,+ maxTimestamp: parseClickhouseUTCDateTimeFormat(row.max_timestamp),+ minTimestamp: parseClickhouseUTCDateTimeFormat(row.min_timestamp),+ inputUsage: Number(row.input_usage),+ outputUsage: Number(row.output_usage),+ totalUsage: Number(row.total_usage),+ observationCount: Number(row.obs_count),+ traceCount: Number(row.trace_count),+ totalCost: Number(row.sum_total_cost),+ }));};diff --git a/web/src/__tests__/async/users-ui-table.servertest.ts b/web/src/__tests__/async/users-ui-table.servertest.tsnew file mode 100644index 0000000000..0e209a4a25--- /dev/null+++ b/web/src/__tests__/async/users-ui-table.servertest.ts@@ -0,0 +1,68 @@+import {+ createObservation as createObservationObject,+ createTrace,+} from "@/src/__tests__/fixtures/tracing-factory";+import {+ createObservationsCh as createObservationsInClickhouse,+ createTracesCh,+} from "@/src/__tests__/async/repositories/clickhouse-helpers";+import { v4 as uuidv4 } from "uuid";+import { getUserMetrics } from "@langfuse/shared/src/server";++const projectId = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";++describe("getUserMetrics function", () => {+ it("should return correct user metrics for a trace with two observations", async () => {+ const userId = uuidv4();+ const traceId = uuidv4();++ const trace = createTrace({+ id: traceId,+ project_id: projectId,+ user_id: userId,+ });++ await createTracesCh([trace]);++ const observation1 = createObservationObject({+ id: uuidv4(),+ trace_id: traceId,+ project_id: projectId,+ usage_details: {+ input: 100,+ output: 200,+ total: 300,+ },+ total_cost: 50,+ type: "GENERATION",+ });++ const observation2 = createObservationObject({+ id: uuidv4(),+ trace_id: traceId,+ project_id: projectId,+ usage_details: {+ input: 150,+ output: 250,+ total: 400,+ },+ total_cost: 75,+ type: "GENERATION",+ });++ await createObservationsInClickhouse([observation1, observation2]);++ const userMetrics = await getUserMetrics(projectId, [userId]);++ expect(userMetrics.length).toBe(1);+ expect(userMetrics[0]).toMatchObject({+ userId: userId,+ inputUsage: 250, // 100 + 150+ outputUsage: 450, // 200 + 250+ totalUsage: 700, // 300 + 400+ observationCount: 2,+ traceCount: 1,+ totalCost: 125, // 50 + 75+ });+ });+});diff --git a/web/src/server/api/routers/users.ts b/web/src/server/api/routers/users.tsindex d04ff1c32c..1079671647 100644--- a/web/src/server/api/routers/users.ts+++ b/web/src/server/api/routers/users.ts@@ -182,7 +182,19 @@ export const userRouter = createTRPCRouter({if (input.userIds.length === 0) {return [];}- return getUserMetrics(input.projectId, input.userIds);+ const metrics = await getUserMetrics(input.projectId, input.userIds);++ return metrics.map((metric) => ({+ userId: metric.userId,+ firstTrace: metric.minTimestamp,+ lastTrace: metric.maxTimestamp,+ totalPromptTokens: BigInt(metric.inputUsage),+ totalCompletionTokens: BigInt(metric.outputUsage),+ totalTokens: BigInt(metric.totalUsage),+ totalObservations: BigInt(metric.observationCount),+ totalTraces: BigInt(metric.traceCount),+ sumCalculatedTotalCost: metric.totalCost,+ }));},});}),@@ -234,32 +246,35 @@ export const userRouter = createTRPCRouter({LIMIT 50`;+ const res = result.shift();+return {userId: input.userId,- firstTrace: result[0]?.firstTrace,- lastTrace: result[0]?.lastTrace,- totalTraces: result[0]?.totalTraces ?? 0,- totalPromptTokens: result[0]?.totalPromptTokens ?? 0,- totalCompletionTokens: result[0]?.totalCompletionTokens ?? 0,- totalTokens: result[0]?.totalTokens ?? 0,- totalObservations: result[0]?.totalObservations ?? 0,- sumCalculatedTotalCost: result[0]?.sumCalculatedTotalCost ?? 0,+ firstTrace: res?.firstTrace,+ lastTrace: res?.lastTrace,+ totalTraces: res?.totalTraces ?? 0,+ totalPromptTokens: res?.totalPromptTokens ?? 0,+ totalCompletionTokens: res?.totalCompletionTokens ?? 0,+ totalTokens: res?.totalTokens ?? 0,+ totalObservations: res?.totalObservations ?? 0,+ sumCalculatedTotalCost: res?.sumCalculatedTotalCost ?? 0,};},clickhouseExecution: async () => {const result = (await getUserMetrics(input.projectId, [input.userId])).shift();+return {userId: input.userId,- firstTrace: result?.firstTrace,- lastTrace: result?.lastTrace,- totalTraces: result?.totalTraces ?? 0,- totalPromptTokens: result?.totalPromptTokens ?? 0,- totalCompletionTokens: result?.totalCompletionTokens ?? 0,- totalTokens: result?.totalTokens ?? 0,- totalObservations: result?.totalObservations ?? 0,- sumCalculatedTotalCost: result?.sumCalculatedTotalCost ?? 0,+ firstTrace: result?.minTimestamp,+ lastTrace: result?.maxTimestamp,+ totalTraces: result?.traceCount ?? 0,+ totalPromptTokens: result?.inputUsage ?? 0,+ totalCompletionTokens: result?.outputUsage ?? 0,+ totalTokens: result?.totalUsage ?? 0,+ totalObservations: result?.observationCount ?? 0,+ sumCalculatedTotalCost: result?.totalCost ?? 0,};},});