Skip to content

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

changes

Max Deichmanna2c7af335a53
diff --git a/src/components/table/use-cases/traces.tsx b/src/components/table/use-cases/traces.tsx
index 9d09aa0987..dca3629f5b 100644
--- a/src/components/table/use-cases/traces.tsx
+++ b/src/components/table/use-cases/traces.tsx
@@ -41,7 +41,6 @@ export type TraceFilterInput = Omit<
>;
export default function TracesTable({ projectId, userId }: TraceTableProps) {
- console.log("TracesTable", projectId, userId);
const [queryOptions, setQueryOptions] = useState<TraceFilterInput>({
scores: null,
name: null,
@@ -54,11 +53,6 @@ export default function TracesTable({ projectId, userId }: TraceTableProps) {
operator: null,
});
- console.log({
- ...queryOptions,
- userId: userId || null,
- projectId,
- });
const traces = api.traces.all.useQuery({
...queryOptions,
userId: userId || null,
diff --git a/src/features/dashboard/components/BaseTimeSeriesChart.tsx b/src/features/dashboard/components/BaseTimeSeriesChart.tsx
index 771187a9d1..04689991f7 100644
--- a/src/features/dashboard/components/BaseTimeSeriesChart.tsx
+++ b/src/features/dashboard/components/BaseTimeSeriesChart.tsx
@@ -1,4 +1,5 @@
import { type DateTimeAggregationOption } from "@/src/features/dashboard/lib/timeseriesAggregation";
+import { numberFormatter } from "@/src/utils/numbers";
import { AreaChart } from "@tremor/react";
export function BaseTimeSeriesChart(props: {
@@ -27,10 +28,6 @@ export function BaseTimeSeriesChart(props: {
});
}
- const dataFormatter = (number: number) => {
- return Intl.NumberFormat("us").format(number).toString();
- };
-
const convertDate = (date: number, agg: DateTimeAggregationOption) => {
if (agg === "24 hours" || agg === "1 hour") {
return new Date(date).toLocaleTimeString("en-US", {
@@ -56,7 +53,7 @@ export function BaseTimeSeriesChart(props: {
index="timestamp"
categories={Array.from(labels)}
colors={["indigo", "cyan"]}
- valueFormatter={dataFormatter}
+ valueFormatter={numberFormatter}
/>
);
}
diff --git a/src/features/feedback/server/feedbackHandler.ts b/src/features/feedback/server/feedbackHandler.ts
index 1992024ddd..49a81fba97 100644
--- a/src/features/feedback/server/feedbackHandler.ts
+++ b/src/features/feedback/server/feedbackHandler.ts
@@ -6,9 +6,6 @@ export default async function feedbackApiHandler(
req: NextApiRequest,
res: NextApiResponse
) {
- // Run the cors middleware
- console.log(JSON.stringify(req.body));
-
await runFeedbackCorsMiddleware(req, res);
try {
diff --git a/src/pages/project/[projectId]/scores.tsx b/src/pages/project/[projectId]/scores.tsx
index ec3682d1c9..ce07f29988 100644
--- a/src/pages/project/[projectId]/scores.tsx
+++ b/src/pages/project/[projectId]/scores.tsx
@@ -1,13 +1,5 @@
import Header from "@/src/components/layouts/header";
-import { api } from "@/src/utils/api";
-import { type ColumnDef } from "@tanstack/react-table";
-import { type RouterOutput, type RouterInput } from "@/src/utils/types";
-import { useState } from "react";
-import TableLink from "@/src/components/table/table-link";
-import { type TableRowOptions } from "@/src/components/table/types";
-import { DataTable } from "@/src/components/table/data-table";
-
import { useRouter } from "next/router";
import ScoresTable from "@/src/components/table/use-cases/scores";
diff --git a/src/pages/project/[projectId]/users.tsx b/src/pages/project/[projectId]/users.tsx
index b9ab155d5b..590b3a4d15 100644
--- a/src/pages/project/[projectId]/users.tsx
+++ b/src/pages/project/[projectId]/users.tsx
@@ -7,6 +7,9 @@ import { useState } from "react";
import TableLink from "@/src/components/table/table-link";
import { DataTable } from "@/src/components/table/data-table";
import { useRouter } from "next/router";
+import { numberFormatter } from "@/src/utils/numbers";
+import { GroupedScoreBadges } from "@/src/components/grouped-score-badge";
+import { type Score } from "@prisma/client";
type RowData = {
userId: string;
@@ -56,6 +59,30 @@ export default function UsersPage() {
accessorKey: "totalEvents",
header: "Total Events",
},
+ {
+ accessorKey: "totalTokens",
+ header: "Total Tokens",
+ },
+ {
+ accessorKey: "lastScore",
+ header: "Last Score",
+ cell: ({ row }) => {
+ const value: Score = row.getValue("lastScore");
+ return (
+ <div className="flex items-center gap-4">
+ <TableLink
+ path={
+ value?.observationId
+ ? `/project/${projectId}/traces/${value.traceId}?observation=${value.observationId}`
+ : `/project/${projectId}/traces/${value.traceId}`
+ }
+ value={value.traceId}
+ />
+ <GroupedScoreBadges scores={[value]} />
+ </div>
+ );
+ },
+ },
];
return (
@@ -77,14 +104,18 @@ export default function UsersPage() {
isLoading: false,
isError: false,
data: users.data?.map((t) => {
- console.log(t);
return {
userId: t.userId,
- firstEvent: t.firstEvent?.toISOString() ?? "No event yet",
- lastEvent: t.lastEvent?.toISOString() ?? "No event yet",
- totalEvents: (
- (t.totalTraces ?? 0) + (t.totalObservations ?? 0)
- ).toString(),
+ firstEvent:
+ t.firstObservation?.toISOString() ?? "No event yet",
+ lastEvent:
+ t.lastObservation?.toISOString() ?? "No event yet",
+ totalEvents: numberFormatter(
+ (Number(t.totalTraces) || 0) +
+ (Number(t.totalObservations) || 0)
+ ),
+ totalTokens: numberFormatter(t.totalTokens),
+ lastScore: t.lastScore,
};
}),
}
diff --git a/src/pages/project/[projectId]/users/[userId].tsx b/src/pages/project/[projectId]/users/[userId].tsx
index b8c7bec6e9..5409bb868c 100644
--- a/src/pages/project/[projectId]/users/[userId].tsx
+++ b/src/pages/project/[projectId]/users/[userId].tsx
@@ -4,6 +4,9 @@ import { api } from "@/src/utils/api";
import { useState } from "react";
import TracesTable from "@/src/components/table/use-cases/traces";
import ScoresTable from "@/src/components/table/use-cases/scores";
+import { numberFormatter } from "@/src/utils/numbers";
+import { GroupedScoreBadges } from "@/src/components/grouped-score-badge";
+import TableLink from "@/src/components/table/table-link";
type TabDefinition = {
name: string;
@@ -102,49 +105,76 @@ type TabProps = {
};
function DetailsTab({ userId, projectId }: TabProps) {
- console.log("DetailsTab", userId, projectId);
const user = api.users.byId.useQuery({ projectId: projectId, userId });
+ const userData = user.data
+ ? [
+ { label: "User Id", value: user.data.userId },
+ {
+ label: "First Observation",
+ value: user.data.firstObservation?.toISOString(),
+ },
+ {
+ label: "Last Observation",
+ value: user.data.lastObservation?.toISOString(),
+ },
+ { label: "Total Observations", value: user.data.totalObservations },
+ {
+ label: "Prompt Tokens",
+ value: numberFormatter(user.data.totalPromptTokens),
+ },
+ {
+ label: "Completion Tokens",
+ value: numberFormatter(user.data.totalCompletionTokens),
+ },
+ {
+ label: "Total Tokens",
+ value: numberFormatter(user.data.totalTokens),
+ },
+ ]
+ : [];
+
return (
<div className="mt-5 pt-5">
- {user.data ? (
+ {userData ? (
<div className="mt-6 border-t border-gray-100">
<dl className="divide-y divide-gray-100">
- <div className="px-4 py-6 sm:grid sm:grid-cols-3 sm:gap-4 sm:px-0">
- <dt className="text-sm font-medium leading-6 text-gray-900">
- User ID
- </dt>
- <dd className="mt-1 text-sm leading-6 text-gray-700 sm:col-span-2 sm:mt-0">
- {user.data?.userId}
- </dd>
- </div>
- <div className="px-4 py-6 sm:grid sm:grid-cols-3 sm:gap-4 sm:px-0">
- <dt className="text-sm font-medium leading-6 text-gray-900">
- First Event
- </dt>
- <dd className="mt-1 text-sm leading-6 text-gray-700 sm:col-span-2 sm:mt-0">
- {user.data?.firstEvent?.toISOString() ?? "No events yet"}
- </dd>
- </div>
- <div className="px-4 py-6 sm:grid sm:grid-cols-3 sm:gap-4 sm:px-0">
- <dt className="text-sm font-medium leading-6 text-gray-900">
- Last Event
- </dt>
- <dd className="mt-1 text-sm leading-6 text-gray-700 sm:col-span-2 sm:mt-0">
- {user.data?.lastEvent?.toISOString() ?? "No events yet"}
- </dd>
- </div>
- <div className="px-4 py-6 sm:grid sm:grid-cols-3 sm:gap-4 sm:px-0">
- <dt className="text-sm font-medium leading-6 text-gray-900">
- Total Events
- </dt>
- <dd className="mt-1 text-sm leading-6 text-gray-700 sm:col-span-2 sm:mt-0">
- {(
- (user.data?.totalTraces ?? 0) +
- (user.data?.totalObservations ?? 0)
- ).toString()}
- </dd>
- </div>
+ {userData.map((item) => (
+ <div
+ key={item.label}
+ className="px-4 py-6 sm:grid sm:grid-cols-3 sm:gap-4 sm:px-0"
+ >
+ <dt className="text-sm font-medium leading-6 text-gray-900">
+ {item.label}
+ </dt>
+ <dd className="mt-1 text-sm leading-6 text-gray-700 sm:col-span-2 sm:mt-0">
+ {item.value ?? "-"}
+ </dd>
+ </div>
+ ))}
+ {user.data?.lastScore ? (
+ <div
+ key="score"
+ className="px-4 py-6 sm:grid sm:grid-cols-3 sm:gap-4 sm:px-0"
+ >
+ <dt className="text-sm font-medium leading-6 text-gray-900">
+ Last Score
+ </dt>
+ <dd className="mt-1 text-sm leading-6 text-gray-700 sm:col-span-2 sm:mt-0">
+ <div className="flex items-center gap-4">
+ <TableLink
+ path={
+ user.data?.lastScore.observationId
+ ? `/project/${projectId}/traces/${user.data?.lastScore.traceId}?observation=${user.data?.lastScore.observationId}`
+ : `/project/${projectId}/traces/${user.data?.lastScore.traceId}`
+ }
+ value={user.data?.lastScore.traceId}
+ />
+ <GroupedScoreBadges scores={[user.data?.lastScore]} />
+ </div>
+ </dd>
+ </div>
+ ) : undefined}
</dl>
</div>
) : undefined}
diff --git a/src/server/api/routers/scores.ts b/src/server/api/routers/scores.ts
index d8b6948de9..d13c39eb22 100644
--- a/src/server/api/routers/scores.ts
+++ b/src/server/api/routers/scores.ts
@@ -169,7 +169,6 @@ export const scoresRouter = createTRPCRouter({
})
)
.mutation(async ({ input, ctx }) => {
- console.log(input);
const score = await ctx.prisma.score.findFirstOrThrow({
where: {
id: input.id,
diff --git a/src/server/api/routers/traces.ts b/src/server/api/routers/traces.ts
index a508a563d3..1d99ea1559 100644
--- a/src/server/api/routers/traces.ts
+++ b/src/server/api/routers/traces.ts
@@ -26,7 +26,6 @@ export const traceRouter = createTRPCRouter({
all: protectedProjectProcedure
.input(TraceFilterOptions)
.query(async ({ input, ctx }) => {
- console.log("input", input);
const traces = await ctx.prisma.trace.findMany({
where: {
AND: [
diff --git a/src/server/api/routers/users.ts b/src/server/api/routers/users.ts
index 61998dc47d..b17ad1feb7 100644
--- a/src/server/api/routers/users.ts
+++ b/src/server/api/routers/users.ts
@@ -21,79 +21,126 @@ export const userRouter = createTRPCRouter({
},
],
},
- by: ["userId"],
- _count: {
- _all: true,
- },
- take: 50,
- orderBy: {
- _count: { userId: "desc" },
- },
+ by: ["userId", "id"],
});
- const userIds = traces
- .map((t) => t.userId)
- .filter((s): s is string => Boolean(s));
+ const userIdToTraceIdsMap = traces.reduce((map, trace) => {
+ const userId = trace.userId;
+ const traceId = trace.id;
- const traceAnalytics = await ctx.prisma.trace.groupBy({
- where: {
- userId: {
- in: userIds,
- },
- },
- _min: {
- timestamp: true,
- },
- _max: {
- timestamp: true,
- },
- _count: {
- _all: true,
- },
- by: ["userId"],
- });
+ // If the user ID is not in the map, create a new entry with an array containing the trace ID
+
+ if (userId) {
+ if (!map.has(userId)) {
+ map.set(userId, [traceId]);
+ } else {
+ // If the user ID is already in the map, append the trace ID to the existing array
+ map.get(userId).push(traceId);
+ }
+ }
+
+ return map;
+ }, new Map<string, string[]>());
+
+ const userIds = Array.from(userIdToTraceIdsMap.keys());
+
+ const [traceAnalytics, observationAnalytics, lastScore] =
+ await Promise.all([
+ ctx.prisma.trace.groupBy({
+ where: {
+ userId: {
+ in: userIds,
+ },
+ },
+ _count: {
+ _all: true,
+ },
+ _min: {
+ timestamp: true,
+ },
+ _max: {
+ timestamp: true,
+ },
+ by: ["userId"],
+ }),
+ ctx.prisma.$queryRawUnsafe<
+ {
+ min_start_time: Date;
+ max_start_time: Date;
+ total_tokens: number;
+ prompt_tokens: number;
+ completion_tokens: number;
+ total_observations: number;
+ user_id: string;
+ }[]
+ >(`SELECT
+ MIN(observations.start_time) AS min_start_time,
+ MAX(observations.start_time) AS max_start_time,
+ SUM(observations.total_tokens) AS total_tokens,
+ SUM(observations.prompt_tokens) AS prompt_tokens,
+ SUM(observations.completion_tokens) AS completion_tokens,
+ count(*) as total_observations,
+ traces.user_id as user_id
+ FROM
+ observations
+ JOIN traces ON observations.trace_id = traces.id
+ WHERE
+ traces.user_id IN (${userIds.map((id) => `'${id}'`).join(",")})
+ GROUP BY
+ traces.user_id
+ `),
+ ctx.prisma.trace.findMany({
+ distinct: ["userId"],
+ orderBy: {
+ timestamp: "desc",
+ },
+ include: {
+ scores: {
+ orderBy: {
+ timestamp: "desc",
+ },
+ take: 1,
+ },
+ },
+ where: {
+ userId: {
+ in: userIds,
+ },
+ },
+ }),
+ ]);
return userIds.map((userId) => {
- const trace = traces.find((t) => t.userId === userId);
- const analytics = traceAnalytics.find((t) => t.userId === userId);
+ const traceAnalyticsForUser = traceAnalytics.find(
+ (t) => t.userId === userId
+ );
+ const observationAnalyticsForUser = observationAnalytics.find(
+ (o) => o.user_id === userId
+ );
+
+ if (!traceAnalyticsForUser || !observationAnalyticsForUser) {
+ throw new Error("User not found in analytics");
+ }
+
+ const returnedScore =
+ lastScore.find((s) => s.userId === userId)?.scores[0] ?? null;
return {
- userId,
- firstEvent: analytics?._min?.timestamp,
- lastEvent: analytics?._max?.timestamp,
- totalTraces: trace?._count?._all,
- totalObservations: analytics?._count?._all,
+ userId: userId,
+ firstTrace: traceAnalytics[0]?._min?.timestamp,
+ lastTrace: traceAnalytics[0]?._max?.timestamp,
+ totalTraces: traceAnalytics[0]?._count?._all,
+ totalPromptTokens: observationAnalyticsForUser.prompt_tokens ?? 0,
+ totalCompletionTokens:
+ observationAnalyticsForUser.completion_tokens ?? 0,
+ totalTokens: observationAnalyticsForUser.total_tokens ?? 0,
+ firstObservation: observationAnalyticsForUser.min_start_time,
+ lastObservation: observationAnalyticsForUser.max_start_time,
+ totalObservations: observationAnalyticsForUser.total_observations,
+ lastScore: returnedScore,
};
});
}),
- // availableFilterOptions: protectedProjectProcedure
- // .input(UserFilterOptions)
- // .query(async ({ input, ctx }) => {
- // const filter = {
- // AND: [
- // {
- // projectId: input.projectId,
- // },
- // ],
- // };
-
- // const traces = ctx.prisma.trace.groupBy({
- // where: filter,
- // by: ["userId"],
- // _count: {
- // _all: true,
- // },
- // });
-
- // return [
- // {
- // key: "users",
- // occurrences: traces.map((i) => {
- // return { key: i.name ?? "undefined", count: i._count };
- // }),
- // },
- // ];
- // }),
byId: protectedProjectProcedure
.input(
@@ -103,53 +150,69 @@ export const userRouter = createTRPCRouter({
})
)
.query(async ({ input, ctx }) => {
- const trace = await ctx.prisma.trace.groupBy({
- where: {
- AND: [
- {
- projectId: input.projectId,
+ const [traceAnalytics, observationAnalytics, lastScore] =
+ await Promise.all([
+ ctx.prisma.trace.groupBy({
+ where: {
userId: input.userId,
},
- ],
- },
- by: ["userId"],
- _count: {
- _all: true,
- },
- take: 50,
- orderBy: {
- _count: { userId: "desc" },
- },
- });
-
- const traceAnalytics = await ctx.prisma.trace.groupBy({
- where: {
- userId: input.userId,
- },
- _min: {
- timestamp: true,
- },
- _max: {
- timestamp: true,
- },
- _count: {
- _all: true,
- },
- by: ["userId"],
- });
-
- console.log("trace", trace);
- console.log("traceAnalytics", traceAnalytics);
-
- if (trace.length === 0 || traceAnalytics.length === 0)
- throw new Error("unexpected database result");
+ _count: {
+ _all: true,
+ },
+ _min: {
+ timestamp: true,
+ },
+ _max: {
+ timestamp: true,
+ },
+ by: ["userId"],
+ }),
+ ctx.prisma.observation.aggregate({
+ where: {
+ trace: {
+ userId: input.userId,
+ },
+ },
+ _sum: {
+ promptTokens: true,
+ completionTokens: true,
+ totalTokens: true,
+ },
+ _min: {
+ startTime: true,
+ },
+ _max: {
+ endTime: true,
+ },
+ _count: {
+ _all: true,
+ },
+ }),
+ ctx.prisma.score.findFirst({
+ where: {
+ trace: {
+ userId: input.userId,
+ },
+ },
+ orderBy: {
+ timestamp: "desc",
+ },
+ take: 1,
+ }),
+ ]);
return {
userId: input.userId,
- firstEvent: traceAnalytics[0]?._min?.timestamp,
- lastEvent: traceAnalytics[0]?._max?.timestamp,
- totalTraces: trace[0]?._count?._all,
- totalObservations: traceAnalytics[0]?._count?._all,
+ firstTrace: traceAnalytics[0]?._min?.timestamp,
+ lastTrace: traceAnalytics[0]?._max?.timestamp,
+ totalTraces: traceAnalytics[0]?._count?._all,
+ totalPromptTokens: observationAnalytics._sum?.promptTokens ?? 0,
+ totalCompletionTokens: observationAnalytics._sum?.completionTokens ?? 0,
+ totalTokens: observationAnalytics._sum?.totalTokens ?? 0,
+ firstObservation: observationAnalytics._min?.startTime,
+ lastObservation: observationAnalytics._max?.endTime,
+ totalObservations: observationAnalytics._count?._all,
+ lastScore: lastScore,
};
}),
});
diff --git a/src/utils/numbers.ts b/src/utils/numbers.ts
new file mode 100644
index 0000000000..7983f8a14e
--- /dev/null
+++ b/src/utils/numbers.ts
@@ -0,0 +1,3 @@
+export const numberFormatter = (number: number) => {
+ return Intl.NumberFormat("us").format(number).toString();
+};