🪢 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: delayed loading for user metrics (#1338)
Max Deichmann4ac3b13ca6e5
diff --git a/web/src/pages/project/[projectId]/users.tsx b/web/src/pages/project/[projectId]/users.tsxindex f4e00550fb..2d1357e3d4 100644--- a/web/src/pages/project/[projectId]/users.tsx+++ b/web/src/pages/project/[projectId]/users.tsx@@ -1,7 +1,7 @@import Header from "@/src/components/layouts/header";import { api } from "@/src/utils/api";-import { type RouterInput } from "@/src/utils/types";+import { type RouterOutput, type RouterInput } from "@/src/utils/types";import { useEffect, useState } from "react";import TableLink from "@/src/components/table/table-link";import { DataTable } from "@/src/components/table/data-table";@@ -12,6 +12,9 @@ import { type Score } from "@prisma/client";import { useQueryParams, withDefault, NumberParam } from "use-query-params";import { useDetailPageLists } from "@/src/features/navigate-detail-pages/context";import { type LangfuseColumnDef } from "@/src/components/table/types";+import { Skeleton } from "@/src/components/ui/skeleton";++export type ScoreFilterInput = Omit<RouterInput["users"]["all"], "projectId">;type RowData = {userId: string;@@ -20,8 +23,6 @@ type RowData = {totalEvents: string;};-export type ScoreFilterInput = Omit<RouterInput["users"]["all"], "projectId">;-export default function UsersPage() {const router = useRouter();const projectId = router.query.projectId as string;@@ -40,14 +41,39 @@ export default function UsersPage() {limit: paginationState.pageSize,projectId,});- const totalCount = users.data?.slice(1)[0]?.totalCount ?? 0;++ // this API call will return an empty array if there are no users.+ // Hence this adds one fast unnecessary API call if there are no users.+ const userMetrics = api.users.metrics.useQuery({+ projectId,+ userIds: users.data?.users.map((u) => u.userId) ?? [],+ });++ type UserCoreOutput = RouterOutput["users"]["all"]["users"][number];+ type UserMetricsOutput = RouterOutput["users"]["metrics"][number];++ type CoreType = Omit<UserCoreOutput, "userId"> & { id: string };+ type MetricType = Omit<UserMetricsOutput, "userId"> & { id: string };++ const userRowData = joinTableCoreAndMetrics<CoreType, MetricType>(+ users.data?.users.map((u) => ({+ ...u,+ id: u.userId,+ })),+ userMetrics.data?.map((u) => ({+ ...u,+ id: u.userId,+ })),+ );++ const totalCount = userRowData.rows?.length ?? 0;useEffect(() => {if (users.isSuccess) {console.log("setting detail page list");setDetailPageList("users",- users.data.map((u) => encodeURIComponent(u.userId)),+ users.data.users.map((u) => encodeURIComponent(u.userId)),);}// eslint-disable-next-line react-hooks/exhaustive-deps@@ -74,14 +100,41 @@ export default function UsersPage() {{accessorKey: "firstEvent",header: "First Event",+ cell: ({ row }) => {+ const value: unknown = row.getValue("firstEvent");+ if (userMetrics.isFetching) {+ return <Skeleton className="h-3 w-1/2" />;+ }+ if (typeof value === "string") {+ return <>{value}</>;+ }+ },},{accessorKey: "totalCost",header: "Total Cost",+ cell: ({ row }) => {+ const value: unknown = row.getValue("totalCost");+ if (userMetrics.isFetching) {+ return <Skeleton className="h-3 w-1/2" />;+ }+ if (typeof value === "string") {+ return <>{value}</>;+ }+ },},{accessorKey: "lastEvent",header: "Last Event",+ cell: ({ row }) => {+ const value: unknown = row.getValue("lastEvent");+ if (userMetrics.isFetching) {+ return <Skeleton className="h-3 w-1/2" />;+ }+ if (typeof value === "string") {+ return <>{value}</>;+ }+ },},{accessorKey: "totalEvents",@@ -90,12 +143,25 @@ export default function UsersPage() {{accessorKey: "totalTokens",header: "Total Tokens",+ cell: ({ row }) => {+ const value: unknown = row.getValue("totalTokens");+ if (userMetrics.isFetching) {+ return <Skeleton className="h-3 w-1/2" />;+ }+ if (typeof value === "string") {+ return <>{value}</>;+ }+ },},{accessorKey: "lastScore",header: "Last Score",cell: ({ row }) => {const value: Score | null = row.getValue("lastScore");+ if (userMetrics.isFetching) {+ return <Skeleton className="h-3 w-1/2" />;+ }+return (<>{value ? (@@ -142,9 +208,9 @@ export default function UsersPage() {: {isLoading: false,isError: false,- data: users.data.map((t) => {+ data: userRowData.rows?.map((t) => {return {- userId: t.userId,+ userId: t.id,firstEvent:t.firstTrace?.toLocaleString() ?? "No event yet",lastEvent:@@ -153,9 +219,13 @@ export default function UsersPage() {(Number(t.totalTraces) || 0) +(Number(t.totalObservations) || 0),),- totalTokens: compactNumberFormatter(t.totalTokens),+ totalTokens: t.totalTokens+ ? compactNumberFormatter(t.totalTokens)+ : undefined,lastScore: t.lastScore,- totalCost: usdFormatter(t.sumCalculatedTotalCost, 2, 2),+ totalCost: t.sumCalculatedTotalCost+ ? usdFormatter(t.sumCalculatedTotalCost, 2, 2)+ : undefined,};}),}@@ -169,3 +239,50 @@ export default function UsersPage() {</div>);}++function joinTableCoreAndMetrics<+ Core extends { id: string },+ Metric extends { id: string },+>(+ userCoreData?: Core[],+ userMetricsData?: Metric[],+): {+ status: "loading" | "error" | "success";+ rows: (Core & Partial<Metric>)[] | undefined;+} {+ if (!userCoreData) {+ return { status: "error", rows: undefined };+ }++ const userCoreDataProcessed = userCoreData;++ if (!userMetricsData) {+ // create an object with all the keys of the UserMetrics type with undefined value++ return {+ status: "success",+ rows: userCoreDataProcessed.map((u) => ({+ ...u,+ ...({} as Partial<Metric>),+ })),+ };+ }++ const metricsById = userMetricsData.reduce<Record<string, Metric>>(+ (acc, metric) => {+ acc[metric.id] = metric;+ return acc;+ },+ {},+ );++ const joinedData = userCoreDataProcessed.map((userCore) => {+ const metrics = metricsById[userCore.id];+ return {+ ...userCore,+ ...(metrics ?? ({} as Partial<Metric>)),+ };+ });++ return { status: "success", rows: joinedData };+}diff --git a/web/src/server/api/routers/users.ts b/web/src/server/api/routers/users.tsindex fbeb447578..fe5203a4d0 100644--- a/web/src/server/api/routers/users.ts+++ b/web/src/server/api/routers/users.ts@@ -19,6 +19,16 @@ export const userRouter = createTRPCRouter({all: protectedProjectProcedure.input(UserAllOptions).query(async ({ input, ctx }) => {+ const uniqueUsers = await ctx.prisma.trace.findMany({+ where: {+ projectId: input.projectId,+ },+ select: {+ userId: true,+ },+ distinct: ["userId"],+ });+const topUsers = await ctx.prisma.$queryRaw<Array<{userId: string;@@ -40,6 +50,24 @@ export const userRouter = createTRPCRouter({${input.limit} OFFSET ${input.page * input.limit};`;+ return {+ totalUsers: uniqueUsers.length,+ users: topUsers,+ };+ }),++ metrics: protectedProjectProcedure+ .input(+ z.object({+ projectId: z.string(),+ userIds: z.array(z.string()),+ }),+ )+ .query(async ({ input, ctx }) => {+ if (input.userIds.length === 0) {+ return [];+ }+const users = await ctx.prisma.$queryRaw<Array<{userId: string;@@ -55,57 +83,54 @@ export const userRouter = createTRPCRouter({sumCalculatedTotalCost: number;}>>`+ SELECT+ t.user_id AS "userId",+ MIN(t."timestamp") AS "firstTrace",+ MAX(t."timestamp") AS "lastTrace",+ COALESCE(SUM(o.prompt_tokens), 0)::int AS "totalPromptTokens",+ COALESCE(SUM(o.completion_tokens), 0)::int AS "totalCompletionTokens",+ COALESCE(SUM(o.total_tokens), 0)::int AS "totalTokens",+ MIN(o."firstObservation") AS "firstObservation",+ MAX(o."lastObservation") AS "lastObservation",+ COUNT(o."totalObservations")::int AS "totalObservations",+ (COUNT(*) OVER ())::int AS "totalCount",+ SUM(COALESCE(ov.calculated_total_cost, 0)) AS "sumCalculatedTotalCost"+ FROM+ traces t+ LEFT JOIN LATERAL (SELECT- t.user_id AS "userId",- MIN(t."timestamp") AS "firstTrace",- MAX(t."timestamp") AS "lastTrace",- COALESCE(SUM(o.prompt_tokens), 0)::int AS "totalPromptTokens",- COALESCE(SUM(o.completion_tokens), 0)::int AS "totalCompletionTokens",- COALESCE(SUM(o.total_tokens), 0)::int AS "totalTokens",- MIN(o."firstObservation") AS "firstObservation",- MAX(o."lastObservation") AS "lastObservation",- COUNT(o."totalObservations")::int AS "totalObservations",- (COUNT(*) OVER ())::int AS "totalCount",- SUM(COALESCE(ov.calculated_total_cost, 0)) AS "sumCalculatedTotalCost"+ COALESCE(SUM(o.prompt_tokens), 0)::int AS "prompt_tokens",+ COALESCE(SUM(o.completion_tokens), 0)::int AS "completion_tokens",+ COALESCE(SUM(o.total_tokens), 0)::int AS "total_tokens",+ MIN(o.start_time) AS "firstObservation",+ MAX(o.start_time) AS "lastObservation",+ COUNT(DISTINCT o.id)::int AS "totalObservations"FROM- traces t- LEFT JOIN LATERAL (- SELECT- COALESCE(SUM(o.prompt_tokens), 0)::int AS "prompt_tokens",- COALESCE(SUM(o.completion_tokens), 0)::int AS "completion_tokens",- COALESCE(SUM(o.total_tokens), 0)::int AS "total_tokens",- MIN(o.start_time) AS "firstObservation",- MAX(o.start_time) AS "lastObservation",- COUNT(DISTINCT o.id)::int AS "totalObservations"- FROM- observations o- WHERE- o.trace_id = t.id- AND o.project_id = ${input.projectId}- GROUP BY- t.user_id- ) o ON TRUE- LEFT JOIN LATERAL (- SELECT- SUM(COALESCE(ov.calculated_total_cost, 0)) AS "calculated_total_cost"- FROM- observations_view ov- WHERE- ov.trace_id = t.id- AND ov."type" = 'GENERATION'- AND ov.project_id = ${input.projectId}- GROUP BY- t.user_id- ) ov ON TRUE+ observations oWHERE- t.user_id IN (${Prisma.join(- topUsers.map((user) => user.userId),- ",",- )})- AND t.project_id = ${input.projectId}+ o.trace_id = t.id+ AND o.project_id = ${input.projectId}GROUP BY- 1;- `;+ t.user_id+ ) o ON TRUE+ LEFT JOIN LATERAL (+ SELECT+ SUM(COALESCE(ov.calculated_total_cost, 0)) AS "calculated_total_cost"+ FROM+ observations_view ov+ WHERE+ ov.trace_id = t.id+ AND ov."type" = 'GENERATION'+ AND ov.project_id = ${input.projectId}+ GROUP BY+ t.user_id+ ) ov ON TRUE+ WHERE+ t.user_id IN (${Prisma.join(input.userIds, ",")})+ AND t.project_id = ${input.projectId}+ GROUP BY+ 1;+ `;if (users.length === 0) {return [];@@ -118,35 +143,34 @@ export const userRouter = createTRPCRouter({}>>`- WITH ranked_scores AS (- SELECT- t.user_id,- s.*,- ROW_NUMBER() OVER (PARTITION BY t.user_id ORDER BY s."timestamp" DESC) AS rn- FROM- scores s- JOIN traces t ON t.id = s.trace_id- WHERE- s.trace_id IS NOT NULL- AND t.project_id = ${input.projectId}- AND t.user_id IN (${Prisma.join(users.map((user) => user.userId))})- AND t.user_id IS NOT NULL- )- SELECT- user_id "userId",- "id",- "timestamp",- "name",- "value",- observation_id "observationId",- trace_id "traceId",- "comment"- FROM- ranked_scores- WHERE rn = 1- `;-- return topUsers.map((topUser) => {+ WITH ranked_scores AS (+ SELECT+ t.user_id,+ s.*,+ ROW_NUMBER() OVER (PARTITION BY t.user_id ORDER BY s."timestamp" DESC) AS rn+ FROM+ scores s+ JOIN traces t ON t.id = s.trace_id+ WHERE+ s.trace_id IS NOT NULL+ AND t.project_id = ${input.projectId}+ AND t.user_id IN (${Prisma.join(users.map((user) => user.userId))})+ AND t.user_id IS NOT NULL+ )+ SELECT+ user_id "userId",+ "id",+ "timestamp",+ "name",+ "value",+ observation_id "observationId",+ trace_id "traceId",+ "comment"+ FROM+ ranked_scores+ WHERE rn = 1+ `;+ return users.map((topUser) => {const user = users.find((user) => user.userId === topUser.userId);if (!user) {console.error("User not found", topUser.userId);