Skip to content

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

search traces (#46)

Maximilian Deichmann6b447ebf966d
diff --git a/.env.local.example b/.env.local.example
index cb9722074d..709d09fd91 100644
--- a/.env.local.example
+++ b/.env.local.example
@@ -9,4 +9,4 @@ DATABASE_URL="postgresql://postgres:postgres@db:5432/postgres"
# openssl rand -base64 32
# https://next-auth.js.org/configuration/options#secret
NEXTAUTH_SECRET="secret"
-NEXTAUTH_URL="http://localhost:3000"
+NEXTAUTH_URL="http://localhost:3000"
\ No newline at end of file
diff --git a/.vscode/launch.json b/.vscode/launch.json
index 5fcd845247..cbb9f4a4a0 100644
--- a/.vscode/launch.json
+++ b/.vscode/launch.json
@@ -2,12 +2,27 @@
"version": "0.2.0",
"configurations": [
{
- "name": "Next.js",
+ "name": "Next.js: debug server-side",
"type": "node-terminal",
"request": "launch",
- "command": "pnpm dev",
- "cwd": "${workspaceFolder}/apps/nextjs/",
- "skipFiles": ["<node_internals>/**"]
+ "command": "npm run dev"
+ },
+ {
+ "name": "Next.js: debug client-side",
+ "type": "chrome",
+ "request": "launch",
+ "url": "http://localhost:3000"
+ },
+ {
+ "name": "Next.js: debug full stack",
+ "type": "node-terminal",
+ "request": "launch",
+ "command": "npm run dev",
+ "serverReadyAction": {
+ "pattern": "started server on .+, url: (https?://.+)",
+ "uriFormat": "%s",
+ "action": "debugWithChrome"
+ }
}
]
}
diff --git a/prisma/migrations/20230711104810_traces_add_index/migration.sql b/prisma/migrations/20230711104810_traces_add_index/migration.sql
new file mode 100644
index 0000000000..319bfb749d
--- /dev/null
+++ b/prisma/migrations/20230711104810_traces_add_index/migration.sql
@@ -0,0 +1,5 @@
+-- DropIndex
+DROP INDEX "traces_project_id_name_user_id_idx";
+
+-- CreateIndex
+CREATE INDEX "traces_project_id_name_user_id_external_id_idx" ON "traces"("project_id", "name", "user_id", "external_id");
diff --git a/prisma/migrations/20230711110517_memberships_add_userid_index/migration.sql b/prisma/migrations/20230711110517_memberships_add_userid_index/migration.sql
new file mode 100644
index 0000000000..85012e1ff9
--- /dev/null
+++ b/prisma/migrations/20230711110517_memberships_add_userid_index/migration.sql
@@ -0,0 +1,2 @@
+-- CreateIndex
+CREATE INDEX "memberships_user_id_idx" ON "memberships"("user_id");
diff --git a/prisma/migrations/20230711112235_fix_indices/migration.sql b/prisma/migrations/20230711112235_fix_indices/migration.sql
new file mode 100644
index 0000000000..db9fc83a23
--- /dev/null
+++ b/prisma/migrations/20230711112235_fix_indices/migration.sql
@@ -0,0 +1,23 @@
+-- DropIndex
+DROP INDEX "observations_trace_id_type_idx";
+
+-- DropIndex
+DROP INDEX "traces_project_id_name_user_id_external_id_idx";
+
+-- CreateIndex
+CREATE INDEX "observations_trace_id_idx" ON "observations"("trace_id");
+
+-- CreateIndex
+CREATE INDEX "observations_type_idx" ON "observations"("type");
+
+-- CreateIndex
+CREATE INDEX "traces_project_id_idx" ON "traces"("project_id");
+
+-- CreateIndex
+CREATE INDEX "traces_name_idx" ON "traces"("name");
+
+-- CreateIndex
+CREATE INDEX "traces_user_id_idx" ON "traces"("user_id");
+
+-- CreateIndex
+CREATE INDEX "traces_external_id_idx" ON "traces"("external_id");
diff --git a/prisma/schema.prisma b/prisma/schema.prisma
index ac587a84ff..cea843ba72 100644
--- a/prisma/schema.prisma
+++ b/prisma/schema.prisma
@@ -107,6 +107,7 @@ model Membership {
updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
@@id([projectId, userId])
+ @@index([userId])
@@map("memberships")
}
@@ -130,7 +131,10 @@ model Trace {
scores Score[]
@@unique([projectId, externalId])
- @@index([projectId, name, userId])
+ @@index([projectId])
+ @@index([name])
+ @@index([userId])
+ @@index([externalId])
@@map("traces")
}
@@ -159,7 +163,8 @@ model Observation {
childs Observation[] @relation("ParentChilds")
scores Score[]
- @@index([traceId, type])
+ @@index([traceId])
+ @@index([type])
@@map("observations")
}
diff --git a/src/components/table/data-table-toolbar.tsx b/src/components/table/data-table-toolbar.tsx
index 6f7f5a6c3d..f1076d364b 100644
--- a/src/components/table/data-table-toolbar.tsx
+++ b/src/components/table/data-table-toolbar.tsx
@@ -5,11 +5,19 @@ import { Button } from "@/src/components/ui/button";
import { type TableRowOptions } from "@/src/components/table/types";
import { DataTableSelectFilter } from "@/src/components/table/data-table-select-filter";
import { DataTableNumberFilter } from "@/src/components/table/data-table-number-filter";
-import React from "react";
+import React, { useState } from "react";
+import { Input } from "@/src/components/ui/input";
+
+interface SearchConfig {
+ placeholder: string;
+ updateQuery(event: string): void;
+ currentQuery?: string;
+}
interface DataTableToolbarProps<TData, TValue> {
columnDefs: ColumnDef<TData, TValue>[];
options: TableRowOptions[];
+ searchConfig?: SearchConfig;
resetFilters: () => void;
isFiltered: () => boolean;
}
@@ -17,33 +25,60 @@ interface DataTableToolbarProps<TData, TValue> {
export function DataTableToolbar<TData, TValue>({
columnDefs,
options,
+ searchConfig,
resetFilters,
isFiltered,
}: DataTableToolbarProps<TData, TValue>) {
+ const [searchString, setSearchString] = useState(
+ searchConfig?.currentQuery ?? ""
+ );
+
return (
<div className="my-2 flex items-center justify-between">
<div className="flex flex-1 items-center space-x-2">
- {columnDefs.map((column) => {
- const columnOptions = options.find(
- (o) =>
- o.columnId.toLowerCase() === column.meta?.label?.toLowerCase()
- );
- return column.enableColumnFilter && columnOptions ? (
- column.meta?.filter?.type === "select" ? (
- <DataTableSelectFilter
- title={column.meta?.label}
- meta={column.meta?.filter}
- options={columnOptions}
- />
- ) : column.meta?.filter?.type === "number-comparison" ? (
- <DataTableNumberFilter
- title={column.meta?.label}
- meta={column.meta?.filter}
- options={columnOptions}
- />
- ) : undefined
- ) : undefined;
- })}
+ {searchConfig ? (
+ <div className="flex w-full max-w-md items-center space-x-2">
+ <Input
+ autoFocus
+ placeholder={searchConfig.placeholder}
+ value={searchString}
+ className="h-8 w-[350px]"
+ onChange={(event) => {
+ setSearchString(event.currentTarget.value);
+ }}
+ />
+ <Button
+ variant="outline"
+ type="submit"
+ onClick={() => searchConfig.updateQuery(searchString)}
+ >
+ Search
+ </Button>
+ </div>
+ ) : undefined}
+ {options
+ ? columnDefs.map((column) => {
+ const columnOptions = options.find(
+ (o) =>
+ o.columnId.toLowerCase() === column.meta?.label?.toLowerCase()
+ );
+ return column.enableColumnFilter && columnOptions ? (
+ column.meta?.filter?.type === "select" ? (
+ <DataTableSelectFilter
+ title={column.meta?.label}
+ meta={column.meta?.filter}
+ options={columnOptions}
+ />
+ ) : column.meta?.filter?.type === "number-comparison" ? (
+ <DataTableNumberFilter
+ title={column.meta?.label}
+ meta={column.meta?.filter}
+ options={columnOptions}
+ />
+ ) : undefined
+ ) : undefined;
+ })
+ : undefined}
{isFiltered() && (
<Button
variant="ghost"
diff --git a/src/pages/project/[projectId]/generations.tsx b/src/pages/project/[projectId]/generations.tsx
index 8000a5a237..97fddc08a3 100644
--- a/src/pages/project/[projectId]/generations.tsx
+++ b/src/pages/project/[projectId]/generations.tsx
@@ -30,7 +30,6 @@ export default function Generations() {
const [queryOptions, setQueryOptions] = useState<GenerationFilterInput>({
traceId: null,
- id: null,
});
const generations = api.generations.all.useQuery({
@@ -47,7 +46,6 @@ export default function Generations() {
{
accessorKey: "id",
header: "ID",
- enableColumnFilter: true,
cell: ({ row }) => {
const value = row.getValue("id");
return typeof value === "string" ? (
@@ -57,16 +55,6 @@ export default function Generations() {
/>
) : undefined;
},
- meta: {
- label: "Id",
- filter: {
- type: "select",
- values: queryOptions.id,
- updateFunction: (newValues: string[] | null) => {
- setQueryOptions({ ...queryOptions, id: newValues });
- },
- },
- },
},
{
accessorKey: "traceId",
@@ -152,12 +140,10 @@ export default function Generations() {
const resetFilters = () =>
setQueryOptions({
- id: null,
traceId: null,
});
- const isFiltered = () =>
- queryOptions.traceId !== null || queryOptions.id !== null;
+ const isFiltered = () => queryOptions.traceId !== null;
return (
<div className="container">
diff --git a/src/pages/project/[projectId]/traces.tsx b/src/pages/project/[projectId]/traces.tsx
index f90e3362c7..136b5f9bcc 100644
--- a/src/pages/project/[projectId]/traces.tsx
+++ b/src/pages/project/[projectId]/traces.tsx
@@ -36,10 +36,11 @@ export type TraceFilterInput = Omit<RouterInput["traces"]["all"], "projectId">;
export default function Traces() {
const router = useRouter();
const projectId = router.query.projectId as string;
+
const [queryOptions, setQueryOptions] = useState<TraceFilterInput>({
scores: null,
name: null,
- id: null,
+ searchQuery: null,
});
const [selectedScore, setSelectedScores] = useState<SelectedScoreFilter>({
@@ -103,17 +104,6 @@ export default function Traces() {
/>
) : undefined;
},
- enableColumnFilter: true,
- meta: {
- label: "Id",
- filter: {
- type: "select",
- values: queryOptions.id,
- updateFunction: (newValues: string[] | null) => {
- setQueryOptions({ ...queryOptions, id: newValues });
- },
- },
- },
},
{
accessorKey: "externalId",
@@ -212,15 +202,13 @@ export default function Traces() {
};
const isFiltered = () =>
- queryOptions.name !== null ||
- queryOptions.id !== null ||
- queryOptions.scores !== null;
+ queryOptions.name !== null || queryOptions.scores !== null;
const resetFilters = () => {
setQueryOptions({
scores: null,
name: null,
- id: null,
+ searchQuery: null,
});
setSelectedScores({
name: null,
@@ -229,14 +217,22 @@ export default function Traces() {
});
};
+ const updateSearchQuery = (searchQuery: string) => {
+ setQueryOptions({ ...queryOptions, searchQuery });
+ };
+
return (
<div className="container">
<Header title="Traces" />
-
{tableOptions.data ? (
<DataTableToolbar
columnDefs={columns}
options={tableOptions.data}
+ searchConfig={{
+ placeholder: "Search traces (ID, External ID, Name, User ID)",
+ updateQuery: updateSearchQuery,
+ currentQuery: queryOptions.searchQuery ?? undefined,
+ }}
resetFilters={resetFilters}
isFiltered={isFiltered}
/>
diff --git a/src/server/api/routers/generations.ts b/src/server/api/routers/generations.ts
index f9b3a3a6d6..916800a3e7 100644
--- a/src/server/api/routers/generations.ts
+++ b/src/server/api/routers/generations.ts
@@ -9,7 +9,6 @@ import { type Generation } from "@/src/utils/types";
const GenerationFilterOptions = z.object({
traceId: z.array(z.string()).nullable(),
- id: z.array(z.string()).nullable(),
projectId: z.string(), // Required for protectedProjectProcedure
});
@@ -28,11 +27,6 @@ export const generationsRouter = createTRPCRouter({
traceId: { in: input.traceId },
}
: undefined),
- ...(input.id
- ? {
- id: { in: input.id },
- }
- : undefined),
},
orderBy: {
startTime: "desc",
@@ -55,43 +49,20 @@ export const generationsRouter = createTRPCRouter({
traceId: { in: input.traceId },
}
: undefined),
- ...(input.id
- ? {
- id: { in: input.id },
- }
- : undefined),
};
- const [ids, traceIds] = await Promise.all([
- ctx.prisma.observation.groupBy({
- where: {
- type: "GENERATION",
- ...filter,
- },
- by: ["id"],
- _count: {
- _all: true,
- },
- }),
- ctx.prisma.observation.groupBy({
- where: {
- type: "GENERATION",
- ...filter,
- },
- by: ["traceId"],
- _count: {
- _all: true,
- },
- }),
- ]);
+ const traceIds = await ctx.prisma.observation.groupBy({
+ where: {
+ type: "GENERATION",
+ ...filter,
+ },
+ by: ["traceId"],
+ _count: {
+ _all: true,
+ },
+ });
return [
- {
- key: "id",
- occurrences: ids.map((i) => {
- return { key: i.id, count: i._count };
- }),
- },
{
key: "traceId",
occurrences: traceIds.map((i) => {
diff --git a/src/server/api/routers/traces.ts b/src/server/api/routers/traces.ts
index ce989a7bde..9804b42e40 100644
--- a/src/server/api/routers/traces.ts
+++ b/src/server/api/routers/traces.ts
@@ -19,8 +19,8 @@ type ScoreFilter = z.infer<typeof ScoreFilter>;
const TraceFilterOptions = z.object({
projectId: z.string(), // Required for protectedProjectProcedure
name: z.array(z.string()).nullable(),
- id: z.array(z.string()).nullable(),
scores: ScoreFilter.nullable(),
+ searchQuery: z.string().nullable(),
});
export const traceRouter = createTRPCRouter({
@@ -29,24 +29,25 @@ export const traceRouter = createTRPCRouter({
.query(async ({ input, ctx }) => {
return await ctx.prisma.trace.findMany({
where: {
- projectId: input.projectId,
- ...(input.name
- ? {
- name: {
- in: input.name,
- },
- }
- : undefined),
- ...(input.id
- ? {
- id: {
- in: input.id,
- },
- }
- : undefined),
- ...(input.scores
- ? { scores: { some: createScoreCondition(input.scores) } }
- : undefined),
+ AND: [
+ {
+ projectId: input.projectId,
+ ...(input.name ? { name: { in: input.name } } : undefined),
+ ...(input.scores
+ ? { scores: { some: createScoreCondition(input.scores) } }
+ : undefined),
+ },
+ input.searchQuery
+ ? {
+ OR: [
+ { id: { contains: input.searchQuery } },
+ { externalId: { contains: input.searchQuery } },
+ { userId: { contains: input.searchQuery } },
+ { name: { contains: input.searchQuery } },
+ ],
+ }
+ : {},
+ ],
},
orderBy: {
timestamp: "desc",
@@ -61,39 +62,37 @@ export const traceRouter = createTRPCRouter({
.input(TraceFilterOptions)
.query(async ({ input, ctx }) => {
const filter = {
- projectId: input.projectId,
- ...(input.name
- ? {
- name: {
- in: input.name,
- },
- }
- : undefined),
- ...(input.id
- ? {
- id: {
- in: input.id,
- },
- }
- : undefined),
- ...(input.scores
- ? {
- scores: {
- some: createScoreCondition(input.scores),
- },
- }
- : undefined),
+ AND: [
+ {
+ projectId: input.projectId,
+ ...(input.name ? { name: { in: input.name } } : undefined),
+ ...(input.scores
+ ? { scores: { some: createScoreCondition(input.scores) } }
+ : undefined),
+ },
+ input.searchQuery
+ ? {
+ OR: [
+ { id: { contains: input.searchQuery } },
+ { externalId: { contains: input.searchQuery } },
+ { userId: { contains: input.searchQuery } },
+ { name: { contains: input.searchQuery } },
+ ],
+ }
+ : {},
+ ],
};
- const [ids, names] = await Promise.all([
- ctx.prisma.trace.groupBy({
- where: filter,
- by: ["id"],
+ const [scores, names] = await Promise.all([
+ ctx.prisma.score.groupBy({
+ where: {
+ trace: filter,
+ },
+ by: ["name", "traceId"],
_count: {
_all: true,
},
}),
-
ctx.prisma.trace.groupBy({
where: filter,
by: ["name"],
@@ -103,16 +102,6 @@ export const traceRouter = createTRPCRouter({
}),
]);
- const scores = await ctx.prisma.score.groupBy({
- where: {
- trace: filter,
- },
- by: ["name", "traceId"],
- _count: {
- _all: true,
- },
- });
-
let groupedCounts: Map<string, number> = new Map();
for (const item of scores) {
@@ -126,12 +115,6 @@ export const traceRouter = createTRPCRouter({
}
return [
- {
- key: "id",
- occurrences: ids.map((i) => {
- return { key: i.id, count: i._count };
- }),
- },
{
key: "name",
occurrences: names.map((i) => {