Skip to content

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

Paginate generations (#230)

Marc Klingen025c871c7bcd
diff --git a/src/components/table/data-table-pagination.tsx b/src/components/table/data-table-pagination.tsx
index 431633cf45..95f8e5c228 100644
--- a/src/components/table/data-table-pagination.tsx
+++ b/src/components/table/data-table-pagination.tsx
@@ -23,14 +23,14 @@ export function DataTablePagination<TData>({
table,
}: DataTablePaginationProps<TData>) {
return (
- <div className="mt-3 flex items-center justify-between px-2">
+ <div className="mt-3 flex items-center justify-between overflow-x-auto px-2">
<div className="flex-1 text-sm text-muted-foreground">
{/* {table.getFilteredSelectedRowModel().rows.length} of{" "}
{table.getFilteredRowModel().rows.length} row(s) selected. */}
</div>
<div className="flex items-center space-x-6 lg:space-x-8">
<div className="flex items-center space-x-2">
- <p className="text-sm font-medium">Rows per page</p>
+ <p className="whitespace-nowrap text-sm font-medium">Rows per page</p>
<Select
value={`${table.getState().pagination.pageSize}`}
onValueChange={(value) => {
@@ -49,7 +49,7 @@ export function DataTablePagination<TData>({
</SelectContent>
</Select>
</div>
- <div className="flex w-[100px] items-center justify-center text-sm font-medium">
+ <div className="flex w-[100px] items-center justify-center whitespace-nowrap text-sm font-medium">
Page {table.getState().pagination.pageIndex + 1} of{" "}
{table.getPageCount()}
</div>
diff --git a/src/components/table/use-cases/traces.tsx b/src/components/table/use-cases/traces.tsx
index b84a4ead36..44be3279fc 100644
--- a/src/components/table/use-cases/traces.tsx
+++ b/src/components/table/use-cases/traces.tsx
@@ -81,8 +81,7 @@ export default function TracesTable({
const traces = api.traces.all.useQuery({
...queryOptions,
- pageIndex: paginationState.pageIndex,
- pageSize: paginationState.pageSize,
+ ...paginationState,
projectId,
});
const totalCount = traces.data?.slice(1)[0]?.totalCount ?? 0;
@@ -314,7 +313,7 @@ export default function TracesTable({
};
const isFiltered = () =>
- queryOptions.name !== null || queryOptions.scores !== null;
+ Object.entries(queryOptions).filter(([_k, v]) => v !== null).length > 0;
const resetFilters = () => {
setQueryOptions({
diff --git a/src/pages/project/[projectId]/generations.tsx b/src/pages/project/[projectId]/generations.tsx
index ed4a92542f..13def23124 100644
--- a/src/pages/project/[projectId]/generations.tsx
+++ b/src/pages/project/[projectId]/generations.tsx
@@ -19,6 +19,7 @@ import { Button } from "@/src/components/ui/button";
import { ChevronDownIcon, Loader } from "lucide-react";
import { type ExportFileFormats } from "@/src/server/api/routers/generations";
import { usePostHog } from "posthog-js/react";
+import { NumberParam, useQueryParams, withDefault } from "use-query-params";
type GenerationTableRow = {
id: string;
@@ -27,6 +28,7 @@ type GenerationTableRow = {
endTime?: string;
name?: string;
model?: string;
+ traceName?: string;
usage: {
promptTokens: number;
completionTokens: number;
@@ -66,12 +68,20 @@ export default function Generations() {
traceId: null,
name: null,
model: null,
+ traceName: null,
+ });
+
+ const [paginationState, setPaginationState] = useQueryParams({
+ pageIndex: withDefault(NumberParam, 0),
+ pageSize: withDefault(NumberParam, 50),
});
const generations = api.generations.all.useQuery({
...queryOptions,
+ ...paginationState,
projectId,
});
+ const totalCount = generations.data?.slice(1)[0]?.totalCount ?? 0;
const generationOptions = api.generations.availableFilterOptions.useQuery({
...queryOptions,
@@ -131,6 +141,21 @@ export default function Generations() {
) : null;
},
},
+ {
+ accessorKey: "name",
+ enableColumnFilter: true,
+ header: "name",
+ meta: {
+ label: "Name",
+ filter: {
+ type: "select",
+ values: queryOptions.name,
+ updateFunction: (newValues: string[] | null) => {
+ setQueryOptions({ ...queryOptions, name: newValues });
+ },
+ },
+ },
+ },
{
accessorKey: "traceId",
enableColumnFilter: true,
@@ -156,16 +181,16 @@ export default function Generations() {
},
},
{
- accessorKey: "name",
+ accessorKey: "traceName",
enableColumnFilter: true,
- header: "name",
+ header: "Trace Name",
meta: {
- label: "Name",
+ label: "TraceName",
filter: {
type: "select",
- values: queryOptions.name,
+ values: queryOptions.traceName,
updateFunction: (newValues: string[] | null) => {
- setQueryOptions({ ...queryOptions, name: newValues });
+ setQueryOptions({ ...queryOptions, traceName: newValues });
},
},
},
@@ -221,7 +246,7 @@ export default function Generations() {
return {
columnId: o.key,
options: o.occurrences.map((o) => {
- return { label: o.key, value: o.count._all };
+ return { label: o.key, value: o.count };
}),
};
});
@@ -245,6 +270,7 @@ export default function Generations() {
? generations.data.map((generation) => ({
id: generation.id,
traceId: generation.traceId,
+ traceName: generation.traceName,
startTime: generation.startTime.toLocaleString(),
endTime: generation.endTime?.toLocaleString() ?? undefined,
name: generation.name ?? undefined,
@@ -262,6 +288,7 @@ export default function Generations() {
traceId: null,
name: null,
model: null,
+ traceName: null,
});
const isFiltered = () =>
@@ -325,6 +352,11 @@ export default function Generations() {
}
}
options={{ isLoading: true, isError: false }}
+ pagination={{
+ pageCount: Math.ceil(totalCount / paginationState.pageSize),
+ onChange: setPaginationState,
+ state: paginationState,
+ }}
/>
</div>
);
diff --git a/src/server/api/routers/generations.ts b/src/server/api/routers/generations.ts
index cd0976ae97..bb1ef212e1 100644
--- a/src/server/api/routers/generations.ts
+++ b/src/server/api/routers/generations.ts
@@ -6,6 +6,7 @@ import {
protectedProjectProcedure,
} from "@/src/server/api/trpc";
import { type Generation } from "@/src/utils/types";
+import { type Observation, Prisma } from "@prisma/client";
const exportFileFormats = ["CSV", "JSON", "OPENAI-JSONL"] as const;
export type ExportFileFormats = (typeof exportFileFormats)[number];
@@ -15,59 +16,96 @@ const GenerationFilterOptions = z.object({
projectId: z.string(), // Required for protectedProjectProcedure
name: z.array(z.string()).nullable(),
model: z.array(z.string()).nullable(),
+ traceName: z.array(z.string()).nullable(),
+});
+
+const generationsFilterPrismaCondition = (
+ filter: z.infer<typeof GenerationFilterOptions>,
+) => {
+ const traceIdCondition =
+ filter.traceId !== null
+ ? Prisma.sql`AND o.trace_id IN (${Prisma.join(filter.traceId)})`
+ : Prisma.empty;
+
+ const nameCondition =
+ filter.name !== null
+ ? Prisma.sql`AND o.name IN (${Prisma.join(filter.name)})`
+ : Prisma.empty;
+
+ const modelCondition =
+ filter.model !== null
+ ? Prisma.sql`AND o.model IN (${Prisma.join(filter.model)})`
+ : Prisma.empty;
+
+ const traceNameCondition =
+ filter.traceName !== null
+ ? Prisma.sql`AND t.name IN (${Prisma.join(filter.traceName)})`
+ : Prisma.empty;
+
+ return Prisma.join(
+ [traceIdCondition, nameCondition, modelCondition, traceNameCondition],
+ " ",
+ );
+};
+
+const ListInputs = GenerationFilterOptions.extend({
+ pageIndex: z.number().int().gte(0).nullable().default(0),
+ pageSize: z.number().int().gte(0).lte(100).nullable().default(50),
});
// extend generationfilteroptions with export options
-const ExportOptions = GenerationFilterOptions.extend({
+const ExportInputs = GenerationFilterOptions.extend({
fileFormat: z.enum(exportFileFormats),
});
export const generationsRouter = createTRPCRouter({
all: protectedProjectProcedure
- .input(GenerationFilterOptions)
+ .input(ListInputs)
.query(async ({ input, ctx }) => {
- const generations = (await ctx.prisma.observation.findMany({
- where: {
- type: "GENERATION",
- projectId: input.projectId,
- ...(input.name
- ? {
- name: {
- in: input.name,
- },
- }
- : undefined),
- ...(input.model
- ? {
- model: {
- in: input.model,
- },
- }
- : undefined),
- traceId: {
- not: null,
- ...(input.traceId
- ? {
- in: input.traceId,
- }
- : undefined),
- },
- },
- orderBy: {
- startTime: "desc",
- },
- take: 100,
- })) as Array<
- Generation & {
- traceId: string;
- }
- >;
+ const generations = await ctx.prisma.$queryRaw<
+ Array<
+ Observation & {
+ traceId: string;
+ traceName: string;
+ totalCount: number;
+ }
+ >
+ >(
+ Prisma.sql`
+ SELECT
+ o.id,
+ o.name,
+ o.model,
+ o.start_time as "startTime",
+ o.end_time as "endTime",
+ o.input,
+ o.output,
+ o.metadata,
+ o.trace_id as "traceId",
+ t.name as "traceName",
+ o.completion_start_time as "completionStartTime",
+ o.prompt_tokens as "promptTokens",
+ o.completion_tokens as "completionTokens",
+ o.total_tokens as "totalTokens",
+ o.version,
+ (count(*) OVER())::int AS "totalCount"
+ FROM observations o
+ JOIN traces t ON t.id = o.trace_id
+ WHERE o.type = 'GENERATION'
+ AND o.project_id = ${input.projectId}
+ AND t.project_id = ${input.projectId}
+ ${generationsFilterPrismaCondition(input)}
+ ORDER BY o.start_time DESC
+ LIMIT ${input.pageSize ?? 50}
+ OFFSET ${(input.pageIndex ?? 0) * (input.pageSize ?? 50)}
+ `,
+ );
return generations;
}),
export: protectedProjectProcedure
- .input(ExportOptions)
+ .input(ExportInputs)
.query(async ({ input, ctx }) => {
const generations = (await ctx.prisma.observation.findMany({
where: {
@@ -183,61 +221,76 @@ export const generationsRouter = createTRPCRouter({
availableFilterOptions: protectedProjectProcedure
.input(GenerationFilterOptions)
.query(async ({ input, ctx }) => {
- const filter = {
- projectId: input.projectId,
- ...(input.name
- ? {
- name: {
- in: input.name,
- },
- }
- : undefined),
- ...(input.model
- ? {
- model: {
- in: input.model,
- },
- }
- : undefined),
- ...(input.traceId
- ? {
- traceId: { in: input.traceId },
- }
- : undefined),
- };
-
- const traceIds = await ctx.prisma.observation.groupBy({
- where: {
- type: "GENERATION",
- ...filter,
- },
- by: ["traceId"],
- _count: {
- _all: true,
- },
- });
-
- const names = await ctx.prisma.observation.groupBy({
- where: {
- type: "GENERATION",
- ...filter,
- },
- by: ["name"],
- _count: {
- _all: true,
- },
- });
-
- const models = await ctx.prisma.observation.groupBy({
- where: {
- type: "GENERATION",
- ...filter,
- },
- by: ["model"],
- _count: {
- _all: true,
- },
- });
+ const [traceIds, names, models, traceNames] = await Promise.all([
+ ctx.prisma.$queryRaw<
+ Array<{
+ traceId: string | null;
+ count: number;
+ }>
+ >(Prisma.sql`
+ SELECT
+ t.id as "traceId",
+ count(*)::int AS count
+ FROM traces t
+ JOIN observations o ON o.trace_id = t.id
+ WHERE o.type = 'GENERATION'
+ AND o.project_id = ${input.projectId}
+ AND t.project_id = ${input.projectId}
+ ${generationsFilterPrismaCondition(input)}
+ GROUP BY 1
+ `),
+ ctx.prisma.$queryRaw<
+ Array<{
+ name: string | null;
+ count: number;
+ }>
+ >(Prisma.sql`
+ SELECT
+ o.name,
+ count(*)::int AS count
+ FROM traces t
+ JOIN observations o ON o.trace_id = t.id
+ WHERE o.type = 'GENERATION'
+ AND o.project_id = ${input.projectId}
+ AND t.project_id = ${input.projectId}
+ ${generationsFilterPrismaCondition(input)}
+ GROUP BY 1
+ `),
+ ctx.prisma.$queryRaw<
+ Array<{
+ model: string | null;
+ count: number;
+ }>
+ >(Prisma.sql`
+ SELECT
+ o.model,
+ count(*)::int AS count
+ FROM traces t
+ JOIN observations o ON o.trace_id = t.id
+ WHERE o.type = 'GENERATION'
+ AND o.project_id = ${input.projectId}
+ AND t.project_id = ${input.projectId}
+ ${generationsFilterPrismaCondition(input)}
+ GROUP BY 1
+ `),
+ ctx.prisma.$queryRaw<
+ Array<{
+ name: string | null;
+ count: number;
+ }>
+ >(Prisma.sql`
+ SELECT
+ t.name,
+ count(*)::int AS count
+ FROM traces t
+ JOIN observations o ON o.trace_id = t.id
+ WHERE o.type = 'GENERATION'
+ AND o.project_id = ${input.projectId}
+ AND t.project_id = ${input.projectId}
+ ${generationsFilterPrismaCondition(input)}
+ GROUP BY 1
+ `),
+ ]);
return [
{
@@ -245,7 +298,7 @@ export const generationsRouter = createTRPCRouter({
occurrences: traceIds
.filter((i) => i.traceId !== null)
.map((i) => {
- return { key: i.traceId ?? "null", count: i._count };
+ return { key: i.traceId ?? "null", count: i.count };
}),
},
{
@@ -253,7 +306,7 @@ export const generationsRouter = createTRPCRouter({
occurrences: names
.filter((i) => i.name !== null)
.map((i) => {
- return { key: i.name ?? "null", count: i._count };
+ return { key: i.name ?? "null", count: i.count };
}),
},
{
@@ -261,7 +314,15 @@ export const generationsRouter = createTRPCRouter({
occurrences: models
.filter((i) => i.model !== null)
.map((i) => {
- return { key: i.model ?? "null", count: i._count };
+ return { key: i.model ?? "null", count: i.count };
+ }),
+ },
+ {
+ key: "traceName",
+ occurrences: traceNames
+ .filter((i) => i.name !== null)
+ .map((i) => {
+ return { key: i.name ?? "null", count: i.count };
}),
},
];