Skip to content

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

feat(ui): bookmark traces (#579)

Simon Gneuß93c080813ef0
diff --git a/.gitignore b/.gitignore
index d8ea54f45a..edc5fc7498 100644
--- a/.gitignore
+++ b/.gitignore
@@ -20,6 +20,9 @@ next-env.d.ts
# production
/build
+# idea
+.idea
+
# misc
.DS_Store
*.pem
diff --git a/prisma/migrations/20231119171940_bookmarked/migration.sql b/prisma/migrations/20231119171940_bookmarked/migration.sql
new file mode 100644
index 0000000000..841dc192fc
--- /dev/null
+++ b/prisma/migrations/20231119171940_bookmarked/migration.sql
@@ -0,0 +1,3 @@
+
+-- AlterTable
+ALTER TABLE "traces" ADD COLUMN "bookmarked" BOOLEAN NOT NULL DEFAULT false;
diff --git a/prisma/schema.prisma b/prisma/schema.prisma
index 75c83e982b..2196598da9 100644
--- a/prisma/schema.prisma
+++ b/prisma/schema.prisma
@@ -2,340 +2,341 @@
// learn more about it in the docs: https://pris.ly/d/prisma-schema
generator client {
- provider = "prisma-client-js"
- previewFeatures = ["tracing"]
+ provider = "prisma-client-js"
+ previewFeatures = ["tracing"]
}
datasource db {
- provider = "postgresql"
- url = env("DATABASE_URL")
- directUrl = env("DIRECT_URL")
+ provider = "postgresql"
+ url = env("DATABASE_URL")
+ directUrl = env("DIRECT_URL")
}
model Example {
- id String @id @default(cuid())
- createdAt DateTime @default(now()) @map("created_at")
- updatedAt DateTime @updatedAt @map("updated_at")
+ id String @id @default(cuid())
+ createdAt DateTime @default(now()) @map("created_at")
+ updatedAt DateTime @updatedAt @map("updated_at")
}
// Necessary for Next auth
model Account {
- id String @id @default(cuid())
- userId String @map("user_id")
- type String
- provider String
- providerAccountId String
- refresh_token String? // @db.Text
- access_token String? // @db.Text
- expires_at Int?
- token_type String?
- scope String?
- id_token String? // @db.Text
- session_state String?
- user User @relation(fields: [userId], references: [id], onDelete: Cascade)
-
- @@unique([provider, providerAccountId])
- @@index([userId])
+ id String @id @default(cuid())
+ userId String @map("user_id")
+ type String
+ provider String
+ providerAccountId String
+ refresh_token String? // @db.Text
+ access_token String? // @db.Text
+ expires_at Int?
+ token_type String?
+ scope String?
+ id_token String? // @db.Text
+ session_state String?
+ user User @relation(fields: [userId], references: [id], onDelete: Cascade)
+
+ @@unique([provider, providerAccountId])
+ @@index([userId])
}
model Session {
- id String @id @default(cuid())
- sessionToken String @unique @map("session_token")
- userId String @map("user_id")
- expires DateTime
- user User @relation(fields: [userId], references: [id], onDelete: Cascade)
+ id String @id @default(cuid())
+ sessionToken String @unique @map("session_token")
+ userId String @map("user_id")
+ expires DateTime
+ user User @relation(fields: [userId], references: [id], onDelete: Cascade)
}
model User {
- id String @id @default(cuid())
- name String?
- email String? @unique
- emailVerified DateTime? @map("email_verified")
- password String?
- image String?
- admin Boolean @default(false)
- accounts Account[]
- sessions Session[]
- memberships Membership[]
- createdAt DateTime @default(now()) @map("created_at")
- updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
- featureFlags String[] @default([]) @map("feature_flags")
-
- @@map("users")
+ id String @id @default(cuid())
+ name String?
+ email String? @unique
+ emailVerified DateTime? @map("email_verified")
+ password String?
+ image String?
+ admin Boolean @default(false)
+ accounts Account[]
+ sessions Session[]
+ memberships Membership[]
+ createdAt DateTime @default(now()) @map("created_at")
+ updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
+ featureFlags String[] @default([]) @map("feature_flags")
+
+ @@map("users")
}
model VerificationToken {
- identifier String
- token String @unique
- expires DateTime
+ identifier String
+ token String @unique
+ expires DateTime
- @@unique([identifier, token])
- @@map("verification_tokens")
+ @@unique([identifier, token])
+ @@map("verification_tokens")
}
model Project {
- id String @id @default(cuid())
- createdAt DateTime @default(now()) @map("created_at")
- updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
- name String
- members Membership[]
- traces Trace[]
- observations Observation[]
- apiKeys ApiKey[]
- dataset Dataset[]
- RawEvents Events[]
-
- @@map("projects")
+ id String @id @default(cuid())
+ createdAt DateTime @default(now()) @map("created_at")
+ updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
+ name String
+ members Membership[]
+ traces Trace[]
+ observations Observation[]
+ apiKeys ApiKey[]
+ dataset Dataset[]
+ RawEvents Events[]
+
+ @@map("projects")
}
model ApiKey {
- id String @id @unique @default(cuid())
- createdAt DateTime @default(now()) @map("created_at")
- note String?
- publicKey String @unique @map("public_key")
- hashedSecretKey String @unique @map("hashed_secret_key")
- fastHashedSecretKey String? @unique @map("fast_hashed_secret_key")
- displaySecretKey String @map("display_secret_key")
- lastUsedAt DateTime? @map("last_used_at")
- expiresAt DateTime? @map("expires_at")
- projectId String @map("project_id")
- project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
-
- @@index(projectId)
- @@index(publicKey)
- @@index(hashedSecretKey)
- @@index(fastHashedSecretKey)
- @@map("api_keys")
+ id String @id @unique @default(cuid())
+ createdAt DateTime @default(now()) @map("created_at")
+ note String?
+ publicKey String @unique @map("public_key")
+ hashedSecretKey String @unique @map("hashed_secret_key")
+ fastHashedSecretKey String? @unique @map("fast_hashed_secret_key")
+ displaySecretKey String @map("display_secret_key")
+ lastUsedAt DateTime? @map("last_used_at")
+ expiresAt DateTime? @map("expires_at")
+ projectId String @map("project_id")
+ project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
+
+ @@index(projectId)
+ @@index(publicKey)
+ @@index(hashedSecretKey)
+ @@index(fastHashedSecretKey)
+ @@map("api_keys")
}
model Membership {
- projectId String @map("project_id")
- project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
- userId String @map("user_id")
- user User @relation(fields: [userId], references: [id], onDelete: Cascade)
- role MembershipRole
- createdAt DateTime @default(now()) @map("created_at")
- updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
-
- @@id([projectId, userId])
- @@index([userId])
- @@map("memberships")
+ projectId String @map("project_id")
+ project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
+ userId String @map("user_id")
+ user User @relation(fields: [userId], references: [id], onDelete: Cascade)
+ role MembershipRole
+ createdAt DateTime @default(now()) @map("created_at")
+ updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
+
+ @@id([projectId, userId])
+ @@index([userId])
+ @@map("memberships")
}
enum MembershipRole {
- OWNER
- ADMIN
- MEMBER
- VIEWER
+ OWNER
+ ADMIN
+ MEMBER
+ VIEWER
}
model Trace {
- id String @id @default(cuid())
- externalId String? @map("external_id")
- timestamp DateTime @default(now())
- name String?
- userId String? @map("user_id")
- metadata Json?
- release String?
- version String?
- projectId String @map("project_id")
- project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
- public Boolean @default(false)
-
- scores Score[]
-
- @@unique([projectId, externalId])
- @@index([projectId])
- @@index([name])
- @@index([userId])
- @@index([externalId])
- @@index(timestamp)
- @@index(release)
- @@map("traces")
+ id String @id @default(cuid())
+ externalId String? @map("external_id")
+ timestamp DateTime @default(now())
+ name String?
+ userId String? @map("user_id")
+ metadata Json?
+ release String?
+ version String?
+ projectId String @map("project_id")
+ project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
+ public Boolean @default(false)
+ bookmarked Boolean @default(false)
+
+ scores Score[]
+
+ @@unique([projectId, externalId])
+ @@index([projectId])
+ @@index([name])
+ @@index([userId])
+ @@index([externalId])
+ @@index(timestamp)
+ @@index(release)
+ @@map("traces")
}
model Observation {
- id String @id @default(cuid())
- traceId String? @map("trace_id")
- projectId String @map("project_id")
- type ObservationType
- startTime DateTime @default(now()) @map("start_time")
- endTime DateTime? @map("end_time")
- name String?
- metadata Json?
- parentObservationId String? @map("parent_observation_id")
- level ObservationLevel @default(DEFAULT)
- statusMessage String? @map("status_message")
- version String?
- createdAt DateTime @default(now()) @map("created_at")
-
- // GENERATION ONLY
- model String?
- modelParameters Json?
- input Json?
- output Json?
- promptTokens Int @default(0) @map("prompt_tokens")
- completionTokens Int @default(0) @map("completion_tokens")
- totalTokens Int @default(0) @map("total_tokens")
- completionStartTime DateTime? @map("completion_start_time")
- scores Score[]
- project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
- derivedDatasetItems DatasetItem[]
- datasetRunItems DatasetRunItems[]
-
- @@unique([id, projectId])
- @@index([traceId])
- @@index([type])
- @@index(startTime)
- @@index(createdAt)
- @@index(projectId)
- @@index(parentObservationId)
- @@map("observations")
+ id String @id @default(cuid())
+ traceId String? @map("trace_id")
+ projectId String @map("project_id")
+ type ObservationType
+ startTime DateTime @default(now()) @map("start_time")
+ endTime DateTime? @map("end_time")
+ name String?
+ metadata Json?
+ parentObservationId String? @map("parent_observation_id")
+ level ObservationLevel @default(DEFAULT)
+ statusMessage String? @map("status_message")
+ version String?
+ createdAt DateTime @default(now()) @map("created_at")
+
+ // GENERATION ONLY
+ model String?
+ modelParameters Json?
+ input Json?
+ output Json?
+ promptTokens Int @default(0) @map("prompt_tokens")
+ completionTokens Int @default(0) @map("completion_tokens")
+ totalTokens Int @default(0) @map("total_tokens")
+ completionStartTime DateTime? @map("completion_start_time")
+ scores Score[]
+ project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
+ derivedDatasetItems DatasetItem[]
+ datasetRunItems DatasetRunItems[]
+
+ @@unique([id, projectId])
+ @@index([traceId])
+ @@index([type])
+ @@index(startTime)
+ @@index(createdAt)
+ @@index(projectId)
+ @@index(parentObservationId)
+ @@map("observations")
}
enum ObservationType {
- SPAN
- EVENT
- GENERATION
+ SPAN
+ EVENT
+ GENERATION
}
enum ObservationLevel {
- DEBUG
- DEFAULT
- WARNING
- ERROR
+ DEBUG
+ DEFAULT
+ WARNING
+ ERROR
}
model Score {
- id String @id @default(cuid())
- timestamp DateTime @default(now())
- name String
- value Float
- comment String?
- traceId String @map("trace_id")
- trace Trace @relation(fields: [traceId], references: [id], onDelete: Cascade)
- observationId String? @map("observation_id")
- observation Observation? @relation(fields: [observationId], references: [id], onDelete: SetNull)
-
- @@unique([id, traceId]) // used for upsert
- @@index([value])
- @@index([traceId], type: Hash)
- @@index([observationId], type: Hash)
- @@map("scores")
+ id String @id @default(cuid())
+ timestamp DateTime @default(now())
+ name String
+ value Float
+ comment String?
+ traceId String @map("trace_id")
+ trace Trace @relation(fields: [traceId], references: [id], onDelete: Cascade)
+ observationId String? @map("observation_id")
+ observation Observation? @relation(fields: [observationId], references: [id], onDelete: SetNull)
+
+ @@unique([id, traceId]) // used for upsert
+ @@index([value])
+ @@index([traceId], type: Hash)
+ @@index([observationId], type: Hash)
+ @@map("scores")
}
enum PricingUnit {
- PER_1000_TOKENS
- PER_1000_CHARS
+ PER_1000_TOKENS
+ PER_1000_CHARS
}
enum TokenType {
- PROMPT
- COMPLETION
- TOTAL
+ PROMPT
+ COMPLETION
+ TOTAL
}
model Pricing {
- id String @id @default(cuid())
- modelName String @map("model_name")
- pricingUnit PricingUnit @default(PER_1000_TOKENS) @map("pricing_unit")
- price Decimal
- currency String @default("USD")
- tokenType TokenType @map("token_type")
-
- @@map("pricings")
+ id String @id @default(cuid())
+ modelName String @map("model_name")
+ pricingUnit PricingUnit @default(PER_1000_TOKENS) @map("pricing_unit")
+ price Decimal
+ currency String @default("USD")
+ tokenType TokenType @map("token_type")
+
+ @@map("pricings")
}
model CronJobs {
- name String @id
- lastRun DateTime? @map("last_run")
- jobStartedAt DateTime? @map("job_started_at")
- state String?
+ name String @id
+ lastRun DateTime? @map("last_run")
+ jobStartedAt DateTime? @map("job_started_at")
+ state String?
- @@map("cron_jobs")
+ @@map("cron_jobs")
}
model Dataset {
- id String @id @default(cuid())
- name String
- status DatasetStatus @default(ACTIVE)
- projectId String @map("project_id")
- project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
- createdAt DateTime @default(now()) @map("created_at")
- updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
- datasetItems DatasetItem[]
- datasetRuns DatasetRuns[]
-
- @@unique([projectId, name])
- @@index([projectId], type: Hash)
- @@map("datasets")
+ id String @id @default(cuid())
+ name String
+ status DatasetStatus @default(ACTIVE)
+ projectId String @map("project_id")
+ project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
+ createdAt DateTime @default(now()) @map("created_at")
+ updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
+ datasetItems DatasetItem[]
+ datasetRuns DatasetRuns[]
+
+ @@unique([projectId, name])
+ @@index([projectId], type: Hash)
+ @@map("datasets")
}
model DatasetItem {
- id String @id @default(cuid())
- status DatasetStatus @default(ACTIVE)
- input Json
- expectedOutput Json? @map("expected_output")
- sourceObservationId String? @map("source_observation_id")
- sourceObservation Observation? @relation(fields: [sourceObservationId], references: [id], onDelete: SetNull)
- datasetId String @map("dataset_id")
- dataset Dataset @relation(fields: [datasetId], references: [id], onDelete: Cascade)
- createdAt DateTime @default(now()) @map("created_at")
- updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
- datasetRunItems DatasetRunItems[]
-
- @@index([sourceObservationId], type: Hash)
- @@index([datasetId], type: Hash)
- @@map("dataset_items")
+ id String @id @default(cuid())
+ status DatasetStatus @default(ACTIVE)
+ input Json
+ expectedOutput Json? @map("expected_output")
+ sourceObservationId String? @map("source_observation_id")
+ sourceObservation Observation? @relation(fields: [sourceObservationId], references: [id], onDelete: SetNull)
+ datasetId String @map("dataset_id")
+ dataset Dataset @relation(fields: [datasetId], references: [id], onDelete: Cascade)
+ createdAt DateTime @default(now()) @map("created_at")
+ updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
+ datasetRunItems DatasetRunItems[]
+
+ @@index([sourceObservationId], type: Hash)
+ @@index([datasetId], type: Hash)
+ @@map("dataset_items")
}
enum DatasetStatus {
- ACTIVE
- ARCHIVED
+ ACTIVE
+ ARCHIVED
}
model DatasetRuns {
- id String @id @default(cuid())
- name String
- datasetId String @map("dataset_id")
- dataset Dataset @relation(fields: [datasetId], references: [id], onDelete: Cascade)
- createdAt DateTime @default(now()) @map("created_at")
- updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
- datasetRunItems DatasetRunItems[]
-
- @@unique([datasetId, name])
- @@index([datasetId], type: Hash)
- @@map("dataset_runs")
+ id String @id @default(cuid())
+ name String
+ datasetId String @map("dataset_id")
+ dataset Dataset @relation(fields: [datasetId], references: [id], onDelete: Cascade)
+ createdAt DateTime @default(now()) @map("created_at")
+ updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
+ datasetRunItems DatasetRunItems[]
+
+ @@unique([datasetId, name])
+ @@index([datasetId], type: Hash)
+ @@map("dataset_runs")
}
model DatasetRunItems {
- id String @id @default(cuid())
- datasetRunId String @map("dataset_run_id")
- datasetRun DatasetRuns @relation(fields: [datasetRunId], references: [id], onDelete: Cascade)
- datasetItemId String @map("dataset_item_id")
- datasetItem DatasetItem @relation(fields: [datasetItemId], references: [id], onDelete: Cascade)
- observationId String @map("observation_id")
- observation Observation @relation(fields: [observationId], references: [id], onDelete: Cascade)
- createdAt DateTime @default(now()) @map("created_at")
- updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
-
- @@index([datasetRunId], type: Hash)
- @@index([datasetItemId], type: Hash)
- @@index([observationId], type: Hash)
- @@map("dataset_run_items")
+ id String @id @default(cuid())
+ datasetRunId String @map("dataset_run_id")
+ datasetRun DatasetRuns @relation(fields: [datasetRunId], references: [id], onDelete: Cascade)
+ datasetItemId String @map("dataset_item_id")
+ datasetItem DatasetItem @relation(fields: [datasetItemId], references: [id], onDelete: Cascade)
+ observationId String @map("observation_id")
+ observation Observation @relation(fields: [observationId], references: [id], onDelete: Cascade)
+ createdAt DateTime @default(now()) @map("created_at")
+ updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
+
+ @@index([datasetRunId], type: Hash)
+ @@index([datasetItemId], type: Hash)
+ @@index([observationId], type: Hash)
+ @@map("dataset_run_items")
}
model Events {
- id String @id @default(cuid())
- createdAt DateTime @default(now()) @map("created_at")
- updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
- projectId String @map("project_id")
- project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
- data Json
- headers Json @default("{}")
- url String?
- method String?
-
- @@index(projectId)
- @@map("events")
+ id String @id @default(cuid())
+ createdAt DateTime @default(now()) @map("created_at")
+ updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
+ projectId String @map("project_id")
+ project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
+ data Json
+ headers Json @default("{}")
+ url String?
+ method String?
+
+ @@index(projectId)
+ @@map("events")
}
diff --git a/src/components/bookmark-trace.tsx b/src/components/bookmark-trace.tsx
new file mode 100644
index 0000000000..11baee4979
--- /dev/null
+++ b/src/components/bookmark-trace.tsx
@@ -0,0 +1,50 @@
+import { StarIcon } from "lucide-react";
+
+import { Button } from "@/src/components/ui/button";
+import { api } from "@/src/utils/api";
+import { useHasAccess } from "@/src/features/rbac/utils/checkAccess";
+
+export function BookmarkTrace({
+ traceId,
+ projectId,
+ isBookmarked,
+ size = "sm",
+}: {
+ traceId: string;
+ projectId: string;
+ isBookmarked: boolean;
+ size?: "sm" | "xs";
+}) {
+ const utils = api.useUtils();
+ const hasAccess = useHasAccess({ projectId, scope: "traces:bookmark" });
+ const mutBookmarkTrace = api.traces.bookmark.useMutation({
+ onSuccess: () => {
+ void utils.traces.invalidate();
+ },
+ });
+
+ const handleBookmarkClick = () => {
+ if (!hasAccess) return;
+ void mutBookmarkTrace.mutateAsync({
+ traceId,
+ projectId,
+ bookmarked: !isBookmarked,
+ });
+ };
+
+ return (
+ <Button
+ variant="ghost"
+ size={size}
+ onClick={handleBookmarkClick}
+ disabled={!hasAccess}
+ loading={mutBookmarkTrace.isLoading}
+ >
+ <StarIcon
+ className={`h-4 w-4 ${
+ isBookmarked ? "fill-current text-yellow-500" : "text-gray-500"
+ }`}
+ />
+ </Button>
+ );
+}
diff --git a/src/components/table/use-cases/traces.tsx b/src/components/table/use-cases/traces.tsx
index ed2a021e51..5dfa726755 100644
--- a/src/components/table/use-cases/traces.tsx
+++ b/src/components/table/use-cases/traces.tsx
@@ -21,8 +21,10 @@ import {
useQueryParams,
withDefault,
} from "use-query-params";
+import { BookmarkTrace } from "@/src/components/bookmark-trace";
export type TraceTableRow = {
+ bookmarked: boolean;
id: string;
timestamp: string;
name: string;
@@ -111,6 +113,7 @@ export default function TracesTable({
trace: RouterOutput["traces"]["all"][0],
): TraceTableRow => {
return {
+ bookmarked: trace.bookmarked,
id: trace.id,
timestamp: trace.timestamp.toLocaleString(),
name: trace.name ?? "",
@@ -129,6 +132,24 @@ export default function TracesTable({
};
const columns: ColumnDef<TraceTableRow>[] = [
+ {
+ accessorKey: "bookmarked",
+ header: undefined,
+ cell: ({ row }) => {
+ const isBookmarked = row.getValue("bookmarked");
+ const traceId = row.getValue("id");
+
+ return typeof traceId === "string" &&
+ typeof isBookmarked === "boolean" ? (
+ <BookmarkTrace
+ traceId={traceId}
+ projectId={projectId}
+ isBookmarked={isBookmarked}
+ size="xs"
+ />
+ ) : undefined;
+ },
+ },
{
accessorKey: "id",
header: "ID",
diff --git a/src/components/trace/index.tsx b/src/components/trace/index.tsx
index 4021d7ef14..3d2d8a358b 100644
--- a/src/components/trace/index.tsx
+++ b/src/components/trace/index.tsx
@@ -14,6 +14,7 @@ import { useRouter } from "next/router";
import { type ObservationReturnType } from "@/src/server/api/routers/traces";
import { api } from "@/src/utils/api";
import { DeleteTrace } from "@/src/components/delete-trace";
+import { BookmarkTrace } from "@/src/components/bookmark-trace";
export function Trace(props: {
observations: Array<ObservationReturnType>;
@@ -91,6 +92,11 @@ export function TracePage({ traceId }: { traceId: string }) {
title="Trace Detail"
actionButtons={
<>
+ <BookmarkTrace
+ traceId={trace.data.id}
+ projectId={trace.data.projectId}
+ isBookmarked={trace.data.bookmarked}
+ />
<PublishTraceSwitch
traceId={trace.data.id}
projectId={trace.data.projectId}
diff --git a/src/components/ui/button.tsx b/src/components/ui/button.tsx
index 052f8f7dfc..f68d83f34b 100644
--- a/src/components/ui/button.tsx
+++ b/src/components/ui/button.tsx
@@ -78,7 +78,7 @@ export { Button, buttonVariants };
function Spinner() {
return (
- <div className="flex h-3/4 items-center justify-center">
+ <div className="flex h-1/2 items-center justify-center">
<Loader2 className="h-full w-full animate-spin" />
</div>
);
diff --git a/src/features/filters/components/filter-builder.tsx b/src/features/filters/components/filter-builder.tsx
index 880154e65c..c96c12eaf3 100644
--- a/src/features/filters/components/filter-builder.tsx
+++ b/src/features/filters/components/filter-builder.tsx
@@ -58,11 +58,10 @@ export function FilterBuilder({
) => {
_setWipFilterState((prev) => {
const newState = state instanceof Function ? state(prev) : state;
- onChange(
- newState.filter(
- (f) => singleFilter.safeParse(f).success,
- ) as FilterState,
- );
+ const validFilters = newState.filter(
+ (f) => singleFilter.safeParse(f).success,
+ ) as FilterState;
+ onChange(validFilters);
return newState;
});
};
@@ -97,11 +96,13 @@ export function FilterBuilder({
{filter.type === "datetime"
? new Date(filter.value).toLocaleDateString()
: filter.type === "stringOptions"
- ? filter.value.join(", ")
- : filter.type === "number" ||
- filter.type === "numberObject"
- ? filter.value
- : `"${filter.value}"`}
+ ? filter.value.join(", ")
+ : filter.type === "number" ||
+ filter.type === "numberObject"
+ ? filter.value
+ : filter.type === "boolean"
+ ? `${filter.value}`
+ : `"${filter.value}"`}
</span>
);
})
@@ -332,6 +333,33 @@ function FilterBuilderForm({
}
values={Array.isArray(filter.value) ? filter.value : []}
/>
+ ) : filter.type === "boolean" ? (
+ <Select
+ onValueChange={(value) => {
+ handleFilterChange(
+ {
+ ...filter,
+ value:
+ value !== undefined && value !== ""
+ ? value === "true"
+ : undefined,
+ },
+ i,
+ );
+ }}
+ value={filter.value?.toString() ?? ""}
+ >
+ <SelectTrigger className="min-w-[60px]">
+ <SelectValue placeholder="" />
+ </SelectTrigger>
+ <SelectContent>
+ {["true", "false"].map((option) => (
+ <SelectItem key={option} value={option}>
+ {option}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
) : (
<Input disabled />
)}
diff --git a/src/features/filters/hooks/useFilterState.ts b/src/features/filters/hooks/useFilterState.ts
index 9eca8d26ed..531aed681b 100644
--- a/src/features/filters/hooks/useFilterState.ts
+++ b/src/features/filters/hooks/useFilterState.ts
@@ -22,8 +22,8 @@ const CommaArrayParam = {
f.type === "datetime"
? f.value.toISOString()
: f.type === "stringOptions"
- ? f.value.join("|")
- : f.value
+ ? f.value.join("|")
+ : f.value
}`;
if (DEBUG_QUERY_STATE) console.log("stringified", stringified);
return stringified;
@@ -42,12 +42,14 @@ const CommaArrayParam = {
value === undefined || type === undefined
? undefined
: type === "datetime"
- ? new Date(value)
- : type === "number" || type === "numberObject"
- ? Number(value)
- : type === "stringOptions"
- ? value.split("|")
- : value;
+ ? new Date(value)
+ : type === "number" || type === "numberObject"
+ ? Number(value)
+ : type === "stringOptions"
+ ? value.split("|")
+ : type === "boolean"
+ ? value === "true"
+ : value;
if (DEBUG_QUERY_STATE) console.log("parsedValue", parsedValue);
const parsed = singleFilter.safeParse({
column,
diff --git a/src/features/filters/server/filterToPrisma.ts b/src/features/filters/server/filterToPrisma.ts
index f6ec02694b..e94b00efd4 100644
--- a/src/features/filters/server/filterToPrisma.ts
+++ b/src/features/filters/server/filterToPrisma.ts
@@ -58,6 +58,9 @@ export function filterToPrismaSql(
filter.value.map((v) => Prisma.sql`${v}`),
)})`;
break;
+ case "boolean":
+ valuePrisma = Prisma.sql`${filter.value}`;
+ break;
}
const jsonKeyPrisma =
filter.type === "stringObject" || filter.type === "numberObject"
diff --git a/src/features/rbac/constants/roleAccessRights.ts b/src/features/rbac/constants/roleAccessRights.ts
index 7f28200af9..c3cb3acfbc 100644
--- a/src/features/rbac/constants/roleAccessRights.ts
+++ b/src/features/rbac/constants/roleAccessRights.ts
@@ -10,6 +10,7 @@ const scopes = [
"apiKeys:delete",
"traces:publish",
+ "traces:bookmark",
"traces:delete",
"scores:CUD",
@@ -32,6 +33,7 @@ export const roleAccessRights: Record<MembershipRole, Scope[]> = {
"apiKeys:create",
"apiKeys:delete",
"traces:publish",
+ "traces:bookmark",
"traces:delete",
"scores:CUD",
"project:delete",
@@ -46,10 +48,17 @@ export const roleAccessRights: Record<MembershipRole, Scope[]> = {
"apiKeys:create",
"apiKeys:delete",
"traces:publish",
+ "traces:bookmark",
"traces:delete",
"scores:CUD",
"datasets:CUD",
],
- MEMBER: ["members:read", "traces:publish", "scores:CUD", "datasets:CUD"],
+ MEMBER: [
+ "members:read",
+ "traces:publish",
+ "traces:bookmark",
+ "scores:CUD",
+ "datasets:CUD",
+ ],
VIEWER: [],
};
diff --git a/src/server/api/definitions/tracesTable.ts b/src/server/api/definitions/tracesTable.ts
index 9134b5abe2..10d172b76b 100644
--- a/src/server/api/definitions/tracesTable.ts
+++ b/src/server/api/definitions/tracesTable.ts
@@ -4,6 +4,7 @@ import {
} from "@/src/server/api/interfaces/tableDefinition";
export const tracesTableCols: ColumnDefinition[] = [
+ { name: "⭐️", type: "boolean", internal: "t.bookmarked" },
{ name: "id", type: "string", internal: "t.id" },
{
name: "name",
diff --git a/src/server/api/interfaces/filters.ts b/src/server/api/interfaces/filters.ts
index 5fdaee5792..0eac5365fa 100644
--- a/src/server/api/interfaces/filters.ts
+++ b/src/server/api/interfaces/filters.ts
@@ -13,6 +13,7 @@ export const filterOperators = {
"ends with",
],
numberObject: ["=", ">", "<", ">=", "<="],
+ boolean: ["=", "<>"],
} as const;
export const timeFilter = z.object({
@@ -54,6 +55,12 @@ export const numberObjectFilter = z.object({
operator: z.enum(filterOperators.number),
value: z.number(),
});
+export const booleanFilter = z.object({
+ type: z.literal("boolean"),
+ column: z.string(),
+ operator: z.enum(filterOperators.boolean),
+ value: z.boolean(),
+});
export const singleFilter = z.discriminatedUnion("type", [
timeFilter,
stringFilter,
@@ -61,4 +68,5 @@ export const singleFilter = z.discriminatedUnion("type", [
stringOptionsFilter,
stringObjectFilter,
numberObjectFilter,
+ booleanFilter,
]);
diff --git a/src/server/api/interfaces/tableDefinition.ts b/src/server/api/interfaces/tableDefinition.ts
index 0a9f201862..f071d566a3 100644
--- a/src/server/api/interfaces/tableDefinition.ts
+++ b/src/server/api/interfaces/tableDefinition.ts
@@ -6,7 +6,7 @@ export type OptionsDefinition = {
export type ColumnDefinition =
| {
name: string;
- type: "number" | "string" | "datetime";
+ type: "number" | "string" | "datetime" | "boolean";
internal: string;
}
| {
diff --git a/src/server/api/routers/traces.ts b/src/server/api/routers/traces.ts
index a9c8b30285..9812dab8f1 100644
--- a/src/server/api/routers/traces.ts
+++ b/src/server/api/routers/traces.ts
@@ -154,6 +154,7 @@ export const traceRouter = createTRPCRouter({
t.*,
t."user_id" AS "userId",
t."metadata" AS "metadata",
+ t."bookmarked" AS "bookmarked",
COALESCE(u."promptTokens", 0)::int AS "promptTokens",
COALESCE(u."completionTokens", 0)::int AS "completionTokens",
COALESCE(u."totalTokens", 0)::int AS "totalTokens",
@@ -309,4 +310,37 @@ export const traceRouter = createTRPCRouter({
}),
]);
}),
+ bookmark: protectedProjectProcedure
+ .input(
+ z.object({
+ traceId: z.string(),
+ projectId: z.string(),
+ bookmarked: z.boolean(),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ throwIfNoAccess({
+ session: ctx.session,
+ projectId: input.projectId,
+ scope: "traces:bookmark",
+ });
+ const trace = await ctx.prisma.trace.findFirst({
+ where: {
+ id: input.traceId,
+ projectId: input.projectId,
+ },
+ });
+ if (!trace) {
+ throw new Error("Trace not found in project");
+ }
+
+ return ctx.prisma.trace.update({
+ where: {
+ id: input.traceId,
+ },
+ data: {
+ bookmarked: input.bookmarked,
+ },
+ });
+ }),
});