Skip to content

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

feat(annotation): add annotation queue in feature flagged beta release (#3499)

marliessophiec4fa31be9f39
diff --git a/.codespellrc b/.codespellrc
index dad3ecc8e4..09e92873b0 100644
--- a/.codespellrc
+++ b/.codespellrc
@@ -1,4 +1,4 @@
[codespell]
skip = .git,*.pdf,*.svg,package-lock.json,*.prisma,pnpm-lock.yaml
-ignore-words-list = afterall,vertx
+ignore-words-list = afterall,vertx,notIn
diff --git a/packages/shared/prisma/generated/types.ts b/packages/shared/prisma/generated/types.ts
index 2589771ee4..aa2924b918 100644
--- a/packages/shared/prisma/generated/types.ts
+++ b/packages/shared/prisma/generated/types.ts
@@ -37,6 +37,16 @@ export const ScoreDataType = {
BOOLEAN: "BOOLEAN"
} as const;
export type ScoreDataType = (typeof ScoreDataType)[keyof typeof ScoreDataType];
+export const AnnotationQueueStatus = {
+ PENDING: "PENDING",
+ COMPLETED: "COMPLETED"
+} as const;
+export type AnnotationQueueStatus = (typeof AnnotationQueueStatus)[keyof typeof AnnotationQueueStatus];
+export const AnnotationQueueObjectType = {
+ TRACE: "TRACE",
+ OBSERVATION: "OBSERVATION"
+} as const;
+export type AnnotationQueueObjectType = (typeof AnnotationQueueObjectType)[keyof typeof AnnotationQueueObjectType];
export const DatasetStatus = {
ACTIVE: "ACTIVE",
ARCHIVED: "ARCHIVED"
@@ -83,6 +93,29 @@ export type Account = {
refresh_token_expires_in: number | null;
created_at: number | null;
};
+export type AnnotationQueue = {
+ id: string;
+ name: string;
+ description: string | null;
+ score_config_ids: Generated<string[]>;
+ project_id: string;
+ created_at: Generated<Timestamp>;
+ updated_at: Generated<Timestamp>;
+};
+export type AnnotationQueueItem = {
+ id: string;
+ queue_id: string;
+ object_id: string;
+ object_type: AnnotationQueueObjectType;
+ status: Generated<AnnotationQueueStatus>;
+ locked_at: Timestamp | null;
+ locked_by_user_id: string | null;
+ annotator_user_id: string | null;
+ completed_at: Timestamp | null;
+ project_id: string;
+ created_at: Generated<Timestamp>;
+ updated_at: Generated<Timestamp>;
+};
export type ApiKey = {
id: string;
created_at: Generated<Timestamp>;
@@ -411,6 +444,7 @@ export type Score = {
observation_id: string | null;
config_id: string | null;
string_value: string | null;
+ queue_id: string | null;
created_at: Generated<Timestamp>;
updated_at: Generated<Timestamp>;
data_type: Generated<ScoreDataType>;
@@ -507,6 +541,8 @@ export type VerificationToken = {
};
export type DB = {
Account: Account;
+ annotation_queue_items: AnnotationQueueItem;
+ annotation_queues: AnnotationQueue;
api_keys: ApiKey;
audit_logs: AuditLog;
batch_exports: BatchExport;
diff --git a/packages/shared/prisma/migrations/20241009110720_scores_add_nullable_queue_id_column/migration.sql b/packages/shared/prisma/migrations/20241009110720_scores_add_nullable_queue_id_column/migration.sql
new file mode 100644
index 0000000000..106bfc75e2
--- /dev/null
+++ b/packages/shared/prisma/migrations/20241009110720_scores_add_nullable_queue_id_column/migration.sql
@@ -0,0 +1,2 @@
+-- AlterTable
+ALTER TABLE "scores" ADD COLUMN "queue_id" TEXT;
diff --git a/packages/shared/prisma/migrations/20241009113245_add_annotation_queue/migration.sql b/packages/shared/prisma/migrations/20241009113245_add_annotation_queue/migration.sql
new file mode 100644
index 0000000000..6f619ca7a8
--- /dev/null
+++ b/packages/shared/prisma/migrations/20241009113245_add_annotation_queue/migration.sql
@@ -0,0 +1,75 @@
+-- CreateEnum
+CREATE TYPE "AnnotationQueueStatus" AS ENUM ('PENDING', 'COMPLETED');
+
+-- CreateEnum
+CREATE TYPE "AnnotationQueueObjectType" AS ENUM ('TRACE', 'OBSERVATION');
+
+-- CreateTable
+CREATE TABLE "annotation_queues" (
+ "id" TEXT NOT NULL,
+ "name" TEXT NOT NULL,
+ "description" TEXT,
+ "score_config_ids" TEXT[] DEFAULT ARRAY[]::TEXT[],
+ "project_id" TEXT NOT NULL,
+ "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updated_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+
+ CONSTRAINT "annotation_queues_pkey" PRIMARY KEY ("id")
+);
+
+-- CreateTable
+CREATE TABLE "annotation_queue_items" (
+ "id" TEXT NOT NULL,
+ "queue_id" TEXT NOT NULL,
+ "object_id" TEXT NOT NULL,
+ "object_type" "AnnotationQueueObjectType" NOT NULL,
+ "status" "AnnotationQueueStatus" NOT NULL DEFAULT 'PENDING',
+ "locked_at" TIMESTAMP(3),
+ "locked_by_user_id" TEXT,
+ "annotator_user_id" TEXT,
+ "completed_at" TIMESTAMP(3),
+ "project_id" TEXT NOT NULL,
+ "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updated_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+
+ CONSTRAINT "annotation_queue_items_pkey" PRIMARY KEY ("id")
+);
+
+-- CreateIndex
+CREATE INDEX "annotation_queues_id_project_id_idx" ON "annotation_queues"("id", "project_id");
+
+-- CreateIndex
+CREATE INDEX "annotation_queues_project_id_created_at_idx" ON "annotation_queues"("project_id", "created_at");
+
+-- CreateIndex
+CREATE UNIQUE INDEX "annotation_queues_project_id_name_key" ON "annotation_queues"("project_id", "name");
+
+-- CreateIndex
+CREATE INDEX "annotation_queue_items_id_project_id_idx" ON "annotation_queue_items"("id", "project_id");
+
+-- CreateIndex
+CREATE INDEX "annotation_queue_items_project_id_queue_id_status_idx" ON "annotation_queue_items"("project_id", "queue_id", "status");
+
+-- CreateIndex
+CREATE INDEX "annotation_queue_items_object_id_object_type_project_id_que_idx" ON "annotation_queue_items"("object_id", "object_type", "project_id", "queue_id");
+
+-- CreateIndex
+CREATE INDEX "annotation_queue_items_annotator_user_id_idx" ON "annotation_queue_items"("annotator_user_id");
+
+-- CreateIndex
+CREATE INDEX "annotation_queue_items_created_at_idx" ON "annotation_queue_items"("created_at");
+
+-- AddForeignKey
+ALTER TABLE "annotation_queues" ADD CONSTRAINT "annotation_queues_project_id_fkey" FOREIGN KEY ("project_id") REFERENCES "projects"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "annotation_queue_items" ADD CONSTRAINT "annotation_queue_items_queue_id_fkey" FOREIGN KEY ("queue_id") REFERENCES "annotation_queues"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "annotation_queue_items" ADD CONSTRAINT "annotation_queue_items_locked_by_user_id_fkey" FOREIGN KEY ("locked_by_user_id") REFERENCES "users"("id") ON DELETE SET NULL ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "annotation_queue_items" ADD CONSTRAINT "annotation_queue_items_annotator_user_id_fkey" FOREIGN KEY ("annotator_user_id") REFERENCES "users"("id") ON DELETE SET NULL ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "annotation_queue_items" ADD CONSTRAINT "annotation_queue_items_project_id_fkey" FOREIGN KEY ("project_id") REFERENCES "projects"("id") ON DELETE CASCADE ON UPDATE CASCADE;
diff --git a/packages/shared/prisma/schema.prisma b/packages/shared/prisma/schema.prisma
index c0b4e5b171..e38659a747 100644
--- a/packages/shared/prisma/schema.prisma
+++ b/packages/shared/prisma/schema.prisma
@@ -2,874 +2,932 @@
// learn more about it in the docs: https://pris.ly/d/prisma-schema
generator client {
- provider = "prisma-client-js"
- previewFeatures = ["tracing", "views", "relationJoins", "metrics"]
+ provider = "prisma-client-js"
+ previewFeatures = ["tracing", "views", "relationJoins", "metrics"]
}
datasource db {
- provider = "postgresql"
- url = env("DATABASE_URL")
- directUrl = env("DIRECT_URL")
- shadowDatabaseUrl = env("SHADOW_DATABASE_URL")
+ provider = "postgresql"
+ url = env("DATABASE_URL")
+ directUrl = env("DIRECT_URL")
+ shadowDatabaseUrl = env("SHADOW_DATABASE_URL")
}
generator erd {
- provider = "prisma-erd-generator"
- ignoreTables = ["_prisma_migrations", "Session", "Account", "Example"]
- disabled = true
- ignoreEnums = true
- output = "database.svg"
+ provider = "prisma-erd-generator"
+ ignoreTables = ["_prisma_migrations", "Session", "Account", "Example"]
+ disabled = true
+ ignoreEnums = true
+ output = "database.svg"
}
generator kysely {
- provider = "prisma-kysely"
+ provider = "prisma-kysely"
- // Optionally provide a destination directory for the generated file
- // and a filename of your choice
- // output = "../src/db"
- // fileName = "types.ts"
- // Optionally generate runtime enums to a separate file
- // enumFileName = "enums.ts"
+ // Optionally provide a destination directory for the generated file
+ // and a filename of your choice
+ // output = "../src/db"
+ // fileName = "types.ts"
+ // Optionally generate runtime enums to a separate file
+ // enumFileName = "enums.ts"
}
// 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?
- expires_in Int?
- ext_expires_in Int?
- token_type String?
- scope String?
- id_token String? // @db.Text
- session_state String?
- refresh_token_expires_in Int?
- created_at Int? // GitLab
- 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?
+ expires_in Int?
+ ext_expires_in Int?
+ token_type String?
+ scope String?
+ id_token String? // @db.Text
+ session_state String?
+ refresh_token_expires_in Int?
+ created_at Int? // GitLab
+ 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[]
- organizationMemberships OrganizationMembership[]
- projectMemberships ProjectMembership[]
- invitations MembershipInvitation[]
- 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[]
+ organizationMemberships OrganizationMembership[]
+ projectMemberships ProjectMembership[]
+ invitations MembershipInvitation[]
+ createdAt DateTime @default(now()) @map("created_at")
+ updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
+ featureFlags String[] @default([]) @map("feature_flags")
+ annotatedLockedItem AnnotationQueueItem[] @relation("LockedByUser")
+ annotatedCompletedItem AnnotationQueueItem[] @relation("AnnotatorUser")
+
+ @@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 Organization {
- id String @id @default(cuid())
- name String
- createdAt DateTime @default(now()) @map("created_at")
- updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
- cloudConfig Json? @map("cloud_config") // Langfuse Cloud, for zod schema see @/src/features/organizations/utils/cloudConfigSchema
- organizationMemberships OrganizationMembership[]
- projects Project[]
- MembershipInvitation MembershipInvitation[]
+ id String @id @default(cuid())
+ name String
+ createdAt DateTime @default(now()) @map("created_at")
+ updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
+ cloudConfig Json? @map("cloud_config") // Langfuse Cloud, for zod schema see @/src/features/organizations/utils/cloudConfigSchema
+ organizationMemberships OrganizationMembership[]
+ projects Project[]
+ MembershipInvitation MembershipInvitation[]
- @@map("organizations")
+ @@map("organizations")
}
model Project {
- id String @id @default(cuid())
- orgId String @map("org_id")
- createdAt DateTime @default(now()) @map("created_at")
- updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
- name String
- projectMembers ProjectMembership[]
- organization Organization @relation(fields: [orgId], references: [id], onUpdate: Cascade, onDelete: Cascade)
- traces Trace[]
- observations Observation[]
- apiKeys ApiKey[]
- dataset Dataset[]
- RawEvents Events[]
- invitations MembershipInvitation[]
- sessions TraceSession[]
- Prompt Prompt[]
- Model Model[]
- EvalTemplate EvalTemplate[]
- JobConfiguration JobConfiguration[]
- JobExecution JobExecution[]
- LlmApiKeys LlmApiKeys[]
- PosthogIntegration PosthogIntegration[]
- Score Score[]
- scoreConfig ScoreConfig[]
- BatchExport BatchExport[]
- comment Comment[]
-
- @@index([orgId])
- @@map("projects")
+ id String @id @default(cuid())
+ orgId String @map("org_id")
+ createdAt DateTime @default(now()) @map("created_at")
+ updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
+ name String
+ projectMembers ProjectMembership[]
+ organization Organization @relation(fields: [orgId], references: [id], onUpdate: Cascade, onDelete: Cascade)
+ traces Trace[]
+ observations Observation[]
+ apiKeys ApiKey[]
+ dataset Dataset[]
+ RawEvents Events[]
+ invitations MembershipInvitation[]
+ sessions TraceSession[]
+ Prompt Prompt[]
+ Model Model[]
+ EvalTemplate EvalTemplate[]
+ JobConfiguration JobConfiguration[]
+ JobExecution JobExecution[]
+ LlmApiKeys LlmApiKeys[]
+ PosthogIntegration PosthogIntegration[]
+ Score Score[]
+ scoreConfig ScoreConfig[]
+ BatchExport BatchExport[]
+ comment Comment[]
+ annotationQueue AnnotationQueue[]
+ annotationQueueItem AnnotationQueueItem[]
+
+ @@index([orgId])
+ @@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 LlmApiKeys {
- id String @id @unique @default(cuid())
- createdAt DateTime @default(now()) @map("created_at")
- updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
+ id String @id @unique @default(cuid())
+ createdAt DateTime @default(now()) @map("created_at")
+ updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
- provider String
- adapter String // This controls the interface that is used to connect with the LLM, e.g. 'openai' or 'anthropic'
- displaySecretKey String @map("display_secret_key")
- secretKey String @map("secret_key")
- baseURL String? @map("base_url")
- customModels String[] @default([]) @map("custom_models")
- withDefaultModels Boolean @default(true) @map("with_default_models")
+ provider String
+ adapter String // This controls the interface that is used to connect with the LLM, e.g. 'openai' or 'anthropic'
+ displaySecretKey String @map("display_secret_key")
+ secretKey String @map("secret_key")
+ baseURL String? @map("base_url")
+ customModels String[] @default([]) @map("custom_models")
+ withDefaultModels Boolean @default(true) @map("with_default_models")
- projectId String @map("project_id")
- project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
+ projectId String @map("project_id")
+ project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
- @@unique([projectId, provider])
- @@map("llm_api_keys")
+ @@unique([projectId, provider])
+ @@map("llm_api_keys")
}
model OrganizationMembership {
- id String @id @default(cuid())
- orgId String @map("org_id")
- organization Organization @relation(fields: [orgId], references: [id], onDelete: Cascade)
- userId String @map("user_id")
- user User @relation(fields: [userId], references: [id], onDelete: Cascade)
- role Role @map("role")
- createdAt DateTime @default(now()) @map("created_at")
- updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
- ProjectMemberships ProjectMembership[]
+ id String @id @default(cuid())
+ orgId String @map("org_id")
+ organization Organization @relation(fields: [orgId], references: [id], onDelete: Cascade)
+ userId String @map("user_id")
+ user User @relation(fields: [userId], references: [id], onDelete: Cascade)
+ role Role @map("role")
+ createdAt DateTime @default(now()) @map("created_at")
+ updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
+ ProjectMemberships ProjectMembership[]
- @@unique([orgId, userId])
- @@index([userId])
- @@map("organization_memberships")
+ @@unique([orgId, userId])
+ @@index([userId])
+ @@map("organization_memberships")
}
// Set a project-specific role for a user in an organization
model ProjectMembership {
- orgMembershipId String @map("org_membership_id")
- organizationMembership OrganizationMembership @relation(fields: [orgMembershipId], references: [id], onDelete: Cascade)
- 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 Role
- createdAt DateTime @default(now()) @map("created_at")
- updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
-
- @@id([projectId, userId])
- @@index([userId])
- @@index([projectId])
- @@index([orgMembershipId])
- @@map("project_memberships")
+ orgMembershipId String @map("org_membership_id")
+ organizationMembership OrganizationMembership @relation(fields: [orgMembershipId], references: [id], onDelete: Cascade)
+ 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 Role
+ createdAt DateTime @default(now()) @map("created_at")
+ updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
+
+ @@id([projectId, userId])
+ @@index([userId])
+ @@index([projectId])
+ @@index([orgMembershipId])
+ @@map("project_memberships")
}
model MembershipInvitation {
- id String @id @unique @default(cuid())
- email String
- orgId String @map("org_id")
- organization Organization @relation(fields: [orgId], references: [id], onDelete: Cascade)
- orgRole Role @map("org_role")
- projectId String? @map("project_id")
- project Project? @relation(fields: [projectId], references: [id], onDelete: SetNull)
- projectRole Role? @map("project_role")
- invitedByUserId String? @map("invited_by_user_id")
- invitedByUser User? @relation(fields: [invitedByUserId], references: [id], onDelete: SetNull)
- createdAt DateTime @default(now()) @map("created_at")
- updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
-
- @@index([projectId])
- @@index([orgId])
- @@index([email])
- @@map("membership_invitations")
+ id String @id @unique @default(cuid())
+ email String
+ orgId String @map("org_id")
+ organization Organization @relation(fields: [orgId], references: [id], onDelete: Cascade)
+ orgRole Role @map("org_role")
+ projectId String? @map("project_id")
+ project Project? @relation(fields: [projectId], references: [id], onDelete: SetNull)
+ projectRole Role? @map("project_role")
+ invitedByUserId String? @map("invited_by_user_id")
+ invitedByUser User? @relation(fields: [invitedByUserId], references: [id], onDelete: SetNull)
+ createdAt DateTime @default(now()) @map("created_at")
+ updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
+
+ @@index([projectId])
+ @@index([orgId])
+ @@index([email])
+ @@map("membership_invitations")
}
enum Role {
- OWNER
- ADMIN
- MEMBER
- VIEWER
- NONE
+ OWNER
+ ADMIN
+ MEMBER
+ VIEWER
+ NONE
}
model TraceSession {
- id String @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)
- bookmarked Boolean @default(false)
- public Boolean @default(false)
- traces Trace[]
-
- @@id([id, projectId])
- @@index([projectId])
- @@index([createdAt])
- @@index([updatedAt])
- @@map("trace_sessions")
+ id String @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)
+ bookmarked Boolean @default(false)
+ public Boolean @default(false)
+ traces Trace[]
+
+ @@id([id, projectId])
+ @@index([projectId])
+ @@index([createdAt])
+ @@index([updatedAt])
+ @@map("trace_sessions")
}
// Update TraceView below when making changes to this model!
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)
- bookmarked Boolean @default(false)
- tags String[] @default([])
- input Json?
- output Json?
- sessionId String? @map("session_id")
- session TraceSession? @relation(fields: [sessionId, projectId], references: [id, projectId])
- createdAt DateTime @default(now()) @map("created_at")
- updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
-
- JobExecution JobExecution[]
-
- @@index([projectId, timestamp])
- @@index([sessionId])
- @@index([name])
- @@index([userId])
- @@index([id, userId])
- @@index(timestamp)
- @@index(createdAt)
- @@index([tags(ops: ArrayOps)], type: Gin)
- @@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)
+ tags String[] @default([])
+ input Json?
+ output Json?
+ sessionId String? @map("session_id")
+ session TraceSession? @relation(fields: [sessionId, projectId], references: [id, projectId])
+ createdAt DateTime @default(now()) @map("created_at")
+ updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
+
+ JobExecution JobExecution[]
+
+ @@index([projectId, timestamp])
+ @@index([sessionId])
+ @@index([name])
+ @@index([userId])
+ @@index([id, userId])
+ @@index(timestamp)
+ @@index(createdAt)
+ @@index([tags(ops: ArrayOps)], type: Gin)
+ @@map("traces")
}
// This view is based on the trace table. Once prisma supports
// inheritance, we should remove code duplication here.
view TraceView {
- // trace fields
- 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")
- public Boolean @default(false)
- bookmarked Boolean @default(false)
- tags String[] @default([])
- input Json?
- output Json?
- sessionId String? @map("session_id")
- createdAt DateTime @map("created_at")
- updatedAt DateTime @map("updated_at")
-
- // calculated fields
- duration Float? @map("duration") // can be null if no observations in trace
-
- @@map("traces_view")
+ // trace fields
+ 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")
+ public Boolean @default(false)
+ bookmarked Boolean @default(false)
+ tags String[] @default([])
+ input Json?
+ output Json?
+ sessionId String? @map("session_id")
+ createdAt DateTime @map("created_at")
+ updatedAt DateTime @map("updated_at")
+
+ // calculated fields
+ duration Float? @map("duration") // can be null if no observations in trace
+
+ @@map("traces_view")
}
// Update ObservationView below when making changes to this model!
// traceId is optional only due to timing during data injestion
// (traceId is not necessarily known at the time of observation creation)
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")
- updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
-
- // GENERATION ONLY
- model String? // user-provided model attribute
- internalModel String? @map("internal_model") // matched model.name that is matched at ingestion time, to be deprecated
- internalModelId String? @map("internal_model_id") // matched model.id that is matched at ingestion time
-
- 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")
- unit String?
-
- // User provided cost at ingestion
- inputCost Decimal? @map("input_cost")
- outputCost Decimal? @map("output_cost")
- totalCost Decimal? @map("total_cost")
-
- // Calculated cost
- calculatedInputCost Decimal? @map("calculated_input_cost")
- calculatedOutputCost Decimal? @map("calculated_output_cost")
- calculatedTotalCost Decimal? @map("calculated_total_cost")
-
- completionStartTime DateTime? @map("completion_start_time")
- project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
-
- promptId String? @map("prompt_id") // no fk constraint, prompt can be deleted
-
- @@unique([id, projectId])
- @@index([projectId, internalModel, startTime, unit])
- @@index([traceId, projectId, type, startTime])
- @@index([traceId, projectId, startTime])
- @@index([type])
- @@index(startTime)
- @@index(createdAt)
- @@index(model)
- @@index(internalModel)
- @@index([projectId, promptId])
- @@index(promptId)
- @@index([projectId, startTime, type])
- @@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")
+ updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
+
+ // GENERATION ONLY
+ model String? // user-provided model attribute
+ internalModel String? @map("internal_model") // matched model.name that is matched at ingestion time, to be deprecated
+ internalModelId String? @map("internal_model_id") // matched model.id that is matched at ingestion time
+
+ 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")
+ unit String?
+
+ // User provided cost at ingestion
+ inputCost Decimal? @map("input_cost")
+ outputCost Decimal? @map("output_cost")
+ totalCost Decimal? @map("total_cost")
+
+ // Calculated cost
+ calculatedInputCost Decimal? @map("calculated_input_cost")
+ calculatedOutputCost Decimal? @map("calculated_output_cost")
+ calculatedTotalCost Decimal? @map("calculated_total_cost")
+
+ completionStartTime DateTime? @map("completion_start_time")
+ project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
+
+ promptId String? @map("prompt_id") // no fk constraint, prompt can be deleted
+
+ @@unique([id, projectId])
+ @@index([projectId, internalModel, startTime, unit])
+ @@index([traceId, projectId, type, startTime])
+ @@index([traceId, projectId, startTime])
+ @@index([type])
+ @@index(startTime)
+ @@index(createdAt)
+ @@index(model)
+ @@index(internalModel)
+ @@index([projectId, promptId])
+ @@index(promptId)
+ @@index([projectId, startTime, type])
+ @@map("observations")
}
// This view is a mix of the observation and model. Once prisma supports
// inheritance, we should remove code duplication here.
view ObservationView {
- id String @id @default(cuid())
- traceId String? @map("trace_id")
- projectId String @map("project_id")
- type ObservationType
- startTime DateTime @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 @map("created_at")
- updatedAt DateTime @map("updated_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")
- unit String?
- completionStartTime DateTime? @map("completion_start_time")
-
- // prompts
- promptId String? @map("prompt_id")
- promptName String? @map("prompt_name")
- promptVersion Int? @map("prompt_version")
-
- // model fields
- modelId String? @map("model_id")
- inputPrice Decimal? @map("input_price")
- outputPrice Decimal? @map("output_price")
- totalPrice Decimal? @map("total_price")
-
- // calculated fields
- calculatedInputCost Decimal? @map("calculated_input_cost")
- calculatedOutputCost Decimal? @map("calculated_output_cost")
- calculatedTotalCost Decimal? @map("calculated_total_cost")
- latency Float? @map("latency")
- timeToFirstToken Float? @map("time_to_first_token")
-
- @@map("observations_view")
+ id String @id @default(cuid())
+ traceId String? @map("trace_id")
+ projectId String @map("project_id")
+ type ObservationType
+ startTime DateTime @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 @map("created_at")
+ updatedAt DateTime @map("updated_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")
+ unit String?
+ completionStartTime DateTime? @map("completion_start_time")
+
+ // prompts
+ promptId String? @map("prompt_id")
+ promptName String? @map("prompt_name")
+ promptVersion Int? @map("prompt_version")
+
+ // model fields
+ modelId String? @map("model_id")
+ inputPrice Decimal? @map("input_price")
+ outputPrice Decimal? @map("output_price")
+ totalPrice Decimal? @map("total_price")
+
+ // calculated fields
+ calculatedInputCost Decimal? @map("calculated_input_cost")
+ calculatedOutputCost Decimal? @map("calculated_output_cost")
+ calculatedTotalCost Decimal? @map("calculated_total_cost")
+ latency Float? @map("latency")
+ timeToFirstToken Float? @map("time_to_first_token")
+
+ @@map("observations_view")
}
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())
- projectId String @map("project_id")
- project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
- name String
- value Float? // always defined if data type is NUMERIC or BOOLEAN, optional for CATEGORICAL
- source ScoreSource
- authorUserId String? @map("author_user_id")
- comment String?
- traceId String @map("trace_id")
- observationId String? @map("observation_id")
- configId String? @map("config_id")
- stringValue String? @map("string_value") // always defined if data type is CATEGORICAL or BOOLEAN, null for NUMERIC
- createdAt DateTime @default(now()) @map("created_at")
- updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
- dataType ScoreDataType @default(NUMERIC) @map("data_type")
- JobExecution JobExecution[]
- scoreConfig ScoreConfig? @relation(fields: [configId], references: [id], onDelete: SetNull)
-
- @@unique([id, projectId]) // used for upserts via prisma
- @@index(timestamp)
- @@index([value])
- @@index([projectId, name])
- @@index([authorUserId])
- @@index([configId])
- @@index([traceId], type: Hash)
- @@index([observationId], type: Hash)
- @@index([source])
- @@index([createdAt])
- @@map("scores")
+ id String @id @default(cuid())
+ timestamp DateTime @default(now())
+ projectId String @map("project_id")
+ project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
+ name String
+ value Float? // always defined if data type is NUMERIC or BOOLEAN, optional for CATEGORICAL
+ source ScoreSource
+ authorUserId String? @map("author_user_id")
+ comment String?
+ traceId String @map("trace_id")
+ observationId String? @map("observation_id")
+ configId String? @map("config_id")
+ stringValue String? @map("string_value") // always defined if data type is CATEGORICAL or BOOLEAN, null for NUMERIC
+ queueId String? @map("queue_id")
+ createdAt DateTime @default(now()) @map("created_at")
+ updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
+ dataType ScoreDataType @default(NUMERIC) @map("data_type")
+ JobExecution JobExecution[]
+ scoreConfig ScoreConfig? @relation(fields: [configId], references: [id], onDelete: SetNull)
+
+ @@unique([id, projectId]) // used for upserts via prisma
+ @@index(timestamp)
+ @@index([value])
+ @@index([projectId, name])
+ @@index([authorUserId])
+ @@index([configId])
+ @@index([traceId], type: Hash)
+ @@index([observationId], type: Hash)
+ @@index([source])
+ @@index([createdAt])
+ @@map("scores")
}
enum ScoreSource {
- ANNOTATION
- API
- EVAL
+ ANNOTATION
+ API
+ EVAL
}
model ScoreConfig {
- 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)
- name String
- dataType ScoreDataType @map("data_type")
- isArchived Boolean @default(false) @map("is_archived")
- minValue Float? @map("min_value")
- maxValue Float? @map("max_value")
- categories Json? @map("categories")
- description String?
- score Score[]
-
- @@unique([id, projectId]) // used for upserts via prisma
- @@index([dataType])
- @@index([isArchived])
- @@index([projectId])
- @@index([categories])
- @@index([createdAt])
- @@index([updatedAt])
- @@map("score_configs")
+ 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)
+ name String
+ dataType ScoreDataType @map("data_type")
+ isArchived Boolean @default(false) @map("is_archived")
+ minValue Float? @map("min_value")
+ maxValue Float? @map("max_value")
+ categories Json? @map("categories")
+ description String?
+ score Score[]
+
+ @@unique([id, projectId]) // used for upserts via prisma
+ @@index([dataType])
+ @@index([isArchived])
+ @@index([projectId])
+ @@index([categories])
+ @@index([createdAt])
+ @@index([updatedAt])
+ @@map("score_configs")
}
enum ScoreDataType {
- CATEGORICAL
- NUMERIC
- BOOLEAN
+ CATEGORICAL
+ NUMERIC
+ BOOLEAN
+}
+
+model AnnotationQueue {
+ id String @id @default(cuid())
+ name String
+ description String?
+ scoreConfigIds String[] @default([]) @map("score_config_ids")
+ 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")
+ annotationQueueItem AnnotationQueueItem[]
+
+ @@unique([projectId, name])
+ @@index([id, projectId])
+ @@index([projectId, createdAt])
+ @@map("annotation_queues")
+}
+
+model AnnotationQueueItem {
+ id String @id @default(cuid())
+ queueId String @map("queue_id")
+ queue AnnotationQueue @relation(fields: [queueId], references: [id], onDelete: Cascade)
+ objectId String @map("object_id")
+ objectType AnnotationQueueObjectType @map("object_type")
+ status AnnotationQueueStatus @default(PENDING)
+ lockedAt DateTime? @map("locked_at")
+ lockedByUserId String? @map("locked_by_user_id")
+ lockedByUser User? @relation("LockedByUser", fields: [lockedByUserId], references: [id], onDelete: SetNull)
+ annotatorUserId String? @map("annotator_user_id")
+ annotatorUser User? @relation("AnnotatorUser", fields: [annotatorUserId], references: [id], onDelete: SetNull)
+ completedAt DateTime? @map("completed_at")
+ 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")
+
+ @@index([id, projectId])
+ @@index([projectId, queueId, status])
+ @@index([objectId, objectType, projectId, queueId])
+ @@index([annotatorUserId])
+ @@index([createdAt])
+ @@map("annotation_queue_items")
+}
+
+enum AnnotationQueueStatus {
+ PENDING
+ COMPLETED
+}
+
+enum AnnotationQueueObjectType {
+ TRACE
+ OBSERVATION
}
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 @default(cuid())
- projectId String @map("project_id")
- name String
- description String?
- metadata Json?
- 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[]
-
- @@id([id, projectId])
- @@unique([projectId, name])
- @@index([createdAt])
- @@index([updatedAt])
- @@map("datasets")
+ id String @default(cuid())
+ projectId String @map("project_id")
+ name String
+ description String?
+ metadata Json?
+ 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[]
+
+ @@id([id, projectId])
+ @@unique([projectId, name])
+ @@index([createdAt])
+ @@index([updatedAt])
+ @@map("datasets")
}
model DatasetItem {
- id String @default(cuid())
- projectId String @map("project_id")
- status DatasetStatus @default(ACTIVE)
- input Json?
- expectedOutput Json? @map("expected_output")
- metadata Json?
- sourceTraceId String? @map("source_trace_id")
- sourceObservationId String? @map("source_observation_id")
- datasetId String @map("dataset_id")
- dataset Dataset @relation(fields: [datasetId, projectId], references: [id, projectId], onDelete: Cascade)
- createdAt DateTime @default(now()) @map("created_at")
- updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
- datasetRunItems DatasetRunItems[]
-
- @@id([id, projectId])
- @@index([sourceTraceId], type: Hash)
- @@index([sourceObservationId], type: Hash)
- @@index([datasetId], type: Hash)
- @@index([createdAt])
- @@index([updatedAt])
- @@map("dataset_items")
+ id String @default(cuid())
+ projectId String @map("project_id")
+ status DatasetStatus @default(ACTIVE)
+ input Json?
+ expectedOutput Json? @map("expected_output")
+ metadata Json?
+ sourceTraceId String? @map("source_trace_id")
+ sourceObservationId String? @map("source_observation_id")
+ datasetId String @map("dataset_id")
+ dataset Dataset @relation(fields: [datasetId, projectId], references: [id, projectId], onDelete: Cascade)
+ createdAt DateTime @default(now()) @map("created_at")
+ updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
+ datasetRunItems DatasetRunItems[]
+
+ @@id([id, projectId])
+ @@index([sourceTraceId], type: Hash)
+ @@index([sourceObservationId], type: Hash)
+ @@index([datasetId], type: Hash)
+ @@index([createdAt])
+ @@index([updatedAt])
+ @@map("dataset_items")
}
enum DatasetStatus {
- ACTIVE
- ARCHIVED
+ ACTIVE
+ ARCHIVED
}
model DatasetRuns {
- id String @default(cuid())
- projectId String @map("project_id")
- name String
- description String?
- metadata Json?
- datasetId String @map("dataset_id")
- dataset Dataset @relation(fields: [datasetId, projectId], references: [id, projectId], onDelete: Cascade)
- createdAt DateTime @default(now()) @map("created_at")
- updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
- datasetRunItems DatasetRunItems[]
-
- @@id([id, projectId])
- @@unique([datasetId, projectId, name])
- @@index([datasetId], type: Hash)
- @@index([createdAt])
- @@index([updatedAt])
- @@map("dataset_runs")
+ id String @default(cuid())
+ projectId String @map("project_id")
+ name String
+ description String?
+ metadata Json?
+ datasetId String @map("dataset_id")
+ dataset Dataset @relation(fields: [datasetId, projectId], references: [id, projectId], onDelete: Cascade)
+ createdAt DateTime @default(now()) @map("created_at")
+ updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
+ datasetRunItems DatasetRunItems[]
+
+ @@id([id, projectId])
+ @@unique([datasetId, projectId, name])
+ @@index([datasetId], type: Hash)
+ @@index([createdAt])
+ @@index([updatedAt])
+ @@map("dataset_runs")
}
model DatasetRunItems {
- id String @default(cuid())
- projectId String @map("project_id")
- datasetRunId String @map("dataset_run_id")
- datasetRun DatasetRuns @relation(fields: [datasetRunId, projectId], references: [id, projectId], onDelete: Cascade)
- datasetItemId String @map("dataset_item_id")
- datasetItem DatasetItem @relation(fields: [datasetItemId, projectId], references: [id, projectId], onDelete: Cascade)
- traceId String @map("trace_id")
- observationId String? @map("observation_id")
- createdAt DateTime @default(now()) @map("created_at")
- updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
-
- @@id([id, projectId])
- @@index([datasetRunId], type: Hash)
- @@index([datasetItemId], type: Hash)
- @@index([observationId], type: Hash)
- @@index([traceId])
- @@index([createdAt])
- @@index([updatedAt])
- @@map("dataset_run_items")
+ id String @default(cuid())
+ projectId String @map("project_id")
+ datasetRunId String @map("dataset_run_id")
+ datasetRun DatasetRuns @relation(fields: [datasetRunId, projectId], references: [id, projectId], onDelete: Cascade)
+ datasetItemId String @map("dataset_item_id")
+ datasetItem DatasetItem @relation(fields: [datasetItemId, projectId], references: [id, projectId], onDelete: Cascade)
+ traceId String @map("trace_id")
+ observationId String? @map("observation_id")
+ createdAt DateTime @default(now()) @map("created_at")
+ updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
+
+ @@id([id, projectId])
+ @@index([datasetRunId], type: Hash)
+ @@index([datasetItemId], type: Hash)
+ @@index([observationId], type: Hash)
+ @@index([traceId])
+ @@index([createdAt])
+ @@index([updatedAt])
+ @@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?
+ 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")
+ @@index(projectId)
+ @@map("events")
}
model Comment {
- id String @id @default(cuid())
- projectId String @map("project_id")
- project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
- objectType CommentObjectType @map("object_type")
- objectId String @map("object_id")
- createdAt DateTime @default(now()) @map("created_at")
- updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
- content String
- authorUserId String? @map("author_user_id") // no fk constraint, user can be deleted
+ id String @id @default(cuid())
+ projectId String @map("project_id")
+ project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
+ objectType CommentObjectType @map("object_type")
+ objectId String @map("object_id")
+ createdAt DateTime @default(now()) @map("created_at")
+ updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
+ content String
+ authorUserId String? @map("author_user_id") // no fk constraint, user can be deleted
- @@index([projectId, objectType, objectId])
- @@map("comments")
+ @@index([projectId, objectType, objectId])
+ @@map("comments")
}
enum CommentObjectType {
- TRACE
- OBSERVATION
- SESSION
- PROMPT
+ TRACE
+ OBSERVATION
+ SESSION
+ PROMPT
}
model Prompt {
- id String @id @default(cuid())
- createdAt DateTime @default(now()) @map("created_at")
- updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
+ 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)
+ projectId String @map("project_id")
+ project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
- createdBy String @map("created_by")
+ createdBy String @map("created_by")
- prompt Json
- name String
- version Int
- type String @default("text")
- isActive Boolean? @map("is_active") // Deprecated. To be removed once 'production' labels work as expected.
- config Json @default("{}")
- tags String[] @default([])
- labels String[] @default([])
+ prompt Json
+ name String
+ version Int
+ type String @default("text")
+ isActive Boolean? @map("is_active") // Deprecated. To be removed once 'production' labels work as expected.
+ config Json @default("{}")
+ tags String[] @default([])
+ labels String[] @default([])
- @@unique([projectId, name, version])
- @@index([projectId, id])
- @@index([createdAt])
- @@index([updatedAt])
- @@index([tags(ops: ArrayOps)], type: Gin)
- @@map("prompts")
+ @@unique([projectId, name, version])
+ @@index([projectId, id])
+ @@index([createdAt])
+ @@index([updatedAt])
+ @@index([tags(ops: ArrayOps)], type: Gin)
+ @@map("prompts")
}
// Update ObservationView below when making changes to this model!
model Model {
- id String @id @default(cuid())
- createdAt DateTime @default(now()) @map("created_at")
- updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
+ 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)
+ projectId String? @map("project_id")
+ project Project? @relation(fields: [projectId], references: [id], onDelete: Cascade)
- modelName String @map("model_name")
- matchPattern String @map("match_pattern")
- startDate DateTime? @map("start_date")
- inputPrice Decimal? @map("input_price")
- outputPrice Decimal? @map("output_price")
- totalPrice Decimal? @map("total_price")
- unit String // TOKENS, CHARACTERS, MILLISECONDS, SECONDS, REQUESTS, or IMAGES
- tokenizerId String? @map("tokenizer_id")
- tokenizerConfig Json? @map("tokenizer_config")
+ modelName String @map("model_name")
+ matchPattern String @map("match_pattern")
+ startDate DateTime? @map("start_date")
+ inputPrice Decimal? @map("input_price")
+ outputPrice Decimal? @map("output_price")
+ totalPrice Decimal? @map("total_price")
+ unit String // TOKENS, CHARACTERS, MILLISECONDS, SECONDS, REQUESTS, or IMAGES
+ tokenizerId String? @map("tokenizer_id")
+ tokenizerConfig Json? @map("tokenizer_config")
- @@unique([projectId, modelName, startDate, unit])
- @@index(modelName)
- @@map("models")
+ @@unique([projectId, modelName, startDate, unit])
+ @@index(modelName)
+ @@map("models")
}
// No FK constraints to preserve audit logs
model AuditLog {
- id String @id @default(cuid())
- createdAt DateTime @default(now()) @map("created_at")
- updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
- userId String @map("user_id")
- orgId String @map("org_id")
- userOrgRole String @map("user_org_role")
- projectId String? @map("project_id")
- userProjectRole String? @map("user_project_role")
- resourceType String @map("resource_type")
- resourceId String @map("resource_id")
- action String
- before String? //stringified JSON
- after String? // stringified JSON
-
- @@index([projectId])
- @@index([userId])
- @@index([orgId])
- @@index([createdAt])
- @@index([updatedAt])
- @@map("audit_logs")
+ id String @id @default(cuid())
+ createdAt DateTime @default(now()) @map("created_at")
+ updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
+ userId String @map("user_id")
+ orgId String @map("org_id")
+ userOrgRole String @map("user_org_role")
+ projectId String? @map("project_id")
+ userProjectRole String? @map("user_project_role")
+ resourceType String @map("resource_type")
+ resourceId String @map("resource_id")
+ action String
+ before String? //stringified JSON
+ after String? // stringified JSON
+
+ @@index([projectId])
+ @@index([userId])
+ @@index([orgId])
+ @@index([createdAt])
+ @@index([updatedAt])
+ @@map("audit_logs")
}
model EvalTemplate {
- id String @id @default(cuid())
- createdAt DateTime @default(now()) @map("created_at")
- updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
+ 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)
+ projectId String @map("project_id")
+ project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
- name String
- version Int
- prompt String
- model String
- provider String
- modelParams Json @map("model_params")
- vars String[] @default([])
- outputSchema Json @map("output_schema")
- JobConfiguration JobConfiguration[]
+ name String
+ version Int
+ prompt String
+ model String
+ provider String
+ modelParams Json @map("model_params")
+ vars String[] @default([])
+ outputSchema Json @map("output_schema")
+ JobConfiguration JobConfiguration[]
- @@unique([projectId, name, version])
- @@index([projectId, id])
- @@map("eval_templates")
+ @@unique([projectId, name, version])
+ @@index([projectId, id])
+ @@map("eval_templates")
}
enum JobType {
- EVAL
+ EVAL
}
enum JobConfigState {
- ACTIVE
- INACTIVE
+ ACTIVE
+ INACTIVE
}
model JobConfiguration {
- id String @id @default(cuid())
- createdAt DateTime @default(now()) @map("created_at")
- updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
+ 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)
+ projectId String @map("project_id")
+ project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
- jobType JobType @map("job_type")
- status JobConfigState @default(ACTIVE)
- evalTemplateId String? @map("eval_template_id")
- evalTemplate EvalTemplate? @relation(fields: [evalTemplateId], references: [id], onDelete: SetNull)
+ jobType JobType @map("job_type")
+ status JobConfigState @default(ACTIVE)
+ evalTemplateId String? @map("eval_template_id")
+ evalTemplate EvalTemplate? @relation(fields: [evalTemplateId], references: [id], onDelete: SetNull)
- scoreName String @map("score_name")
- filter Json
- targetObject String @map("target_object")
- variableMapping Json @map("variable_mapping")
- sampling Decimal // ratio of jobs that are executed for sampling (0..1)
- delay Int // delay in milliseconds
- JobExecution JobExecution[]
+ scoreName String @map("score_name")
+ filter Json
+ targetObject String @map("target_object")
+ variableMapping Json @map("variable_mapping")
+ sampling Decimal // ratio of jobs that are executed for sampling (0..1)
+ delay Int // delay in milliseconds
+ JobExecution JobExecution[]
- @@index([projectId, id])
- @@map("job_configurations")
+ @@index([projectId, id])
+ @@map("job_configurations")
}
enum JobExecutionStatus {
- COMPLETED
- ERROR
- PENDING
- CANCELLED
+ COMPLETED
+ ERROR
+ PENDING
+ CANCELLED
}
model JobExecution {
- id String @id @default(cuid())
- createdAt DateTime @default(now()) @map("created_at")
- updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
+ 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)
+ projectId String @map("project_id")
+ project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
- jobConfigurationId String @map("job_configuration_id")
- jobConfiguration JobConfiguration @relation(fields: [jobConfigurationId], references: [id], onDelete: Cascade)
+ jobConfigurationId String @map("job_configuration_id")
+ jobConfiguration JobConfiguration @relation(fields: [jobConfigurationId], references: [id], onDelete: Cascade)
- status JobExecutionStatus
- startTime DateTime? @map("start_time")
- endTime DateTime? @map("end_time")
- error String?
+ status JobExecutionStatus
+ startTime DateTime? @map("start_time")
+ endTime DateTime? @map("end_time")
+ error String?
- jobInputTraceId String? @map("job_input_trace_id")
- trace Trace? @relation(fields: [jobInputTraceId], references: [id], onDelete: SetNull) // job remains when traces are deleted
+ jobInputTraceId String? @map("job_input_trace_id")
+ trace Trace? @relation(fields: [jobInputTraceId], references: [id], onDelete: SetNull) // job remains when traces are deleted
- jobOutputScoreId String? @map("job_output_score_id")
- score Score? @relation(fields: [jobOutputScoreId], references: [id], onDelete: SetNull) // job remains when scores are deleted
+ jobOutputScoreId String? @map("job_output_score_id")
+ score Score? @relation(fields: [jobOutputScoreId], references: [id], onDelete: SetNull) // job remains when scores are deleted
- @@index([projectId, status])
- @@index([projectId, id])
- @@index([jobConfigurationId])
- @@index([jobOutputScoreId])
- @@index([jobInputTraceId])
- @@index([createdAt])
- @@index([updatedAt])
- @@map("job_executions")
+ @@index([projectId, status])
+ @@index([projectId, id])
+ @@index([jobConfigurationId])
+ @@index([jobOutputScoreId])
+ @@index([jobInputTraceId])
+ @@index([createdAt])
+ @@index([updatedAt])
+ @@map("job_executions")
}
// Single Sign-On configuration for a domain
// This feature is part of the Enterprise Edition
model SsoConfig {
- domain String @id @default(cuid()) // e.g. "google.com"
- createdAt DateTime @default(now()) @map("created_at")
- updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
- authProvider String @map("auth_provider") // e.g. "okta", ee/sso/types.ts
+ domain String @id @default(cuid()) // e.g. "google.com"
+ createdAt DateTime @default(now()) @map("created_at")
+ updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
+ authProvider String @map("auth_provider") // e.g. "okta", ee/sso/types.ts
- authConfig Json? @map("auth_config")
- // e.g. { "clientId": "1234", "clientSecret": "5678" }, null if credentials from env should be used
- // secrets like clientSecret are encrypted on the application level
+ authConfig Json? @map("auth_config")
+ // e.g. { "clientId": "1234", "clientSecret": "5678" }, null if credentials from env should be used
+ // secrets like clientSecret are encrypted on the application level
- @@map("sso_configs")
+ @@map("sso_configs")
}
model PosthogIntegration {
- projectId String @id @map("project_id")
- project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
- encryptedPosthogApiKey String @map("encrypted_posthog_api_key")
- posthogHostName String @map("posthog_host_name")
- lastSyncAt DateTime? @map("last_sync_at")
- enabled Boolean
- createdAt DateTime @default(now()) @map("created_at")
+ projectId String @id @map("project_id")
+ project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
+ encryptedPosthogApiKey String @map("encrypted_posthog_api_key")
+ posthogHostName String @map("posthog_host_name")
+ lastSyncAt DateTime? @map("last_sync_at")
+ enabled Boolean
+ createdAt DateTime @default(now()) @map("created_at")
- @@map("posthog_integrations")
+ @@map("posthog_integrations")
}
model BatchExport {
- 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)
- userId String @map("user_id")
-
- finishedAt DateTime? @map("finished_at")
- expiresAt DateTime? @map("expires_at")
-
- name String
- status String
- query Json
- format String
- url String?
- log String?
-
- @@index([projectId, userId])
- @@index([status])
- @@map("batch_exports")
+ 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)
+ userId String @map("user_id")
+
+ finishedAt DateTime? @map("finished_at")
+ expiresAt DateTime? @map("expires_at")
+
+ name String
+ status String
+ query Json
+ format String
+ url String?
+ log String?
+
+ @@index([projectId, userId])
+ @@index([status])
+ @@map("batch_exports")
}
diff --git a/packages/shared/prisma/seed.ts b/packages/shared/prisma/seed.ts
index 7429e20bb8..9654262a75 100644
--- a/packages/shared/prisma/seed.ts
+++ b/packages/shared/prisma/seed.ts
@@ -5,6 +5,7 @@ import {
ObservationType,
ScoreSource,
ScoreDataType,
+ AnnotationQueueObjectType,
} from "../src/index";
import { hash } from "bcryptjs";
import { parseArgs } from "node:util";
@@ -77,6 +78,9 @@ async function main() {
create: {
id: seedOrgId,
name: "Seed Org",
+ cloudConfig: {
+ plan: "Team",
+ },
},
});
@@ -250,6 +254,11 @@ async function main() {
project2,
]);
+ const queueIds = await generateQueuesForProject(
+ [project1, project2],
+ configIdsAndNames
+ );
+
const promptIds = await generatePromptsForProject([project1, project2]);
const envTags = [null, "development", "staging", "production"];
@@ -257,19 +266,27 @@ async function main() {
const traceVolume = environment === "load" ? LOAD_TRACE_VOLUME : 100;
- const { traces, observations, scores, sessions, events, comments } =
- createObjects(
- traceVolume,
- envTags,
- colorTags,
- project1,
- project2,
- promptIds,
- configIdsAndNames,
- );
+ const {
+ traces,
+ observations,
+ scores,
+ sessions,
+ events,
+ comments,
+ queueItems,
+ } = createObjects(
+ traceVolume,
+ envTags,
+ colorTags,
+ project1,
+ project2,
+ promptIds,
+ queueIds,
+ configIdsAndNames
+ );
logger.info(
- `Seeding ${traces.length} traces, ${observations.length} observations, and ${scores.length} scores`,
+ `Seeding ${traces.length} traces, ${observations.length} observations, and ${scores.length} scores`
);
await uploadObjects(
@@ -279,6 +296,7 @@ async function main() {
sessions,
events,
comments,
+ queueItems
);
// If openai key is in environment, add it to the projects LLM API keys
@@ -296,7 +314,7 @@ async function main() {
});
} else {
logger.warn(
- "No OPENAI_API_KEY found in environment. Skipping seeding LLM API key.",
+ "No OPENAI_API_KEY found in environment. Skipping seeding LLM API key."
);
}
@@ -431,7 +449,7 @@ async function main() {
for (const datasetItemId of datasetItemIds) {
const relevantObservations = observations.filter(
- (o) => o.projectId === project2.id,
+ (o) => o.projectId === project2.id
);
const observation =
relevantObservations[
@@ -474,6 +492,7 @@ async function uploadObjects(
sessions: Prisma.TraceSessionCreateManyInput[],
events: Prisma.ObservationCreateManyInput[],
comments: Prisma.CommentCreateManyInput[],
+ queueItems: Prisma.AnnotationQueueItemCreateManyInput[]
) {
let promises: Prisma.PrismaPromise<unknown>[] = [];
@@ -487,14 +506,14 @@ async function uploadObjects(
},
create: chunk[0]!,
update: {},
- }),
+ })
);
});
for (let i = 0; i < promises.length; i++) {
if (i + 1 >= promises.length || i % Math.ceil(promises.length / 10) === 0)
logger.info(
- `Seeding of Sessions ${((i + 1) / promises.length) * 100}% complete`,
+ `Seeding of Sessions ${((i + 1) / promises.length) * 100}% complete`
);
await promises[i];
}
@@ -505,13 +524,13 @@ async function uploadObjects(
promises.push(
prisma.trace.createMany({
data: chunk,
- }),
+ })
);
});
for (let i = 0; i < promises.length; i++) {
if (i + 1 >= promises.length || i % Math.ceil(promises.length / 10) === 0)
logger.info(
- `Seeding of Traces ${((i + 1) / promises.length) * 100}% complete`,
+ `Seeding of Traces ${((i + 1) / promises.length) * 100}% complete`
);
await promises[i];
}
@@ -521,14 +540,14 @@ async function uploadObjects(
promises.push(
prisma.observation.createMany({
data: chunk,
- }),
+ })
);
});
for (let i = 0; i < promises.length; i++) {
if (i + 1 >= promises.length || i % Math.ceil(promises.length / 10) === 0)
logger.info(
- `Seeding of Observations ${((i + 1) / promises.length) * 100}% complete`,
+ `Seeding of Observations ${((i + 1) / promises.length) * 100}% complete`
);
await promises[i];
}
@@ -538,14 +557,14 @@ async function uploadObjects(
promises.push(
prisma.observation.createMany({
data: chunk,
- }),
+ })
);
});
for (let i = 0; i < promises.length; i++) {
if (i + 1 >= promises.length || i % Math.ceil(promises.length / 10) === 0)
logger.info(
- `Seeding of Events ${((i + 1) / promises.length) * 100}% complete`,
+ `Seeding of Events ${((i + 1) / promises.length) * 100}% complete`
);
await promises[i];
}
@@ -555,13 +574,13 @@ async function uploadObjects(
promises.push(
prisma.score.createMany({
data: chunk,
- }),
+ })
);
});
for (let i = 0; i < promises.length; i++) {
if (i + 1 >= promises.length || i % Math.ceil(promises.length / 10) === 0)
logger.info(
- `Seeding of Scores ${((i + 1) / promises.length) * 100}% complete`,
+ `Seeding of Scores ${((i + 1) / promises.length) * 100}% complete`
);
await promises[i];
}
@@ -571,13 +590,29 @@ async function uploadObjects(
promises.push(
prisma.comment.createMany({
data: chunk,
- }),
+ })
);
});
for (let i = 0; i < promises.length; i++) {
if (i + 1 >= promises.length || i % Math.ceil(promises.length / 10) === 0)
logger.info(
- `Seeding of Comments ${((i + 1) / promises.length) * 100}% complete`,
+ `Seeding of Comments ${((i + 1) / promises.length) * 100}% complete`
+ );
+ await promises[i];
+ }
+
+ promises = [];
+ chunk(queueItems, chunkSize).forEach((chunk) => {
+ promises.push(
+ prisma.annotationQueueItem.createMany({
+ data: chunk,
+ })
+ );
+ });
+ for (let i = 0; i < promises.length; i++) {
+ if (i + 1 >= promises.length || i % Math.ceil(promises.length / 10) === 0)
+ logger.info(
+ `Seeding of Annotation Queue Items ${((i + 1) / promises.length) * 100}% complete`
);
await promises[i];
}
@@ -590,6 +625,7 @@ function createObjects(
project1: Project,
project2: Project,
promptIds: Map<string, string[]>,
+ queueIds: Map<string, string[]>,
configParams: Map<
string,
{
@@ -598,7 +634,7 @@ function createObjects(
dataType: ScoreDataType;
categories: ConfigCategory[] | null;
}[]
- >,
+ >
) {
const traces: Prisma.TraceCreateManyInput[] = [];
const observations: Prisma.ObservationCreateManyInput[] = [];
@@ -607,12 +643,13 @@ function createObjects(
const events: Prisma.ObservationCreateManyInput[] = [];
const configs: Prisma.ScoreConfigCreateManyInput[] = [];
const comments: Prisma.CommentCreateManyInput[] = [];
+ const queueItems: Prisma.AnnotationQueueItemCreateManyInput[] = [];
for (let i = 0; i < traceVolume; i++) {
// print progress to console with a progress bar that refreshes every 10 iterations
// random date within last 90 days, with a linear bias towards more recent dates
const traceTs = new Date(
- Date.now() - Math.floor(Math.random() ** 1.5 * 90 * 24 * 60 * 60 * 1000),
+ Date.now() - Math.floor(Math.random() ** 1.5 * 90 * 24 * 60 * 60 * 1000)
);
const envTag = envTags[Math.floor(Math.random() * envTags.length)];
@@ -689,6 +726,23 @@ function createObjects(
}),
};
+ const queueItem = [
+ ...(Math.random() > 0.9
+ ? [
+ {
+ queueId: queueIds.get(projectId)?.[
+ Math.floor(Math.random() * 2)
+ ] as string,
+ objectId: trace.id,
+ objectType: AnnotationQueueObjectType.TRACE,
+ projectId,
+ },
+ ]
+ : []),
+ ];
+
+ queueItems.push(...queueItem);
+
const traceScores = [
...(Math.random() > 0.5
? [
@@ -753,11 +807,11 @@ function createObjects(
for (let j = 0; j < Math.floor(Math.random() * 10) + 1; j++) {
// add between 1 and 30 ms to trace timestamp
const spanTsStart = new Date(
- traceTs.getTime() + Math.floor(Math.random() * 30),
+ traceTs.getTime() + Math.floor(Math.random() * 30)
);
// random duration of upto 5000ms
const spanTsEnd = new Date(
- spanTsStart.getTime() + Math.floor(Math.random() * 5000),
+ spanTsStart.getTime() + Math.floor(Math.random() * 5000)
);
const span = {
@@ -792,22 +846,22 @@ function createObjects(
const generationTsStart = new Date(
spanTsStart.getTime() +
Math.floor(
- Math.random() * (spanTsEnd.getTime() - spanTsStart.getTime()),
- ),
+ Math.random() * (spanTsEnd.getTime() - spanTsStart.getTime())
+ )
);
const generationTsEnd = new Date(
generationTsStart.getTime() +
Math.floor(
Math.random() *
- (spanTsEnd.getTime() - generationTsStart.getTime()),
- ),
+ (spanTsEnd.getTime() - generationTsStart.getTime())
+ )
);
// somewhere in the middle
const generationTsCompletionStart = new Date(
generationTsStart.getTime() +
Math.floor(
- (generationTsEnd.getTime() - generationTsStart.getTime()) / 3,
- ),
+ (generationTsEnd.getTime() - generationTsStart.getTime()) / 3
+ )
);
const promptTokens = Math.floor(Math.random() * 1000) + 300;
@@ -828,7 +882,7 @@ function createObjects(
const promptId =
promptIds.get(projectId)![
Math.floor(
- Math.random() * Math.floor(promptIds.get(projectId)!.length / 2),
+ Math.random() * Math.floor(promptIds.get(projectId)!.length / 2)
)
];
@@ -910,8 +964,8 @@ function createObjects(
const eventTs = new Date(
spanTsStart.getTime() +
Math.floor(
- Math.random() * (spanTsEnd.getTime() - spanTsStart.getTime()),
- ),
+ Math.random() * (spanTsEnd.getTime() - spanTsStart.getTime())
+ )
);
events.push({
@@ -933,7 +987,7 @@ function createObjects(
}
// find unique sessions by id and projectid
const uniqueSessions: Prisma.TraceSessionCreateManyInput[] = Array.from(
- new Set(sessions.map((session) => JSON.stringify(session))),
+ new Set(sessions.map((session) => JSON.stringify(session)))
).map((session) => JSON.parse(session) as Prisma.TraceSessionCreateManyInput);
return {
@@ -941,6 +995,7 @@ function createObjects(
observations,
scores,
configs,
+ queueItems,
sessions: uniqueSessions,
events,
comments,
@@ -954,7 +1009,7 @@ async function generatePromptsForProject(projects: Project[]) {
projects.map(async (project) => {
const promptIdsForProject = await generatePrompts(project);
promptIds.set(project.id, promptIdsForProject);
- }),
+ })
);
return promptIds;
}
@@ -1140,7 +1195,7 @@ async function generateConfigsForProject(projects: Project[]) {
projects.map(async (project) => {
const configNameAndId = await generateConfigs(project);
projectIdsToConfigs.set(project.id, configNameAndId);
- }),
+ })
);
return projectIdsToConfigs;
}
@@ -1218,6 +1273,7 @@ async function generateConfigs(project: Project) {
return configNameAndId;
}
+
function getGenerationInputOutput(): {
input: Prisma.InputJsonValue;
output: Prisma.InputJsonValue;
@@ -1278,3 +1334,77 @@ function getGenerationInputOutput(): {
return { input, output };
}
+
+async function generateQueuesForProject(
+ projects: Project[],
+ configIdsAndNames: Map<
+ string,
+ {
+ name: string;
+ id: string;
+ dataType: ScoreDataType;
+ categories: ConfigCategory[] | null;
+ }[]
+ >
+) {
+ const projectIdsToQueues: Map<string, string[]> = new Map();
+
+ await Promise.all(
+ projects.map(async (project) => {
+ const queueIds = await generateQueues(
+ project,
+ configIdsAndNames.get(project.id) ?? []
+ );
+ projectIdsToQueues.set(project.id, queueIds);
+ })
+ );
+ return projectIdsToQueues;
+}
+
+async function generateQueues(
+ project: Project,
+ configIdsAndNames: {
+ name: string;
+ id: string;
+ dataType: ScoreDataType;
+ categories: ConfigCategory[] | null;
+ }[]
+) {
+ const queueIds: string[] = [];
+
+ const queues = [
+ {
+ id: `queue-${v4()}`,
+ name: "Default",
+ description: "Default queue",
+ scoreConfigIds: configIdsAndNames.map((config) => config.id),
+ projectId: project.id,
+ },
+ {
+ id: `queue-${v4()}`,
+ name: "Correction",
+ scoreConfigIds: [configIdsAndNames[0].id],
+ projectId: project.id,
+ },
+ ];
+
+ for (const queue of queues) {
+ await prisma.annotationQueue.upsert({
+ where: {
+ projectId_name: {
+ projectId: queue.projectId,
+ name: queue.name,
+ },
+ },
+ create: {
+ ...queue,
+ },
+ update: {
+ id: queue.id,
+ },
+ });
+ queueIds.push(queue.id);
+ }
+
+ return queueIds;
+}
diff --git a/packages/shared/src/features/annotation/types.ts b/packages/shared/src/features/annotation/types.ts
index f5ab0dab74..4733798005 100644
--- a/packages/shared/src/features/annotation/types.ts
+++ b/packages/shared/src/features/annotation/types.ts
@@ -32,6 +32,7 @@ const CreateAnnotationScoreBase = z.object({
configId: z.string().optional(),
observationId: z.string().optional(),
comment: z.string().nullish(),
+ queueId: z.string().nullish(),
});
const UpdateAnnotationScoreBase = CreateAnnotationScoreBase.extend({
@@ -57,3 +58,15 @@ export const UpdateAnnotationScoreData = z.discriminatedUnion("dataType", [
UpdateAnnotationScoreBase.merge(CategoricalData),
UpdateAnnotationScoreBase.merge(BooleanData),
]);
+
+// annotation queues
+
+export const CreateQueueData = z.object({
+ name: z.string().min(1).max(35),
+ description: z.string().max(1000).optional(),
+ scoreConfigIds: z.array(z.string()).min(1, {
+ message: "At least 1 score config must be selected",
+ }),
+});
+
+export type CreateQueue = z.infer<typeof CreateQueueData>;
diff --git a/web/src/components/layouts/routes.tsx b/web/src/components/layouts/routes.tsx
index bbf2a247f7..bde6386bf2 100644
--- a/web/src/components/layouts/routes.tsx
+++ b/web/src/components/layouts/routes.tsx
@@ -14,6 +14,7 @@ import {
Lightbulb,
Grid2X2,
Sparkle,
+ ClipboardPen,
} from "lucide-react";
import { LangfuseIcon } from "@/src/components/LangfuseLogo";
import { type ReactNode } from "react";
@@ -86,6 +87,15 @@ export const ROUTES: Route[] = [
},
],
},
+ {
+ name: "Annotation Queues",
+ pathname: `/project/[projectId]/annotation-queues`,
+ icon: ClipboardPen,
+ label: "Beta",
+ projectRbacScope: "annotationQueues:read",
+ entitlement: "annotation-queues",
+ featureFlag: "annotationQueues",
+ },
{
name: "Evaluation",
icon: Lightbulb,
diff --git a/web/src/components/layouts/status-badge.tsx b/web/src/components/layouts/status-badge.tsx
index a776b75f39..94412bf6f8 100644
--- a/web/src/components/layouts/status-badge.tsx
+++ b/web/src/components/layouts/status-badge.tsx
@@ -11,32 +11,35 @@ const statusCategories = {
export type Status =
(typeof statusCategories)[keyof typeof statusCategories][number];
-export const StatusBadge = (props: {
- className?: string;
+export const StatusBadge = ({
+ type,
+ isLive = true,
+ className,
+}: {
type: Status | (string & {});
+ isLive?: boolean;
+ className?: string;
}) => {
let badgeColor = "bg-muted-gray text-primary";
let dotColor = "bg-muted-foreground";
let dotPingColor = "bg-muted-foreground";
- let showDot = false;
+ let showDot = isLive;
- if (statusCategories.active.includes(props.type)) {
+ if (statusCategories.active.includes(type)) {
badgeColor = "bg-light-green text-dark-green";
dotColor = "animate-ping bg-dark-green";
dotPingColor = "bg-dark-green";
- showDot = true;
- } else if (statusCategories.pending.includes(props.type)) {
+ } else if (statusCategories.pending.includes(type)) {
badgeColor = "bg-light-yellow text-dark-yellow";
dotColor = "animate-ping bg-dark-yellow";
dotPingColor = "bg-dark-yellow";
- showDot = true;
- } else if (statusCategories.error.includes(props.type)) {
+ } else if (statusCategories.error.includes(type)) {
badgeColor = "bg-light-red text-dark-red";
dotColor = "animate-ping bg-dark-red";
dotPingColor = "bg-dark-red";
- showDot = true;
- } else if (statusCategories.completed.includes(props.type)) {
+ } else if (statusCategories.completed.includes(type)) {
badgeColor = "bg-light-green text-dark-green";
+ showDot = false;
}
return (
@@ -44,26 +47,26 @@ export const StatusBadge = (props: {
className={cn(
"inline-flex items-center gap-2 rounded-sm px-2 py-1 text-xs",
badgeColor,
- props.className,
+ className,
)}
>
{showDot && (
<span className="relative inline-flex h-2 w-2">
<span
className={cn(
- "absolute inline-flex h-full w-full rounded-full opacity-75",
+ "absolute inline-flex h-full w-full rounded-full opacity-75",
dotColor,
)}
></span>
<span
className={cn(
- "relative inline-flex h-2 w-2 rounded-full ",
+ "relative inline-flex h-2 w-2 rounded-full",
dotPingColor,
)}
></span>
</span>
)}
- <span>{props.type}</span>
+ <span>{type}</span>
</div>
);
};
diff --git a/web/src/components/table/data-table-multi-select-actions/trace-table-multi-select-action.tsx b/web/src/components/table/data-table-multi-select-actions/trace-table-multi-select-action.tsx
index 553841f03b..04cddc6772 100644
--- a/web/src/components/table/data-table-multi-select-actions/trace-table-multi-select-action.tsx
+++ b/web/src/components/table/data-table-multi-select-actions/trace-table-multi-select-action.tsx
@@ -1,4 +1,4 @@
-import { ChevronDown, Trash } from "lucide-react";
+import { ChevronDown, ClipboardPen, Trash } from "lucide-react";
import {
DropdownMenu,
@@ -20,6 +20,30 @@ import {
} from "@/src/components/ui/dialog";
import { useState } from "react";
import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
+import {
+ Select,
+ SelectTrigger,
+ SelectContent,
+ SelectItem,
+ SelectValue,
+} from "@/src/components/ui/select";
+import { showSuccessToast } from "@/src/features/notifications/showSuccessToast";
+import {
+ Form,
+ FormControl,
+ FormField,
+ FormItem,
+ FormMessage,
+} from "@/src/components/ui/form";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { useForm } from "react-hook-form";
+import { z } from "zod";
+import { useSession } from "next-auth/react";
+import { useHasOrgEntitlement } from "@/src/features/entitlements/hooks";
+
+const addToQueueFormSchema = z.object({
+ queueId: z.string(),
+});
export function TraceTableMultiSelectAction({
selectedTraceIds,
@@ -31,7 +55,9 @@ export function TraceTableMultiSelectAction({
onDeleteSuccess: () => void;
}) {
const utils = api.useUtils();
- const [open, setOpen] = useState(false);
+ const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
+ const [addToQueueDialogOpen, setAddToQueueDialogOpen] = useState(false);
+ const session = useSession();
const capture = usePostHogClientCapture();
const hasDeleteAccess = useHasProjectAccess({
@@ -45,6 +71,35 @@ export function TraceTableMultiSelectAction({
},
});
+ const hasEntitlement = useHasOrgEntitlement("annotation-queues");
+ const hasAddToQueueAccess = useHasProjectAccess({
+ projectId,
+ scope: "annotationQueues:CUD",
+ });
+ const mutAddToQueue = api.annotationQueueItems.createMany.useMutation({
+ onSuccess: (data) => {
+ showSuccessToast({
+ title: "Traces added to queue",
+ description: `${selectedTraceIds.length} traces added to queue "${data.queueName}".`,
+ link: {
+ href: `/project/${projectId}/annotation-queues/${data.queueId}`,
+ text: `View queue "${data.queueName}"`,
+ },
+ });
+ },
+ });
+
+ const form = useForm<z.infer<typeof addToQueueFormSchema>>({
+ resolver: zodResolver(addToQueueFormSchema),
+ });
+
+ const queues = api.annotationQueues.allNamesAndIds.useQuery(
+ {
+ projectId,
+ },
+ { enabled: session.status === "authenticated" && hasEntitlement },
+ );
+
return (
<>
<DropdownMenu>
@@ -62,19 +117,31 @@ export function TraceTableMultiSelectAction({
count: selectedTraceIds.length,
source: "table-multi-select",
});
- setOpen(true);
+ setDeleteDialogOpen(true);
}}
>
<Trash className="mr-2 h-4 w-4" />
<span>Delete</span>
</DropdownMenuItem>
+ {hasEntitlement && (
+ <DropdownMenuItem
+ disabled={!hasAddToQueueAccess}
+ onClick={() => {
+ setAddToQueueDialogOpen(true);
+ }}
+ >
+ <ClipboardPen className="mr-2 h-4 w-4" />
+ <span>Add to Annotation Queue</span>
+ </DropdownMenuItem>
+ )}
</DropdownMenuContent>
</DropdownMenu>
+
<Dialog
- open={open}
+ open={deleteDialogOpen}
onOpenChange={(isOpen) => {
if (!isOpen) {
- setOpen(false);
+ setDeleteDialogOpen(false);
}
}}
>
@@ -99,7 +166,7 @@ export function TraceTableMultiSelectAction({
projectId,
})
.then(() => {
- setOpen(false);
+ setDeleteDialogOpen(false);
});
capture("trace:delete_form_submit", {
count: selectedTraceIds.length,
@@ -112,6 +179,79 @@ export function TraceTableMultiSelectAction({
</DialogFooter>
</DialogContent>
</Dialog>
+
+ <Dialog
+ open={addToQueueDialogOpen}
+ onOpenChange={(isOpen) => {
+ if (!isOpen) {
+ setAddToQueueDialogOpen(false);
+ }
+ }}
+ >
+ <DialogContent className="sm:max-w-md">
+ <Form {...form}>
+ <form
+ className="space-y-6"
+ onSubmit={form.handleSubmit((data) => {
+ if (data.queueId) {
+ void mutAddToQueue
+ .mutateAsync({
+ projectId,
+ queueId: data.queueId,
+ objectIds: selectedTraceIds,
+ objectType: "TRACE",
+ })
+ .then(() => {
+ setAddToQueueDialogOpen(false);
+ });
+ }
+ })}
+ >
+ <DialogHeader>
+ <DialogTitle>Add to Annotation Queue</DialogTitle>
+ <DialogDescription>
+ Select an annotation queue to add the selected traces to.
+ </DialogDescription>
+ </DialogHeader>
+ <FormField
+ control={form.control}
+ name="queueId"
+ render={({ field }) => (
+ <FormItem>
+ <Select
+ onValueChange={field.onChange}
+ defaultValue={field.value}
+ >
+ <FormControl>
+ <SelectTrigger>
+ <SelectValue placeholder="Select a queue" />
+ </SelectTrigger>
+ </FormControl>
+ <SelectContent>
+ {queues?.data?.map((queue) => (
+ <SelectItem key={queue.id} value={queue.id}>
+ {queue.name}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ <DialogFooter className="sm:justify-start">
+ <Button
+ type="submit"
+ loading={mutAddToQueue.isLoading}
+ disabled={mutAddToQueue.isLoading}
+ >
+ Add {selectedTraceIds.length} trace(s) to queue
+ </Button>
+ </DialogFooter>
+ </form>
+ </Form>
+ </DialogContent>
+ </Dialog>
</>
);
}
diff --git a/web/src/components/trace/ObservationPreview.tsx b/web/src/components/trace/ObservationPreview.tsx
index 17aca302dd..178f6f6843 100644
--- a/web/src/components/trace/ObservationPreview.tsx
+++ b/web/src/components/trace/ObservationPreview.tsx
@@ -1,5 +1,9 @@
import { JSONView } from "@/src/components/ui/CodeJsonViewer";
-import { type APIScore, type ScoreSource } from "@langfuse/shared";
+import {
+ AnnotationQueueObjectType,
+ type APIScore,
+ type ScoreSource,
+} from "@langfuse/shared";
import {
Card,
CardContent,
@@ -8,7 +12,6 @@ import {
CardTitle,
} from "@/src/components/ui/card";
import { Badge } from "@/src/components/ui/badge";
-import { NewDatasetItemFromTrace } from "@/src/features/datasets/components/NewDatasetItemFromObservationButton";
import { type ObservationReturnType } from "@/src/server/api/routers/traces";
import { api } from "@/src/utils/api";
import { IOPreview } from "@/src/components/trace/IOPreview";
@@ -23,16 +26,31 @@ import { JumpToPlaygroundButton } from "@/src/ee/features/playground/page/compon
import { AnnotateDrawer } from "@/src/features/scores/components/AnnotateDrawer";
import useLocalStorage from "@/src/components/useLocalStorage";
import { CommentDrawerButton } from "@/src/features/comments/CommentDrawerButton";
+import { cn } from "@/src/utils/tailwind";
+import { NewDatasetItemFromTrace } from "@/src/features/datasets/components/NewDatasetItemFromObservationButton";
+import { CreateNewAnnotationQueueItem } from "@/src/features/scores/components/CreateNewAnnotationQueueItem";
+import { useHasOrgEntitlement } from "@/src/features/entitlements/hooks";
import { calculateDisplayTotalCost } from "@/src/components/trace/lib/helpers";
import { useMemo } from "react";
-export const ObservationPreview = (props: {
+export const ObservationPreview = ({
+ observations,
+ projectId,
+ scores,
+ currentObservationId,
+ traceId,
+ commentCounts,
+ viewType = "detailed",
+ className,
+}: {
observations: Array<ObservationReturnType>;
projectId: string;
scores: APIScore[];
currentObservationId: string;
traceId: string;
commentCounts?: Map<string, number>;
+ viewType?: "focused" | "detailed";
+ className?: string;
}) => {
const [selectedTab, setSelectedTab] = useQueryParam(
"view",
@@ -41,15 +59,16 @@ export const ObservationPreview = (props: {
const [emptySelectedConfigIds, setEmptySelectedConfigIds] = useLocalStorage<
string[]
>("emptySelectedConfigIds", []);
+ const hasEntitlement = useHasOrgEntitlement("annotation-queues");
const observationWithInputAndOutput = api.observations.byId.useQuery({
- observationId: props.currentObservationId,
- traceId: props.traceId,
- projectId: props.projectId,
+ observationId: currentObservationId,
+ traceId: traceId,
+ projectId: projectId,
});
- const preloadedObservation = props.observations.find(
- (o) => o.id === props.currentObservationId,
+ const preloadedObservation = observations.find(
+ (o) => o.id === currentObservationId,
);
const thisCost = preloadedObservation
@@ -61,15 +80,15 @@ export const ObservationPreview = (props: {
const totalCost = useMemo(
() =>
calculateDisplayTotalCost({
- allObservations: props.observations,
- rootObservationId: props.currentObservationId,
+ allObservations: observations,
+ rootObservationId: currentObservationId,
}),
- [props.observations, props.currentObservationId],
+ [observations, currentObservationId],
);
if (!preloadedObservation) return <div className="flex-1">Not found</div>;
- const observationScores = props.scores.filter(
+ const observationScores = scores.filter(
(s) => s.observationId === preloadedObservation.id,
);
const observationScoresBySource = observationScores.reduce((acc, score) => {
@@ -81,29 +100,36 @@ export const ObservationPreview = (props: {
}, new Map<ScoreSource, APIScore[]>());
return (
- <Card className="col-span-2 flex max-h-full flex-col overflow-hidden">
- <div className="flex flex-shrink-0 flex-row justify-end gap-2">
- <Tabs
- value={selectedTab}
- onValueChange={setSelectedTab}
- className="flex w-full justify-end border-b bg-background"
- >
- <TabsList className="bg-background py-0">
- <TabsTrigger
- value="preview"
- className="h-full rounded-none border-b-4 border-transparent data-[state=active]:border-primary-accent data-[state=active]:shadow-none"
- >
- Preview
- </TabsTrigger>
- <TabsTrigger
- value="scores"
- className="h-full rounded-none border-b-4 border-transparent data-[state=active]:border-primary-accent data-[state=active]:shadow-none"
- >
- Scores
- </TabsTrigger>
- </TabsList>
- </Tabs>
- </div>
+ <Card
+ className={cn(
+ "col-span-2 flex max-h-full flex-col overflow-hidden",
+ className,
+ )}
+ >
+ {viewType === "detailed" && (
+ <div className="flex flex-shrink-0 flex-row justify-end gap-2">
+ <Tabs
+ value={selectedTab}
+ onValueChange={setSelectedTab}
+ className="flex w-full justify-end border-b bg-background"
+ >
+ <TabsList className="bg-background py-0">
+ <TabsTrigger
+ value="preview"
+ className="h-full rounded-none border-b-4 border-transparent data-[state=active]:border-primary-accent data-[state=active]:shadow-none"
+ >
+ Preview
+ </TabsTrigger>
+ <TabsTrigger
+ value="scores"
+ className="h-full rounded-none border-b-4 border-transparent data-[state=active]:border-primary-accent data-[state=active]:shadow-none"
+ >
+ Scores
+ </TabsTrigger>
+ </TabsList>
+ </Tabs>
+ </div>
+ )}
<div className="flex w-full flex-col overflow-y-auto">
<CardHeader className="flex flex-row flex-wrap justify-between gap-2">
<div className="flex flex-col gap-1">
@@ -116,107 +142,123 @@ export const ObservationPreview = (props: {
<CardDescription className="flex gap-2">
{preloadedObservation.startTime.toLocaleString()}
</CardDescription>
+ {viewType === "detailed" && (
+ <div className="flex flex-wrap gap-2">
+ {preloadedObservation.promptId ? (
+ <PromptBadge
+ promptId={preloadedObservation.promptId}
+ projectId={preloadedObservation.projectId}
+ />
+ ) : undefined}
+ {preloadedObservation.timeToFirstToken ? (
+ <Badge variant="outline">
+ Time to first token:{" "}
+ {formatIntervalSeconds(
+ preloadedObservation.timeToFirstToken,
+ )}
+ </Badge>
+ ) : null}
+ {preloadedObservation.endTime ? (
+ <Badge variant="outline">
+ Latency:{" "}
+ {formatIntervalSeconds(
+ (preloadedObservation.endTime.getTime() -
+ preloadedObservation.startTime.getTime()) /
+ 1000,
+ )}
+ </Badge>
+ ) : null}
+ {preloadedObservation.type === "GENERATION" && (
+ <Badge variant="outline">
+ {preloadedObservation.promptTokens} prompt →{" "}
+ {preloadedObservation.completionTokens} completion (∑{" "}
+ {preloadedObservation.totalTokens})
+ </Badge>
+ )}
+ {preloadedObservation.version ? (
+ <Badge variant="outline">
+ Version: {preloadedObservation.version}
+ </Badge>
+ ) : undefined}
+ {preloadedObservation.model ? (
+ <Badge variant="outline">{preloadedObservation.model}</Badge>
+ ) : null}
+ {thisCost ? (
+ <Badge variant="outline">
+ {usdFormatter(thisCost.toNumber())}
+ </Badge>
+ ) : undefined}
+ {totalCost && totalCost !== thisCost ? (
+ <Badge variant="outline">
+ ∑ {usdFormatter(totalCost.toNumber())}
+ </Badge>
+ ) : undefined}
+
+ {preloadedObservation.modelParameters &&
+ typeof preloadedObservation.modelParameters === "object"
+ ? Object.entries(preloadedObservation.modelParameters)
+ .filter(Boolean)
+ .map(([key, value]) => (
+ <Badge variant="outline" key={key}>
+ {key}:{" "}
+ {Object.prototype.toString.call(value) ===
+ "[object Object]"
+ ? JSON.stringify(value)
+ : value?.toString()}
+ </Badge>
+ ))
+ : null}
+ </div>
+ )}
+ </div>
+ {viewType === "detailed" && (
<div className="flex flex-wrap gap-2">
- {preloadedObservation.promptId ? (
- <PromptBadge
- promptId={preloadedObservation.promptId}
- projectId={preloadedObservation.projectId}
+ <CommentDrawerButton
+ projectId={preloadedObservation.projectId}
+ objectId={preloadedObservation.id}
+ objectType="OBSERVATION"
+ count={commentCounts?.get(preloadedObservation.id)}
+ />
+ <div className="flex items-start">
+ <AnnotateDrawer
+ projectId={projectId}
+ traceId={traceId}
+ observationId={preloadedObservation.id}
+ scores={scores}
+ emptySelectedConfigIds={emptySelectedConfigIds}
+ setEmptySelectedConfigIds={setEmptySelectedConfigIds}
+ type="observation"
+ key={"annotation-drawer" + preloadedObservation.id}
+ />
+ {hasEntitlement && (
+ <CreateNewAnnotationQueueItem
+ projectId={projectId}
+ objectId={preloadedObservation.id}
+ objectType={AnnotationQueueObjectType.OBSERVATION}
+ />
+ )}
+ </div>
+
+ {observationWithInputAndOutput.data?.type === "GENERATION" && (
+ <JumpToPlaygroundButton
+ source="generation"
+ generation={observationWithInputAndOutput.data}
+ analyticsEventName="trace_detail:test_in_playground_button_click"
/>
- ) : undefined}
- {preloadedObservation.timeToFirstToken ? (
- <Badge variant="outline">
- Time to first token:{" "}
- {formatIntervalSeconds(preloadedObservation.timeToFirstToken)}
- </Badge>
- ) : null}
- {preloadedObservation.endTime ? (
- <Badge variant="outline">
- Latency:{" "}
- {formatIntervalSeconds(
- (preloadedObservation.endTime.getTime() -
- preloadedObservation.startTime.getTime()) /
- 1000,
- )}
- </Badge>
- ) : null}
- {preloadedObservation.type === "GENERATION" && (
- <Badge variant="outline">
- {preloadedObservation.promptTokens} prompt →{" "}
- {preloadedObservation.completionTokens} completion (∑{" "}
- {preloadedObservation.totalTokens})
- </Badge>
)}
- {preloadedObservation.version ? (
- <Badge variant="outline">
- Version: {preloadedObservation.version}
- </Badge>
- ) : undefined}
- {preloadedObservation.model ? (
- <Badge variant="outline">{preloadedObservation.model}</Badge>
+ {observationWithInputAndOutput.data ? (
+ <NewDatasetItemFromTrace
+ traceId={preloadedObservation.traceId}
+ observationId={preloadedObservation.id}
+ projectId={projectId}
+ input={observationWithInputAndOutput.data.input}
+ output={observationWithInputAndOutput.data.output}
+ metadata={preloadedObservation.metadata}
+ key={preloadedObservation.id}
+ />
) : null}
- {thisCost ? (
- <Badge variant="outline">
- {usdFormatter(thisCost.toNumber())}
- </Badge>
- ) : undefined}
- {totalCost && totalCost !== thisCost ? (
- <Badge variant="outline">
- ∑ {usdFormatter(totalCost.toNumber())}
- </Badge>
- ) : undefined}
-
- {preloadedObservation.modelParameters &&
- typeof preloadedObservation.modelParameters === "object"
- ? Object.entries(preloadedObservation.modelParameters)
- .filter(Boolean)
- .map(([key, value]) => (
- <Badge variant="outline" key={key}>
- {key}:{" "}
- {Object.prototype.toString.call(value) ===
- "[object Object]"
- ? JSON.stringify(value)
- : value?.toString()}
- </Badge>
- ))
- : null}
</div>
- </div>
- <div className="flex flex-wrap gap-2">
- <CommentDrawerButton
- projectId={preloadedObservation.projectId}
- objectId={preloadedObservation.id}
- objectType="OBSERVATION"
- count={props.commentCounts?.get(preloadedObservation.id)}
- />
- <AnnotateDrawer
- projectId={props.projectId}
- traceId={preloadedObservation.traceId}
- observationId={preloadedObservation.id}
- scores={props.scores}
- emptySelectedConfigIds={emptySelectedConfigIds}
- setEmptySelectedConfigIds={setEmptySelectedConfigIds}
- type="observation"
- key={"annotation-drawer" + preloadedObservation.id}
- />
- {observationWithInputAndOutput.data?.type === "GENERATION" && (
- <JumpToPlaygroundButton
- source="generation"
- generation={observationWithInputAndOutput.data}
- analyticsEventName="trace_detail:test_in_playground_button_click"
- />
- )}
- {observationWithInputAndOutput.data ? (
- <NewDatasetItemFromTrace
- traceId={preloadedObservation.traceId}
- observationId={preloadedObservation.id}
- projectId={props.projectId}
- input={observationWithInputAndOutput.data.input}
- output={observationWithInputAndOutput.data.output}
- metadata={preloadedObservation.metadata}
- key={preloadedObservation.id}
- />
- ) : null}
- </div>
+ )}
</CardHeader>
<CardContent className="flex flex-col gap-4">
{selectedTab === "preview" && (
@@ -241,12 +283,14 @@ export const ObservationPreview = (props: {
json={observationWithInputAndOutput.data.metadata}
/>
) : null}
- <ScoresPreview itemScoresBySource={observationScoresBySource} />
+ {viewType === "detailed" && (
+ <ScoresPreview itemScoresBySource={observationScoresBySource} />
+ )}
</>
)}
{selectedTab === "scores" && (
<ScoresTable
- projectId={props.projectId}
+ projectId={projectId}
omittedFilter={["Observation ID"]}
observationId={preloadedObservation.id}
hiddenColumns={[
diff --git a/web/src/components/trace/TracePreview.tsx b/web/src/components/trace/TracePreview.tsx
index 695a99a2f2..78d748b0ec 100644
--- a/web/src/components/trace/TracePreview.tsx
+++ b/web/src/components/trace/TracePreview.tsx
@@ -1,5 +1,10 @@
import { JSONView } from "@/src/components/ui/CodeJsonViewer";
-import { type APIScore, type Trace, type ScoreSource } from "@langfuse/shared";
+import {
+ type APIScore,
+ type Trace,
+ type ScoreSource,
+ AnnotationQueueObjectType,
+} from "@langfuse/shared";
import {
Card,
CardContent,
@@ -13,7 +18,6 @@ import { Badge } from "@/src/components/ui/badge";
import { type ObservationReturnType } from "@/src/server/api/routers/traces";
import { IOPreview } from "@/src/components/trace/IOPreview";
import { formatIntervalSeconds } from "@/src/utils/dates";
-import { NewDatasetItemFromTrace } from "@/src/features/datasets/components/NewDatasetItemFromObservationButton";
import { Tabs, TabsList, TabsTrigger } from "@/src/components/ui/tabs";
import { withDefault, StringParam, useQueryParam } from "use-query-params";
import ScoresTable from "@/src/components/table/use-cases/scores";
@@ -21,6 +25,10 @@ import { ScoresPreview } from "@/src/components/trace/ScoresPreview";
import { AnnotateDrawer } from "@/src/features/scores/components/AnnotateDrawer";
import useLocalStorage from "@/src/components/useLocalStorage";
import { CommentDrawerButton } from "@/src/features/comments/CommentDrawerButton";
+import { cn } from "@/src/utils/tailwind";
+import { NewDatasetItemFromTrace } from "@/src/features/datasets/components/NewDatasetItemFromObservationButton";
+import { CreateNewAnnotationQueueItem } from "@/src/features/scores/components/CreateNewAnnotationQueueItem";
+import { useHasOrgEntitlement } from "@/src/features/entitlements/hooks";
import { useMemo } from "react";
import { usdFormatter } from "@/src/utils/numbers";
import { calculateDisplayTotalCost } from "@/src/components/trace/lib/helpers";
@@ -30,11 +38,15 @@ export const TracePreview = ({
observations,
scores,
commentCounts,
+ viewType = "detailed",
+ className,
}: {
trace: Trace & { latency?: number };
observations: ObservationReturnType[];
scores: APIScore[];
commentCounts?: Map<string, number>;
+ viewType?: "detailed" | "focused";
+ className?: string;
}) => {
const [selectedTab, setSelectedTab] = useQueryParam(
"view",
@@ -43,6 +55,7 @@ export const TracePreview = ({
const [emptySelectedConfigIds, setEmptySelectedConfigIds] = useLocalStorage<
string[]
>("emptySelectedConfigIds", []);
+ const hasEntitlement = useHasOrgEntitlement("annotation-queues");
const traceScores = scores.filter((s) => s.observationId === null);
const traceScoresBySource = traceScores.reduce((acc, score) => {
@@ -62,29 +75,36 @@ export const TracePreview = ({
);
return (
- <Card className="col-span-2 flex max-h-full flex-col overflow-hidden">
- <div className="flex flex-shrink-0 flex-row justify-end gap-2">
- <Tabs
- value={selectedTab}
- onValueChange={setSelectedTab}
- className="flex w-full justify-end border-b bg-background"
- >
- <TabsList className="bg-background py-0">
- <TabsTrigger
- value="preview"
- className="h-full rounded-none border-b-4 border-transparent data-[state=active]:border-primary-accent data-[state=active]:shadow-none"
- >
- Preview
- </TabsTrigger>
- <TabsTrigger
- value="scores"
- className="h-full rounded-none border-b-4 border-transparent data-[state=active]:border-primary-accent data-[state=active]:shadow-none"
- >
- Scores
- </TabsTrigger>
- </TabsList>
- </Tabs>
- </div>
+ <Card
+ className={cn(
+ "col-span-2 flex max-h-full flex-col overflow-hidden",
+ className,
+ )}
+ >
+ {viewType === "detailed" && (
+ <div className="flex flex-shrink-0 flex-row justify-end gap-2">
+ <Tabs
+ value={selectedTab}
+ onValueChange={setSelectedTab}
+ className="flex w-full justify-end border-b bg-background"
+ >
+ <TabsList className="bg-background py-0">
+ <TabsTrigger
+ value="preview"
+ className="h-full rounded-none border-b-4 border-transparent data-[state=active]:border-primary-accent data-[state=active]:shadow-none"
+ >
+ Preview
+ </TabsTrigger>
+ <TabsTrigger
+ value="scores"
+ className="h-full rounded-none border-b-4 border-transparent data-[state=active]:border-primary-accent data-[state=active]:shadow-none"
+ >
+ Scores
+ </TabsTrigger>
+ </TabsList>
+ </Tabs>
+ </div>
+ )}
<div className="flex w-full flex-col overflow-y-auto">
<CardHeader className="flex flex-row flex-wrap justify-between gap-2">
<div className="flex flex-col gap-1">
@@ -97,50 +117,64 @@ export const TracePreview = ({
<CardDescription>
{trace.timestamp.toLocaleString()}
</CardDescription>
+ {viewType === "detailed" && (
+ <div className="flex flex-wrap gap-2">
+ {!!trace.latency && (
+ <Badge variant="outline">
+ {formatIntervalSeconds(trace.latency)}
+ </Badge>
+ )}
+ <AggUsageBadge observations={observations} />
+ {!!trace.release && (
+ <Badge variant="outline">Release: {trace.release}</Badge>
+ )}
+ {!!trace.version && (
+ <Badge variant="outline">Version: {trace.version}</Badge>
+ )}
+ {totalCost && (
+ <Badge variant="outline">
+ ∑ {usdFormatter(totalCost.toNumber())}
+ </Badge>
+ )}
+ </div>
+ )}
+ </div>
+ {viewType === "detailed" && (
<div className="flex flex-wrap gap-2">
- {!!trace.latency && (
- <Badge variant="outline">
- {formatIntervalSeconds(trace.latency)}
- </Badge>
- )}
- <AggUsageBadge observations={observations} />
- {!!trace.release && (
- <Badge variant="outline">Release: {trace.release}</Badge>
- )}
- {!!trace.version && (
- <Badge variant="outline">Version: {trace.version}</Badge>
- )}
- {totalCost && (
- <Badge variant="outline">
- ∑ {usdFormatter(totalCost.toNumber())}
- </Badge>
- )}
+ <CommentDrawerButton
+ projectId={trace.projectId}
+ objectId={trace.id}
+ objectType="TRACE"
+ count={commentCounts?.get(trace.id)}
+ />
+ <div className="flex items-start">
+ <AnnotateDrawer
+ projectId={trace.projectId}
+ traceId={trace.id}
+ scores={scores}
+ emptySelectedConfigIds={emptySelectedConfigIds}
+ setEmptySelectedConfigIds={setEmptySelectedConfigIds}
+ key={"annotation-drawer" + trace.id}
+ hasGroupedButton={hasEntitlement}
+ />
+ {hasEntitlement && (
+ <CreateNewAnnotationQueueItem
+ projectId={trace.projectId}
+ objectId={trace.id}
+ objectType={AnnotationQueueObjectType.TRACE}
+ />
+ )}
+ </div>
+ <NewDatasetItemFromTrace
+ traceId={trace.id}
+ projectId={trace.projectId}
+ input={trace.input}
+ output={trace.output}
+ metadata={trace.metadata}
+ key={trace.id}
+ />
</div>
- </div>
- <div className="flex flex-wrap gap-2">
- <CommentDrawerButton
- projectId={trace.projectId}
- objectId={trace.id}
- objectType="TRACE"
- count={commentCounts?.get(trace.id)}
- />
- <AnnotateDrawer
- projectId={trace.projectId}
- traceId={trace.id}
- scores={scores}
- emptySelectedConfigIds={emptySelectedConfigIds}
- setEmptySelectedConfigIds={setEmptySelectedConfigIds}
- key={"annotation-drawer" + trace.id}
- />
- <NewDatasetItemFromTrace
- traceId={trace.id}
- projectId={trace.projectId}
- input={trace.input}
- output={trace.output}
- metadata={trace.metadata}
- key={trace.id}
- />
- </div>
+ )}
</CardHeader>
<CardContent className="flex flex-col gap-4">
{selectedTab === "preview" && (
@@ -155,7 +189,9 @@ export const TracePreview = ({
title="Metadata"
json={trace.metadata}
/>
- <ScoresPreview itemScoresBySource={traceScoresBySource} />
+ {viewType === "detailed" && (
+ <ScoresPreview itemScoresBySource={traceScoresBySource} />
+ )}
</>
)}
{selectedTab === "scores" && (
diff --git a/web/src/components/trace/index.tsx b/web/src/components/trace/index.tsx
index 1085a6115d..63708d7d89 100644
--- a/web/src/components/trace/index.tsx
+++ b/web/src/components/trace/index.tsx
@@ -41,7 +41,11 @@ export function Trace(props: {
trace: Trace;
scores: APIScore[];
projectId: string;
+ viewType?: "detailed" | "focused";
+ isValidObservationId?: boolean;
}) {
+ const viewType = props.viewType ?? "detailed";
+ const isValidObservationId = props.isValidObservationId ?? true;
const capture = usePostHogClientCapture();
const [currentObservationId, setCurrentObservationId] = useQueryParam(
"observation",
@@ -151,8 +155,9 @@ export function Trace(props: {
observations={props.observations}
scores={props.scores}
commentCounts={traceCommentCounts.data}
+ viewType={viewType}
/>
- ) : (
+ ) : isValidObservationId ? (
<ObservationPreview
observations={props.observations}
scores={props.scores}
@@ -160,8 +165,9 @@ export function Trace(props: {
currentObservationId={currentObservationId}
traceId={props.trace.id}
commentCounts={observationCommentCounts.data}
+ viewType={viewType}
/>
- )}
+ ) : null}
</div>
<div className="md:col-span-2 md:flex md:h-full md:flex-col md:overflow-hidden">
<div className="mb-2 flex flex-shrink-0 flex-row justify-end gap-2">
diff --git a/web/src/ee/features/billing/components/SupportOrUpgradePage.tsx b/web/src/ee/features/billing/components/SupportOrUpgradePage.tsx
new file mode 100644
index 0000000000..901d332731
--- /dev/null
+++ b/web/src/ee/features/billing/components/SupportOrUpgradePage.tsx
@@ -0,0 +1,9 @@
+// TODO: replace placeholder div with actual component
+export const SupportOrUpgradePage = () => {
+ return (
+ <div>
+ You have no access to this feature. Check with your system administrator
+ to get elevated access or upgrade your plan.
+ </div>
+ );
+};
diff --git a/web/src/features/audit-logs/auditLog.ts b/web/src/features/audit-logs/auditLog.ts
index d4234d92e9..37506bac21 100644
--- a/web/src/features/audit-logs/auditLog.ts
+++ b/web/src/features/audit-logs/auditLog.ts
@@ -1,6 +1,8 @@
import { prisma as _prisma, type Role } from "@langfuse/shared/src/db";
export type AuditableResource =
+ | "annotationQueue"
+ | "annotationQueueItem"
| "organization"
| "orgMembership"
| "projectMembership"
diff --git a/web/src/features/datasets/components/NewDatasetItemFromObservationButton.tsx b/web/src/features/datasets/components/NewDatasetItemFromObservationButton.tsx
index 976eb86282..d629b73cf6 100644
--- a/web/src/features/datasets/components/NewDatasetItemFromObservationButton.tsx
+++ b/web/src/features/datasets/components/NewDatasetItemFromObservationButton.tsx
@@ -1,4 +1,3 @@
-import { Button } from "@/src/components/ui/button";
import { ChevronDown, LockIcon, PlusIcon } from "lucide-react";
import {
Dialog,
@@ -10,17 +9,18 @@ import { api } from "@/src/utils/api";
import { cn } from "@/src/utils/tailwind";
import { useState } from "react";
import {
- DropdownMenu,
- DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
+ DropdownMenu,
+ DropdownMenuContent,
DropdownMenuTrigger,
} from "@/src/components/ui/dropdown-menu";
import Link from "next/link";
import { NewDatasetItemForm } from "@/src/features/datasets/components/NewDatasetItemForm";
-import { type Prisma } from "@langfuse/shared";
-import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
+import { type Prisma } from "@langfuse/shared/src/db";
import { useSession } from "next-auth/react";
+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
+import { Button } from "@/src/components/ui/button";
import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
export const NewDatasetItemFromTrace = (props: {
@@ -31,7 +31,7 @@ export const NewDatasetItemFromTrace = (props: {
output: Prisma.JsonValue;
metadata: Prisma.JsonValue;
}) => {
- const [open, setOpen] = useState(false);
+ const [isFormOpen, setIsFormOpen] = useState(false);
const session = useSession();
const observationInDatasets =
api.datasets.datasetItemsBasedOnTraceOrObservation.useQuery(
@@ -58,7 +58,7 @@ export const NewDatasetItemFromTrace = (props: {
<DropdownMenuTrigger asChild>
<Button variant="secondary" disabled={!hasAccess}>
<span>{`In ${observationInDatasets.data.length} dataset(s)`}</span>
- <ChevronDown className="ml-2" />
+ <ChevronDown className="ml-2 h-3 w-3" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
@@ -80,7 +80,9 @@ export const NewDatasetItemFromTrace = (props: {
<DropdownMenuSeparator />
<DropdownMenuItem
className="capitalize"
- onClick={() => setOpen(true)}
+ onClick={() => {
+ setIsFormOpen(true);
+ }}
>
<PlusIcon size={16} className={cn("mr-2")} aria-hidden="true" />
Add new
@@ -91,7 +93,7 @@ export const NewDatasetItemFromTrace = (props: {
) : (
<Button
onClick={() => {
- setOpen(true);
+ setIsFormOpen(true);
capture("dataset_item:new_from_trace_form_open", {
object: props.observationId ? "observation" : "trace",
});
@@ -100,7 +102,10 @@ export const NewDatasetItemFromTrace = (props: {
disabled={!hasAccess}
>
{hasAccess ? (
- <PlusIcon className={cn("-ml-0.5 mr-1.5")} aria-hidden="true" />
+ <PlusIcon
+ className={cn("-ml-0.5 mr-1.5 h-4 w-4")}
+ aria-hidden="true"
+ />
) : null}
Add to dataset
{!hasAccess ? (
@@ -108,7 +113,7 @@ export const NewDatasetItemFromTrace = (props: {
) : null}
</Button>
)}
- <Dialog open={hasAccess && open} onOpenChange={setOpen}>
+ <Dialog open={hasAccess && isFormOpen} onOpenChange={setIsFormOpen}>
<DialogContent className="h-[calc(100vh-5rem)] max-h-none w-[calc(100vw-5rem)] max-w-none">
<DialogHeader>
<DialogTitle>Add to dataset</DialogTitle>
@@ -120,7 +125,7 @@ export const NewDatasetItemFromTrace = (props: {
input={props.input}
output={props.output}
metadata={props.metadata}
- onFormSuccess={() => setOpen(false)}
+ onFormSuccess={() => setIsFormOpen(false)}
className="h-full overflow-y-auto"
/>
</DialogContent>
diff --git a/web/src/features/entitlements/constants/entitlements.ts b/web/src/features/entitlements/constants/entitlements.ts
index 99c0caa813..c889beabf8 100644
--- a/web/src/features/entitlements/constants/entitlements.ts
+++ b/web/src/features/entitlements/constants/entitlements.ts
@@ -8,6 +8,7 @@ const entitlements = [
"cloud-billing",
"integration-posthog",
"batch-export",
+ "annotation-queues",
] as const;
export type Entitlement = (typeof entitlements)[number];
@@ -23,9 +24,14 @@ const cloudAllPlansEntitlements: Entitlement[] = [
export const entitlementAccess: Record<Plan, Entitlement[]> = {
oss: [],
"cloud:hobby": [...cloudAllPlansEntitlements],
- "cloud:pro": [...cloudAllPlansEntitlements],
- "cloud:team": [...cloudAllPlansEntitlements, "rbac-project-roles"],
+ "cloud:pro": [...cloudAllPlansEntitlements, "annotation-queues"],
+ "cloud:team": [
+ ...cloudAllPlansEntitlements,
+ "rbac-project-roles",
+ "annotation-queues",
+ ],
"self-hosted:enterprise": [
+ // "annotation-queues", // TODO: include for non-beta release
"playground",
"rbac-project-roles",
// `LANGFUSE_ALLOWED_ORGANIZATION_CREATORS` -> directly checked on instance level in auth.ts
diff --git a/web/src/features/feature-flags/available-flags.ts b/web/src/features/feature-flags/available-flags.ts
index 276ffb57fe..145b748eb8 100644
--- a/web/src/features/feature-flags/available-flags.ts
+++ b/web/src/features/feature-flags/available-flags.ts
@@ -1 +1 @@
-export const availableFlags = ["templateFlag"] as const;
+export const availableFlags = ["templateFlag", "annotationQueues"] as const;
diff --git a/web/src/features/notifications/SuccessNotification.tsx b/web/src/features/notifications/SuccessNotification.tsx
index ce2030706f..a52ebdc361 100644
--- a/web/src/features/notifications/SuccessNotification.tsx
+++ b/web/src/features/notifications/SuccessNotification.tsx
@@ -1,15 +1,21 @@
import { BadgeCheck, X } from "lucide-react";
+import Link from "next/link";
export type SuccessNotificationProps = {
title: string;
description: string;
onDismiss: () => void;
+ link?: {
+ href: string;
+ text: string;
+ };
};
export const SuccessNotification: React.FC<SuccessNotificationProps> = ({
title,
description,
onDismiss,
+ link,
}) => {
return (
<div className="flex justify-between">
@@ -22,7 +28,12 @@ export const SuccessNotification: React.FC<SuccessNotificationProps> = ({
</div>
{description && (
<div className="text-sm leading-tight text-primary-foreground">
- {description}
+ {description}{" "}
+ {!!link && (
+ <Link href={link.href}>
+ <span className="hover:underline">{link.text}</span>
+ </Link>
+ )}
</div>
)}
</div>
diff --git a/web/src/features/rbac/constants/projectAccessRights.ts b/web/src/features/rbac/constants/projectAccessRights.ts
index 602ef6da3b..03c77e902e 100644
--- a/web/src/features/rbac/constants/projectAccessRights.ts
+++ b/web/src/features/rbac/constants/projectAccessRights.ts
@@ -18,6 +18,9 @@ const projectScopes = [
"scoreConfigs:CUD",
"scoreConfigs:read",
+ "annotationQueues:read",
+ "annotationQueues:CUD",
+
"project:read",
"project:update",
"project:delete",
@@ -83,6 +86,8 @@ export const projectRoleAccessRights: Record<Role, ProjectScope[]> = {
"batchExport:create",
"comments:CUD",
"comments:read",
+ "annotationQueues:read",
+ "annotationQueues:CUD",
],
ADMIN: [
"project:read",
@@ -115,6 +120,8 @@ export const projectRoleAccessRights: Record<Role, ProjectScope[]> = {
"batchExport:create",
"comments:CUD",
"comments:read",
+ "annotationQueues:read",
+ "annotationQueues:CUD",
],
MEMBER: [
"project:read",
@@ -138,6 +145,8 @@ export const projectRoleAccessRights: Record<Role, ProjectScope[]> = {
"batchExport:create",
"comments:CUD",
"comments:read",
+ "annotationQueues:read",
+ "annotationQueues:CUD",
],
VIEWER: [
"project:read",
@@ -148,6 +157,7 @@ export const projectRoleAccessRights: Record<Role, ProjectScope[]> = {
"evalJobExecution:read",
"llmApiKeys:read",
"comments:read",
+ "annotationQueues:read",
],
NONE: [],
};
diff --git a/web/src/features/scores/components/AnnotateDrawer.tsx b/web/src/features/scores/components/AnnotateDrawer.tsx
index 4ad8d9f539..d90f5e674a 100644
--- a/web/src/features/scores/components/AnnotateDrawer.tsx
+++ b/web/src/features/scores/components/AnnotateDrawer.tsx
@@ -24,6 +24,7 @@ export function AnnotateDrawer({
variant = "button",
type = "trace",
source = "TraceDetail",
+ hasGroupedButton = false,
}: {
traceId: string;
scores: APIScore[];
@@ -34,6 +35,7 @@ export function AnnotateDrawer({
variant?: "button" | "badge";
type?: "trace" | "observation" | "session";
source?: "TraceDetail" | "SessionDetail";
+ hasGroupedButton?: boolean;
}) {
const [isDrawerOpen, setIsDrawerOpen] = useState(false);
const capture = usePostHogClientCapture();
@@ -62,6 +64,7 @@ export function AnnotateDrawer({
<Button
variant="secondary"
disabled={!hasAccess}
+ className={hasGroupedButton ? "rounded-r-none" : ""}
onClick={() => {
setIsDrawerOpen(true);
capture(
diff --git a/web/src/features/scores/components/AnnotateDrawerContent.tsx b/web/src/features/scores/components/AnnotateDrawerContent.tsx
index f1177884ae..c7b7616c2f 100644
--- a/web/src/features/scores/components/AnnotateDrawerContent.tsx
+++ b/web/src/features/scores/components/AnnotateDrawerContent.tsx
@@ -1,6 +1,13 @@
-import React, { useEffect, useRef } from "react";
+import React, { useEffect, useRef, useState } from "react";
import { Button } from "@/src/components/ui/button";
-import { MessageCircleMore, MessageCircle, X, Archive } from "lucide-react";
+import {
+ MessageCircleMore,
+ MessageCircle,
+ X,
+ Archive,
+ Loader2,
+ Check,
+} from "lucide-react";
import {
type ControllerRenderProps,
useFieldArray,
@@ -141,6 +148,9 @@ export function AnnotateDrawerContent({
projectId,
type = "trace",
source = "TraceDetail",
+ isSelectHidden = false,
+ queueId,
+ actionButtons,
}: {
traceId: string;
scores: APIScore[];
@@ -151,9 +161,13 @@ export function AnnotateDrawerContent({
projectId: string;
type?: "trace" | "observation" | "session";
source?: "TraceDetail" | "SessionDetail";
+ isSelectHidden?: boolean;
+ queueId?: string;
+ actionButtons?: React.ReactNode;
}) {
const capture = usePostHogClientCapture();
const router = useRouter();
+ const [showSaving, setShowSaving] = useState(false);
const form = useForm<AnnotateFormSchemaType>({
resolver: zodResolver(AnnotateFormSchema),
@@ -176,8 +190,14 @@ export function AnnotateDrawerContent({
const prevEmptySelectedConfigIdsRef = useRef(emptySelectedConfigIds);
useEffect(() => {
- // Only reset the form if emptySelectedConfigIds has changed
- if (prevEmptySelectedConfigIdsRef.current !== emptySelectedConfigIds) {
+ // Only reset the form if emptySelectedConfigIds has changed, compare by value not reference
+ if (
+ prevEmptySelectedConfigIdsRef.current.length !==
+ emptySelectedConfigIds.length ||
+ !prevEmptySelectedConfigIdsRef.current.every(
+ (id, index) => id === emptySelectedConfigIds[index],
+ )
+ ) {
form.reset({
scoreData: getDefaultScoreData({
scores,
@@ -259,6 +279,26 @@ export function AnnotateDrawerContent({
onSettled: onSettledUpsert,
});
+ useEffect(() => {
+ if (
+ mutUpdateScores.isLoading ||
+ mutCreateScores.isLoading ||
+ mutDeleteScore.isLoading
+ ) {
+ setShowSaving(true);
+ } else {
+ const timer = setTimeout(() => {
+ setShowSaving(false);
+ }, 300); // Keep saving message for 1 second after loading
+
+ return () => clearTimeout(timer); // Cleanup timer on unmount or when loading state changes
+ }
+ }, [
+ mutUpdateScores.isLoading,
+ mutCreateScores.isLoading,
+ mutDeleteScore.isLoading,
+ ]);
+
function handleOnCheckedChange(
values: Record<string, string>[],
changedValueId?: string,
@@ -329,6 +369,7 @@ export function AnnotateDrawerContent({
observationId,
value: newValue,
stringValue,
+ queueId,
});
await mutUpdateScores.mutateAsync({
@@ -350,6 +391,7 @@ export function AnnotateDrawerContent({
observationId,
value: newValue,
stringValue,
+ queueId,
});
await mutCreateScores.mutateAsync({
@@ -392,6 +434,7 @@ export function AnnotateDrawerContent({
observationId,
value,
comment,
+ queueId,
});
await mutUpdateScores.mutateAsync({
@@ -450,6 +493,7 @@ export function AnnotateDrawerContent({
comment: score.comment,
observationId,
value: Number(field.value),
+ queueId,
});
await mutUpdateScores.mutateAsync({
@@ -472,6 +516,7 @@ export function AnnotateDrawerContent({
comment: score.comment,
observationId,
value: Number(field.value),
+ queueId,
});
await mutCreateScores.mutateAsync({
@@ -498,49 +543,67 @@ export function AnnotateDrawerContent({
description: `Annotate ${observationId ? "observation" : "trace"} with scores to capture human evaluation across different dimensions.`,
href: "https://langfuse.com/docs/scores/manually",
}}
+ actionButtons={[
+ <div className="flex items-center justify-end" key="saving-spinner">
+ <div className="mr-1 items-center justify-center">
+ {showSaving ? (
+ <Loader2 className="h-3 w-3 animate-spin" />
+ ) : (
+ <Check className="h-3 w-3" />
+ )}
+ </div>
+ <span className="text-xs text-muted-foreground">
+ {showSaving ? "Saving score data" : "Score data saved"}
+ </span>
+ </div>,
+ actionButtons,
+ ]}
></Header>
- <div className="grid grid-flow-col items-center">
- <MultiSelectKeyValues
- title="Value"
- align="end"
- items="empty scores"
- className="grid grid-cols-[auto,1fr,auto,auto] gap-2"
- onValueChange={handleOnCheckedChange}
- options={configs
- .filter(
- (config) =>
- !config.isArchived ||
- fields.find((field) => field.configId === config.id),
- )
- .map((config) => ({
- key: config.id,
- value: `${getScoreDataTypeIcon(config.dataType)} ${config.name}`,
- disabled: fields.some(
- (field) => !!field.scoreId && field.configId === config.id,
- ),
- isArchived: config.isArchived,
- }))}
- values={fields
- .filter((field) => !!field.configId)
- .map((field) => ({
- value: `${getScoreDataTypeIcon(field.dataType)} ${field.name}`,
- key: field.configId as string,
- }))}
- controlButtons={
- <CommandItem
- onSelect={() => {
- capture("score_configs:manage_configs_item_click", {
- type: type,
- source: source,
- });
- router.push(`/project/${projectId}/settings/scores`);
- }}
- >
- Manage score configs
- </CommandItem>
- }
- />
- </div>
+
+ {!isSelectHidden && (
+ <div className="grid grid-flow-col items-center">
+ <MultiSelectKeyValues
+ title="Value"
+ align="end"
+ items="empty scores"
+ className="grid grid-cols-[auto,1fr,auto,auto] gap-2"
+ onValueChange={handleOnCheckedChange}
+ options={configs
+ .filter(
+ (config) =>
+ !config.isArchived ||
+ fields.find((field) => field.configId === config.id),
+ )
+ .map((config) => ({
+ key: config.id,
+ value: `${getScoreDataTypeIcon(config.dataType)} ${config.name}`,
+ disabled: fields.some(
+ (field) => !!field.scoreId && field.configId === config.id,
+ ),
+ isArchived: config.isArchived,
+ }))}
+ values={fields
+ .filter((field) => !!field.configId)
+ .map((field) => ({
+ value: `${getScoreDataTypeIcon(field.dataType)} ${field.name}`,
+ key: field.configId as string,
+ }))}
+ controlButtons={
+ <CommandItem
+ onSelect={() => {
+ capture("score_configs:manage_configs_item_click", {
+ type: type,
+ source: source,
+ });
+ router.push(`/project/${projectId}/settings/scores`);
+ }}
+ >
+ Manage score configs
+ </CommandItem>
+ }
+ />
+ </div>
+ )}
</DrawerHeader>
<Form {...form}>
<form className="flex flex-col gap-4">
@@ -764,6 +827,7 @@ export function AnnotateDrawerContent({
) : config.categories &&
renderSelect(categories) ? (
<Select
+ name={field.name}
defaultValue={score.stringValue}
disabled={config.isArchived}
onValueChange={handleOnValueChange(
diff --git a/web/src/features/scores/components/AnnotationQueueItemPage.tsx b/web/src/features/scores/components/AnnotationQueueItemPage.tsx
new file mode 100644
index 0000000000..0fb2236056
--- /dev/null
+++ b/web/src/features/scores/components/AnnotationQueueItemPage.tsx
@@ -0,0 +1,415 @@
+import { Trace } from "@/src/components/trace";
+import { ObservationPreview } from "@/src/components/trace/ObservationPreview";
+import { TracePreview } from "@/src/components/trace/TracePreview";
+import { Button } from "@/src/components/ui/button";
+import { Card } from "@/src/components/ui/card";
+import {
+ ResizableHandle,
+ ResizablePanel,
+ ResizablePanelGroup,
+} from "@/src/components/ui/resizable";
+import { Skeleton } from "@/src/components/ui/skeleton";
+import useSessionStorage from "@/src/components/useSessionStorage";
+import { showSuccessToast } from "@/src/features/notifications/showSuccessToast";
+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
+import { AnnotateDrawerContent } from "@/src/features/scores/components/AnnotateDrawerContent";
+import { api } from "@/src/utils/api";
+import { type RouterOutput } from "@/src/utils/types";
+import {
+ type AnnotationQueueItem,
+ AnnotationQueueObjectType,
+ AnnotationQueueStatus,
+ isPresent,
+ type ValidatedScoreConfig,
+} from "@langfuse/shared";
+import {
+ ArrowLeft,
+ ArrowRight,
+ SearchXIcon,
+ TriangleAlertIcon,
+} from "lucide-react";
+import { useSession } from "next-auth/react";
+import { useRouter } from "next/router";
+import { useEffect, useMemo, useState } from "react";
+import { StringParam, useQueryParam } from "use-query-params";
+
+const AnnotateIOView = ({
+ item,
+ configs,
+ view,
+}: {
+ item: AnnotationQueueItem & {
+ parentTraceId?: string | null;
+ lockedByUser: { name: string | null | undefined } | null;
+ };
+ configs: ValidatedScoreConfig[];
+ view: "showTree" | "hideTree";
+}) => {
+ const router = useRouter();
+ const session = useSession();
+ const traceId = item.parentTraceId ?? item.objectId;
+ const projectId = router.query.projectId as string;
+ const [panelSize, setPanelSize] = useSessionStorage(
+ `annotationQueuePanelSize-${projectId}`,
+ 65,
+ );
+
+ const [currentObservationId, setCurrentObservationId] = useQueryParam(
+ "observation",
+ StringParam,
+ );
+ useEffect(() => {
+ if (
+ view === "showTree" &&
+ item.objectType === AnnotationQueueObjectType.OBSERVATION
+ ) {
+ setCurrentObservationId(item.objectId);
+ } else setCurrentObservationId(undefined);
+ }, [view, item, setCurrentObservationId]);
+
+ const isLockedByOtherUser = item.lockedByUserId !== session.data?.user?.id;
+
+ const trace = api.traces.byIdWithObservationsAndScores.useQuery(
+ { traceId, projectId },
+ {
+ retry(failureCount, error) {
+ if (error.data?.code === "UNAUTHORIZED") return false;
+ return failureCount < 3;
+ },
+ },
+ );
+
+ const emptySelectedConfigIds = useMemo(() => {
+ return configs.map((c) => c.id);
+ }, [configs]);
+
+ if (trace.isLoading || !trace.data) return <div>Loading...</div>;
+
+ let isValidObservationId = false;
+
+ if (
+ currentObservationId &&
+ trace.data.observations.some(({ id }) => id === currentObservationId)
+ ) {
+ isValidObservationId = true;
+ }
+
+ return (
+ <ResizablePanelGroup
+ direction="horizontal"
+ className="h-full overflow-hidden"
+ onLayout={(sizes) => {
+ setPanelSize(sizes[0]);
+ }}
+ >
+ <ResizablePanel
+ className="col-span-1 h-full !overflow-y-auto"
+ minSize={30}
+ defaultSize={panelSize}
+ >
+ {view === "hideTree" ? (
+ item.objectType === AnnotationQueueObjectType.TRACE ? (
+ <TracePreview
+ key={trace.data.id}
+ trace={trace.data}
+ scores={trace.data.scores}
+ observations={trace.data.observations}
+ viewType="focused"
+ className="h-full"
+ />
+ ) : (
+ <ObservationPreview
+ observations={trace.data.observations}
+ scores={trace.data.scores}
+ projectId={item.projectId}
+ currentObservationId={item.objectId}
+ traceId={traceId}
+ viewType="focused"
+ className="h-full"
+ />
+ )
+ ) : (
+ <Card className="col-span-2 flex h-full flex-col overflow-hidden p-2">
+ <div className="overflow-x-auto md:overflow-hidden">
+ <Trace
+ key={trace.data.id}
+ trace={trace.data}
+ scores={trace.data.scores}
+ projectId={trace.data.projectId}
+ observations={trace.data.observations}
+ viewType="focused"
+ isValidObservationId={isValidObservationId}
+ />
+ </div>
+ </Card>
+ )}
+ </ResizablePanel>
+ <ResizableHandle withHandle className="ml-4 bg-transparent" />
+ <ResizablePanel
+ className="col-span-1 h-full md:flex md:flex-col md:overflow-hidden"
+ minSize={30}
+ >
+ <Card className="col-span-2 flex h-full flex-col overflow-hidden">
+ <AnnotateDrawerContent
+ key={"annotation-drawer-content" + item.objectId}
+ traceId={traceId}
+ scores={trace.data?.scores ?? []}
+ observationId={item.parentTraceId ? item.objectId : undefined}
+ configs={configs}
+ emptySelectedConfigIds={emptySelectedConfigIds}
+ setEmptySelectedConfigIds={() => {}}
+ projectId={item.projectId}
+ type={item.objectType.toLowerCase() as "trace" | "observation"}
+ isSelectHidden
+ queueId={item.queueId}
+ actionButtons={
+ isLockedByOtherUser && isPresent(item.lockedByUser?.name) ? (
+ <div className="flex items-center justify-center rounded-sm border border-dark-red bg-light-red p-1">
+ <TriangleAlertIcon className="mr-1 h-4 w-4 text-dark-red" />
+ <span className="text-xs text-dark-red">
+ Currently edited by {item.lockedByUser.name}
+ </span>
+ </div>
+ ) : undefined
+ }
+ />
+ </Card>
+ </ResizablePanel>
+ </ResizablePanelGroup>
+ );
+};
+
+export const AnnotationQueueItemPage: React.FC<{
+ annotationQueueId: string;
+ projectId: string;
+ view: "showTree" | "hideTree";
+ queryItemId?: string;
+}> = ({ annotationQueueId, projectId, view, queryItemId }) => {
+ const router = useRouter();
+ const isSingleItem = router.query.singleItem === "true";
+ const [nextItemData, setNextItemData] = useState<
+ RouterOutput["annotationQueues"]["fetchAndLockNext"] | null
+ >(null);
+ const [seenItemIds, setSeenItemIds] = useState<string[]>([]);
+ const [progressIndex, setProgressIndex] = useState(0);
+
+ const hasAccess = useHasProjectAccess({
+ projectId,
+ scope: "annotationQueues:CUD",
+ });
+ const itemId = isSingleItem ? queryItemId : seenItemIds[progressIndex];
+
+ const seenItemData = api.annotationQueueItems.byId.useQuery(
+ { projectId, itemId: itemId as string },
+ { enabled: !!itemId, refetchOnMount: false },
+ );
+
+ const fetchAndLockNextMutation =
+ api.annotationQueues.fetchAndLockNext.useMutation();
+
+ useEffect(() => {
+ async function fetchNextItem() {
+ if (!itemId && !isSingleItem) {
+ const nextItem = await fetchAndLockNextMutation.mutateAsync({
+ queueId: annotationQueueId,
+ projectId,
+ seenItemIds,
+ });
+ setNextItemData(nextItem);
+ }
+ }
+ fetchNextItem();
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
+
+ const queueData = api.annotationQueues.byId.useQuery(
+ {
+ queueId: annotationQueueId,
+ projectId,
+ },
+ {
+ refetchOnMount: false,
+ refetchOnWindowFocus: false,
+ refetchOnReconnect: false,
+ },
+ );
+
+ const unseenPendingItemCount =
+ api.annotationQueueItems.unseenPendingItemCountByQueueId.useQuery(
+ {
+ queueId: annotationQueueId,
+ projectId,
+ seenItemIds,
+ },
+ { refetchOnWindowFocus: false },
+ );
+
+ const utils = api.useUtils();
+ const completeMutation = api.annotationQueueItems.complete.useMutation({
+ onSuccess: async () => {
+ utils.annotationQueueItems.invalidate();
+ showSuccessToast({
+ title: "Item marked as complete",
+ description: "The item is successfully marked as complete.",
+ });
+ if (isSingleItem) {
+ return;
+ }
+
+ if (progressIndex >= seenItemIds.length - 1) {
+ const nextItem = await fetchAndLockNextMutation.mutateAsync({
+ queueId: annotationQueueId,
+ projectId,
+ seenItemIds,
+ });
+ setNextItemData(nextItem);
+ }
+
+ if (progressIndex + 1 < totalItems) {
+ setProgressIndex(Math.max(progressIndex + 1, 0));
+ }
+ },
+ });
+
+ const totalItems = useMemo(() => {
+ return seenItemIds.length + (unseenPendingItemCount.data ?? 0);
+ }, [unseenPendingItemCount.data, seenItemIds.length]);
+
+ const configs = queueData.data?.scoreConfigs ?? [];
+
+ const relevantItem = useMemo(() => {
+ if (isSingleItem) return seenItemData.data;
+ else
+ return progressIndex < seenItemIds.length
+ ? seenItemData.data
+ : nextItemData;
+ }, [
+ progressIndex,
+ seenItemIds.length,
+ seenItemData.data,
+ nextItemData,
+ isSingleItem,
+ ]);
+
+ useEffect(() => {
+ if (relevantItem && router.query.itemId !== relevantItem.id) {
+ router.push(
+ {
+ pathname: `/project/${projectId}/annotation-queues/${annotationQueueId}/items/${relevantItem.id}`,
+ },
+ undefined,
+ );
+ }
+ }, [relevantItem, router, projectId, annotationQueueId]);
+
+ useEffect(() => {
+ if (
+ relevantItem &&
+ !seenItemIds.includes(relevantItem.id) &&
+ !isSingleItem
+ ) {
+ setSeenItemIds((prev) => [...prev, relevantItem.id]);
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [relevantItem]);
+
+ if (
+ (seenItemData.isLoading && itemId) ||
+ (fetchAndLockNextMutation.isLoading && !itemId) ||
+ unseenPendingItemCount.isLoading
+ ) {
+ return <Skeleton className="h-full w-full" />;
+ }
+
+ if (!relevantItem && !(itemId && seenItemIds.includes(itemId))) {
+ return <div>No more items left to annotate!</div>;
+ }
+
+ const isNextItemAvailable = totalItems > progressIndex + 1;
+
+ return (
+ <div className="grid h-full grid-rows-[1fr,auto] gap-4 overflow-hidden">
+ {relevantItem ? (
+ <AnnotateIOView item={relevantItem} configs={configs} view={view} />
+ ) : (
+ <Card className="flex h-full w-full flex-col items-center justify-center overflow-hidden">
+ <SearchXIcon className="mb-2 h-8 w-8 text-muted-foreground" />
+ <span className="max-w-96 text-wrap text-sm text-muted-foreground">
+ Item has been <strong>deleted from annotation queue</strong>.
+ Previously added scores and underlying reference trace are
+ unaffected by this action.
+ </span>
+ </Card>
+ )}
+ <div className="grid h-full w-full grid-cols-1 justify-end gap-2 sm:grid-cols-[auto,min-content]">
+ {!isSingleItem && (
+ <div className="flex max-h-10 flex-row gap-2">
+ <span className="grid h-9 min-w-16 items-center rounded-md bg-muted p-1 text-center text-sm">
+ {progressIndex + 1} / {totalItems}
+ </span>
+ <Button
+ onClick={() => {
+ setProgressIndex(progressIndex - 1);
+ }}
+ variant="outline"
+ disabled={progressIndex === 0 || !hasAccess}
+ size="lg"
+ className="px-4"
+ >
+ <ArrowLeft className="mr-1 h-4 w-4" />
+ Back
+ </Button>
+ </div>
+ )}
+ <div className="flex w-full min-w-[265px] justify-end gap-2">
+ {!isSingleItem && (
+ <Button
+ onClick={async () => {
+ if (progressIndex >= seenItemIds.length - 1) {
+ const nextItem = await fetchAndLockNextMutation.mutateAsync({
+ queueId: annotationQueueId,
+ projectId,
+ seenItemIds,
+ });
+ setNextItemData(nextItem);
+ }
+ setProgressIndex(Math.max(progressIndex + 1, 0));
+ }}
+ disabled={!isNextItemAvailable || !hasAccess} // Disable button during loading
+ size="lg"
+ className={`px-4 ${!relevantItem ? "w-full" : ""}`}
+ variant="outline"
+ >
+ {relevantItem?.status === AnnotationQueueStatus.PENDING
+ ? "Skip"
+ : "Next"}
+ <ArrowRight className="ml-1 h-4 w-4" />
+ </Button>
+ )}
+ {!!relevantItem &&
+ (relevantItem.status === AnnotationQueueStatus.PENDING ? (
+ <Button
+ onClick={async () => {
+ await completeMutation.mutateAsync({
+ itemId: relevantItem.id,
+ projectId,
+ });
+ }}
+ size="lg"
+ className="w-full"
+ disabled={completeMutation.isLoading || !hasAccess}
+ >
+ {isSingleItem || progressIndex + 1 === totalItems
+ ? "Complete"
+ : "Complete + Next"}
+ </Button>
+ ) : (
+ <div className="text-dark-gree inline-flex h-9 w-full items-center justify-center rounded-md border border-dark-green bg-light-green px-8 text-sm font-medium">
+ Completed
+ </div>
+ ))}
+ </div>
+ </div>
+ </div>
+ );
+};
diff --git a/web/src/features/scores/components/AnnotationQueueItemsTable.tsx b/web/src/features/scores/components/AnnotationQueueItemsTable.tsx
new file mode 100644
index 0000000000..dac8971a8d
--- /dev/null
+++ b/web/src/features/scores/components/AnnotationQueueItemsTable.tsx
@@ -0,0 +1,409 @@
+import { DataTable } from "@/src/components/table/data-table";
+import TableLink from "@/src/components/table/table-link";
+import { type LangfuseColumnDef } from "@/src/components/table/types";
+import { api } from "@/src/utils/api";
+import { useQueryParams, withDefault, NumberParam } from "use-query-params";
+import { DataTableToolbar } from "@/src/components/table/data-table-toolbar";
+import useColumnVisibility from "@/src/features/column-visibility/hooks/useColumnVisibility";
+import { type AnnotationQueueStatus } from "@langfuse/shared";
+import { useRowHeightLocalStorage } from "@/src/components/table/data-table-row-height-switch";
+import { ChevronDown, ListTree, Trash } from "lucide-react";
+import useColumnOrder from "@/src/features/column-visibility/hooks/useColumnOrder";
+import {
+ Avatar,
+ AvatarFallback,
+ AvatarImage,
+} from "@/src/components/ui/avatar";
+import { type RouterOutput } from "@/src/utils/types";
+import { type RowSelectionState } from "@tanstack/react-table";
+import { useState } from "react";
+import {
+ DropdownMenu,
+ DropdownMenuTrigger,
+ DropdownMenuContent,
+ DropdownMenuItem,
+} from "@/src/components/ui/dropdown-menu";
+import { Button } from "@/src/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@/src/components/ui/dialog";
+import { Checkbox } from "@/src/components/ui/checkbox";
+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
+import { StatusBadge } from "@/src/components/layouts/status-badge";
+
+const QueueItemTableMultiSelectAction = ({
+ selectedItemIds,
+ projectId,
+ onDeleteSuccess,
+}: {
+ selectedItemIds: string[];
+ projectId: string;
+ onDeleteSuccess: () => void;
+}) => {
+ const utils = api.useUtils();
+ const [open, setOpen] = useState(false);
+
+ const hasDeleteAccess = useHasProjectAccess({
+ projectId,
+ scope: "annotationQueues:CUD",
+ });
+ const mutDeleteItems = api.annotationQueueItems.deleteMany.useMutation({
+ onSuccess: () => {
+ onDeleteSuccess();
+ void utils.annotationQueueItems.itemsByQueueId.invalidate();
+ },
+ });
+
+ return (
+ <>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button disabled={selectedItemIds.length < 1}>
+ Actions ({selectedItemIds.length} selected)
+ <ChevronDown className="h-5 w-5" />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent>
+ <DropdownMenuItem
+ disabled={!hasDeleteAccess}
+ onClick={() => {
+ setOpen(true);
+ }}
+ >
+ <Trash className="mr-2 h-4 w-4" />
+ <span>Delete</span>
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ <Dialog
+ open={open}
+ onOpenChange={(isOpen) => {
+ if (!isOpen) {
+ setOpen(false);
+ }
+ }}
+ >
+ <DialogContent className="sm:max-w-md">
+ <DialogHeader>
+ <DialogTitle>Delete queue items</DialogTitle>
+ <DialogDescription>
+ This action cannot be undone and removes the selected annotation
+ queue item(s), but
+ <strong> does not delete associated scores.</strong>
+ </DialogDescription>
+ </DialogHeader>
+ <DialogFooter className="sm:justify-start">
+ <Button
+ type="button"
+ variant="destructive"
+ loading={mutDeleteItems.isLoading}
+ disabled={mutDeleteItems.isLoading}
+ onClick={() => {
+ void mutDeleteItems
+ .mutateAsync({
+ itemIds: selectedItemIds,
+ projectId,
+ })
+ .then(() => {
+ setOpen(false);
+ });
+ }}
+ >
+ Delete {selectedItemIds.length} item(s)
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ </>
+ );
+};
+
+export type QueueItemRowData = {
+ id: string;
+ source: {
+ traceId: string;
+ observationId?: string;
+ };
+ status: AnnotationQueueStatus;
+ completedAt: string;
+ annotatorUser: {
+ userId?: string;
+ userName?: string;
+ image?: string;
+ };
+};
+
+export function AnnotationQueueItemsTable({
+ projectId,
+ queueId,
+}: {
+ projectId: string;
+ queueId: string;
+}) {
+ const [paginationState, setPaginationState] = useQueryParams({
+ pageIndex: withDefault(NumberParam, 0),
+ pageSize: withDefault(NumberParam, 50),
+ });
+ const [selectedRows, setSelectedRows] = useState<RowSelectionState>({});
+
+ const [rowHeight, setRowHeight] = useRowHeightLocalStorage("queueItems", "s");
+ const items = api.annotationQueueItems.itemsByQueueId.useQuery({
+ projectId,
+ queueId,
+ page: paginationState.pageIndex,
+ limit: paginationState.pageSize,
+ });
+
+ const columns: LangfuseColumnDef<QueueItemRowData>[] = [
+ {
+ id: "select",
+ accessorKey: "select",
+ size: 30,
+ isPinned: true,
+ header: ({ table }) => {
+ return (
+ <Checkbox
+ checked={
+ table.getIsAllPageRowsSelected()
+ ? true
+ : table.getIsSomePageRowsSelected()
+ ? "indeterminate"
+ : false
+ }
+ onCheckedChange={(value) => {
+ table.toggleAllPageRowsSelected(!!value);
+ if (!value) {
+ setSelectedRows({});
+ }
+ }}
+ aria-label="Select all"
+ className="mt-1 opacity-60 data-[state=checked]:mt-[6px] data-[state=indeterminate]:mt-[6px]"
+ />
+ );
+ },
+ cell: ({ row }) => {
+ return (
+ <Checkbox
+ checked={row.getIsSelected()}
+ onCheckedChange={(value) => row.toggleSelected(!!value)}
+ aria-label="Select row"
+ className="mt-1 opacity-60 data-[state=checked]:mt-[5px]"
+ />
+ );
+ },
+ },
+ {
+ accessorKey: "id",
+ header: "Id",
+ id: "id",
+ size: 70,
+ isPinned: true,
+ cell: ({ row }) => {
+ const id: QueueItemRowData["id"] = row.getValue("id");
+ return (
+ <TableLink
+ path={`/project/${projectId}/annotation-queues/${queueId}/items/${id}?singleItem=true`}
+ value={id}
+ />
+ );
+ },
+ },
+ {
+ accessorKey: "source",
+ header: "Source",
+ headerTooltip: {
+ description:
+ "Link to the source trace based on which this item was added",
+ },
+ id: "source",
+ size: 50,
+ cell: ({ row }) => {
+ const source: QueueItemRowData["source"] = row.getValue("source");
+ if (!source) return null;
+
+ if (!!source.observationId) {
+ return (
+ <TableLink
+ path={`/project/${projectId}/traces/${source.traceId}?observation=${source.observationId}`}
+ value={source.observationId}
+ icon={<ListTree className="h-4 w-4" />}
+ />
+ );
+ } else {
+ return (
+ <TableLink
+ path={`/project/${projectId}/traces/${source.traceId}`}
+ value={source.traceId}
+ icon={<ListTree className="h-4 w-4" />}
+ />
+ );
+ }
+ },
+ },
+ {
+ accessorKey: "status",
+ header: "Status",
+ id: "status",
+ size: 60,
+ cell: ({ row }) => {
+ const status: QueueItemRowData["status"] = row.getValue("status");
+ return (
+ <StatusBadge
+ className="capitalize"
+ type={status.toLowerCase()}
+ isLive={false}
+ />
+ );
+ },
+ },
+ {
+ accessorKey: "completedAt",
+ header: "Completed At",
+ id: "completedAt",
+ defaultHidden: true,
+ enableHiding: true,
+ size: 60,
+ },
+ {
+ accessorKey: "annotatorUser",
+ header: "Completed by",
+ id: "annotatorUser",
+ enableHiding: true,
+ size: 80,
+ cell: ({ row }) => {
+ const annotatorUser: QueueItemRowData["annotatorUser"] =
+ row.getValue("annotatorUser");
+ if (!annotatorUser || !annotatorUser.userId) return null;
+
+ const { userId, userName, image } = annotatorUser;
+ return (
+ <div className="flex items-center space-x-2">
+ <Avatar className="h-7 w-7">
+ <AvatarImage
+ src={image ?? undefined}
+ alt={userName ?? "User Avatar"}
+ />
+ <AvatarFallback>
+ {userName
+ ? userName
+ .split(" ")
+ .map((word) => word[0])
+ .slice(0, 2)
+ .concat("")
+ : null}
+ </AvatarFallback>
+ </Avatar>
+ <span>{userName ?? userId}</span>
+ </div>
+ );
+ },
+ },
+ ];
+
+ const convertToTableRow = (
+ item: RouterOutput["annotationQueueItems"]["itemsByQueueId"]["queueItems"][number],
+ ): QueueItemRowData => {
+ return {
+ id: item.id,
+ completedAt: item.completedAt?.toLocaleString() ?? "",
+ status: item.status,
+ source:
+ item.objectType === "OBSERVATION"
+ ? {
+ traceId: item.parentTraceId ?? "",
+ observationId: item.objectId,
+ }
+ : {
+ traceId: item.objectId,
+ },
+ annotatorUser: {
+ userId: item.annotatorUserId ?? undefined,
+ userName: item.annotatorUserName ?? undefined,
+ image: item.annotatorUserImage ?? undefined,
+ },
+ };
+ };
+
+ const [columnVisibility, setColumnVisibility] =
+ useColumnVisibility<QueueItemRowData>(
+ `queueItemsColumnVisibility-${projectId}`,
+ columns,
+ );
+
+ const [columnOrder, setColumnOrder] = useColumnOrder<QueueItemRowData>(
+ "queueItemsColumnOrder",
+ columns,
+ );
+
+ return (
+ <>
+ <DataTableToolbar
+ columns={columns}
+ columnVisibility={columnVisibility}
+ setColumnVisibility={setColumnVisibility}
+ columnOrder={columnOrder}
+ setColumnOrder={setColumnOrder}
+ rowHeight={rowHeight}
+ setRowHeight={setRowHeight}
+ actionButtons={[
+ Object.keys(selectedRows).filter((itemId) =>
+ items.data?.queueItems.map((item) => item.id).includes(itemId),
+ ).length > 0 ? (
+ <QueueItemTableMultiSelectAction
+ // Exclude items that are not in the current page
+ selectedItemIds={Object.keys(selectedRows).filter((itemId) =>
+ items.data?.queueItems.map((item) => item.id).includes(itemId),
+ )}
+ projectId={projectId}
+ onDeleteSuccess={() => {
+ setSelectedRows({});
+ }}
+ />
+ ) : null,
+ ]}
+ />
+ <DataTable
+ columns={columns}
+ data={
+ items.isLoading
+ ? { isLoading: true, isError: false }
+ : items.isError
+ ? {
+ isLoading: false,
+ isError: true,
+ error: items.error.message,
+ }
+ : {
+ isLoading: false,
+ isError: false,
+ data: items.data.queueItems.map((item) =>
+ convertToTableRow(item),
+ ),
+ }
+ }
+ help={{
+ description:
+ "Add traces and/or observations to your annotation queue to have them annotated by your team across predefined dimensions.",
+ href: "https://langfuse.com/docs/scores/model-based-evals",
+ }}
+ pagination={{
+ totalCount: items.data?.totalItems ?? null,
+ onChange: setPaginationState,
+ state: paginationState,
+ }}
+ rowSelection={selectedRows}
+ setRowSelection={setSelectedRows}
+ columnVisibility={columnVisibility}
+ onColumnVisibilityChange={setColumnVisibility}
+ columnOrder={columnOrder}
+ onColumnOrderChange={setColumnOrder}
+ rowHeight={rowHeight}
+ />
+ </>
+ );
+}
diff --git a/web/src/features/scores/components/AnnotationQueuesItem.tsx b/web/src/features/scores/components/AnnotationQueuesItem.tsx
new file mode 100644
index 0000000000..66781dc633
--- /dev/null
+++ b/web/src/features/scores/components/AnnotationQueuesItem.tsx
@@ -0,0 +1,99 @@
+import { FullScreenPage } from "@/src/components/layouts/full-screen-page";
+import Header from "@/src/components/layouts/header";
+import { Tabs, TabsList, TabsTrigger } from "@/src/components/ui/tabs";
+import useSessionStorage from "@/src/components/useSessionStorage";
+import { SupportOrUpgradePage } from "@/src/ee/features/billing/components/SupportOrUpgradePage";
+import { useHasOrgEntitlement } from "@/src/features/entitlements/hooks";
+import { FeatureFlagToggle } from "@/src/features/feature-flags/components/FeatureFlagToggle";
+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
+import { AnnotationQueueItemPage } from "@/src/features/scores/components/AnnotationQueueItemPage";
+import { api } from "@/src/utils/api";
+import { Goal, Network } from "lucide-react";
+
+export const AnnotationQueuesItem = ({
+ annotationQueueId,
+ projectId,
+ itemId,
+}: {
+ annotationQueueId: string;
+ projectId: string;
+ itemId?: string;
+}) => {
+ const hasAccess = useHasProjectAccess({
+ projectId,
+ scope: "annotationQueues:read",
+ });
+ const hasEntitlement = useHasOrgEntitlement("annotation-queues");
+
+ const queue = api.annotationQueues.byId.useQuery(
+ {
+ queueId: annotationQueueId,
+ projectId,
+ },
+ {
+ trpc: {
+ context: {
+ skipBatch: true,
+ },
+ },
+ refetchOnMount: false, // prevents refetching loops
+ },
+ );
+
+ const [view, setView] = useSessionStorage<"hideTree" | "showTree">(
+ `annotationQueueView-${projectId}`,
+ "hideTree",
+ );
+
+ if (!hasAccess || !hasEntitlement) return <SupportOrUpgradePage />;
+
+ return (
+ <FullScreenPage>
+ <FeatureFlagToggle
+ featureFlag="annotationQueues"
+ whenEnabled={
+ <>
+ <Header
+ title={`${queue.data?.name ?? annotationQueueId}`}
+ breadcrumb={[
+ {
+ name: "Annotation Queues",
+ href: `/project/${projectId}/annotation-queues`,
+ },
+ {
+ name: queue.data?.name ?? annotationQueueId,
+ href: `/project/${projectId}/annotation-queues/${annotationQueueId}`,
+ },
+ ]}
+ actionButtons={
+ <Tabs
+ value={view}
+ onValueChange={(view: string) => {
+ setView(view as "hideTree" | "showTree");
+ }}
+ >
+ <TabsList>
+ <TabsTrigger value="hideTree">
+ <Goal className="mr-1 h-4 w-4"></Goal>
+ Focused
+ </TabsTrigger>
+ <TabsTrigger value="showTree">
+ <Network className="mr-1 h-4 w-4"></Network>
+ Detailed
+ </TabsTrigger>
+ </TabsList>
+ </Tabs>
+ }
+ />
+ <AnnotationQueueItemPage
+ projectId={projectId}
+ annotationQueueId={annotationQueueId}
+ view={view}
+ queryItemId={itemId}
+ />
+ </>
+ }
+ />
+ </FullScreenPage>
+ );
+};
diff --git a/web/src/features/scores/components/AnnotationQueuesTable.tsx b/web/src/features/scores/components/AnnotationQueuesTable.tsx
new file mode 100644
index 0000000000..12074248f4
--- /dev/null
+++ b/web/src/features/scores/components/AnnotationQueuesTable.tsx
@@ -0,0 +1,273 @@
+import { DataTable } from "@/src/components/table/data-table";
+import { type LangfuseColumnDef } from "@/src/components/table/types";
+import { api } from "@/src/utils/api";
+import { useQueryParams, withDefault, NumberParam } from "use-query-params";
+import { type RouterOutput } from "@/src/utils/types";
+import useColumnVisibility from "@/src/features/column-visibility/hooks/useColumnVisibility";
+import { DataTableToolbar } from "@/src/components/table/data-table-toolbar";
+import { useRowHeightLocalStorage } from "@/src/components/table/data-table-row-height-switch";
+import useColumnOrder from "@/src/features/column-visibility/hooks/useColumnOrder";
+import { CreateOrEditAnnotationQueueButton } from "@/src/features/scores/components/CreateOrEditAnnotationQueueButton";
+import { type ScoreDataType } from "@langfuse/shared";
+import { getScoreDataTypeIcon } from "@/src/features/scores/components/ScoreDetailColumnHelpers";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuLabel,
+ DropdownMenuTrigger,
+} from "@/src/components/ui/dropdown-menu";
+import { ClipboardPen, Lock, MoreVertical } from "lucide-react";
+import { Button } from "@/src/components/ui/button";
+import { DeleteAnnotationQueueButton } from "@/src/features/scores/components/DeleteAnnotationQueueButton";
+import { cn } from "@/src/utils/tailwind";
+import TableLink from "@/src/components/table/table-link";
+import Link from "next/link";
+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
+
+type RowData = {
+ key: {
+ id: string;
+ name: string;
+ };
+ description?: string;
+ countCompletedItems: number;
+ countPendingItems: number;
+ scoreConfigs: { id: string; name: string; dataType: ScoreDataType }[];
+ createdAt: string;
+};
+
+export function AnnotationQueuesTable({ projectId }: { projectId: string }) {
+ const [rowHeight, setRowHeight] = useRowHeightLocalStorage(
+ "annotationQueues",
+ "s",
+ );
+
+ const [paginationState, setPaginationState] = useQueryParams({
+ pageIndex: withDefault(NumberParam, 0),
+ pageSize: withDefault(NumberParam, 50),
+ });
+
+ const queues = api.annotationQueues.all.useQuery({
+ projectId: projectId,
+ page: paginationState.pageIndex,
+ limit: paginationState.pageSize,
+ });
+
+ const hasAccess = useHasProjectAccess({
+ projectId: projectId,
+ scope: "annotationQueues:CUD",
+ });
+
+ const columns: LangfuseColumnDef<RowData>[] = [
+ {
+ accessorKey: "key",
+ header: "Name",
+ id: "key",
+ size: 150,
+ isPinned: true,
+ cell: ({ row }) => {
+ const key: RowData["key"] = row.getValue("key");
+ return key && "id" in key && typeof key.id === "string" ? (
+ <TableLink
+ path={`/project/${projectId}/annotation-queues/${key.id}`}
+ value={key.name}
+ />
+ ) : undefined;
+ },
+ },
+ {
+ accessorKey: "description",
+ header: "Description",
+ id: "description",
+ enableHiding: true,
+ size: 200,
+ cell: ({ row }) => {
+ const description: RowData["description"] = row.getValue("description");
+ return (
+ <span
+ className={cn(
+ "grid h-full items-center overflow-auto",
+ rowHeight === "s" && "leading-3",
+ )}
+ >
+ {description}
+ </span>
+ );
+ },
+ },
+ {
+ accessorKey: "countCompletedItems",
+ header: "Completed Items",
+ id: "countCompletedItems",
+ enableHiding: true,
+ size: 90,
+ },
+ {
+ accessorKey: "countPendingItems",
+ header: "Pending Items",
+ id: "countPendingItems",
+ enableHiding: true,
+ size: 90,
+ },
+ {
+ accessorKey: "scoreConfigs",
+ header: "Score Configs",
+ id: "scoreConfigs",
+ enableHiding: true,
+ size: 200,
+ cell: ({ row }) => {
+ const scoreConfigs: RowData["scoreConfigs"] =
+ row.getValue("scoreConfigs");
+
+ return (
+ <span
+ className={cn(
+ "grid h-full items-center overflow-auto",
+ rowHeight === "s" && "leading-3",
+ )}
+ >
+ {scoreConfigs
+ .map(
+ (config) =>
+ `${getScoreDataTypeIcon(config.dataType)} ${config.name}`,
+ )
+ .join(", ")}
+ </span>
+ );
+ },
+ },
+ {
+ accessorKey: "createdAt",
+ header: "Created",
+ id: "createdAt",
+ enableHiding: true,
+ size: 150,
+ },
+ {
+ accessorKey: "processAction",
+ header: "Process",
+ id: "processAction",
+ isPinned: true,
+ cell: ({ row }) => {
+ const key: RowData["key"] = row.getValue("key");
+ return !hasAccess ? (
+ <Button size="sm" disabled>
+ <Lock className="mr-1 h-3 w-3" />
+ <span className="text-xs">Process queue</span>
+ </Button>
+ ) : (
+ <Button size="sm" asChild>
+ <Link
+ href={`/project/${projectId}/annotation-queues/${key.id}/items`}
+ >
+ <ClipboardPen className="mr-1 h-3 w-3" />
+ <span className="text-xs">Process queue</span>
+ </Link>
+ </Button>
+ );
+ },
+ },
+ {
+ accessorKey: "actions",
+ header: "Actions",
+ id: "actions",
+ size: 70,
+ isPinned: true,
+ cell: ({ row }) => {
+ const key: RowData["key"] = row.getValue("key");
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button variant="ghost" className="h-8 w-8 p-0">
+ <span className="sr-only">Open menu</span>
+ <MoreVertical className="h-4 w-4" />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuLabel>Actions</DropdownMenuLabel>
+ <div className="flex flex-col space-y-0.5">
+ <CreateOrEditAnnotationQueueButton
+ projectId={projectId}
+ queueId={key.id}
+ variant="ghost"
+ />
+ <DeleteAnnotationQueueButton
+ projectId={projectId}
+ queueId={key.id}
+ />
+ </div>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+ },
+ },
+ ];
+
+ const convertToTableRow = (
+ item: RouterOutput["annotationQueues"]["all"]["queues"][number],
+ ): RowData => {
+ return {
+ key: { id: item.id, name: item.name },
+ description: item.description ?? undefined,
+ scoreConfigs: item.scoreConfigs,
+ createdAt: item.createdAt.toLocaleString(),
+ countCompletedItems: item.countCompletedItems,
+ countPendingItems: item.countPendingItems,
+ };
+ };
+
+ const [columnVisibility, setColumnVisibility] = useColumnVisibility<RowData>(
+ "queuesColumnVisibility",
+ columns,
+ );
+
+ const [columnOrder, setColumnOrder] = useColumnOrder<RowData>(
+ "queuesColumnOrder",
+ columns,
+ );
+
+ return (
+ <>
+ <DataTableToolbar
+ columns={columns}
+ columnVisibility={columnVisibility}
+ setColumnVisibility={setColumnVisibility}
+ columnOrder={columnOrder}
+ setColumnOrder={setColumnOrder}
+ rowHeight={rowHeight}
+ setRowHeight={setRowHeight}
+ actionButtons={
+ <CreateOrEditAnnotationQueueButton projectId={projectId} />
+ }
+ />
+ <DataTable
+ columns={columns}
+ data={
+ queues.isLoading
+ ? { isLoading: true, isError: false }
+ : queues.isError
+ ? {
+ isLoading: false,
+ isError: true,
+ error: queues.error.message,
+ }
+ : {
+ isLoading: false,
+ isError: false,
+ data: queues.data.queues.map((t) => convertToTableRow(t)),
+ }
+ }
+ pagination={{
+ totalCount: queues.data?.totalCount ?? null,
+ onChange: setPaginationState,
+ state: paginationState,
+ }}
+ columnVisibility={columnVisibility}
+ onColumnVisibilityChange={setColumnVisibility}
+ columnOrder={columnOrder}
+ onColumnOrderChange={setColumnOrder}
+ rowHeight={rowHeight}
+ />
+ </>
+ );
+}
diff --git a/web/src/features/scores/components/CreateNewAnnotationQueueItem.tsx b/web/src/features/scores/components/CreateNewAnnotationQueueItem.tsx
new file mode 100644
index 0000000000..e51074ef2a
--- /dev/null
+++ b/web/src/features/scores/components/CreateNewAnnotationQueueItem.tsx
@@ -0,0 +1,194 @@
+import { Badge } from "@/src/components/ui/badge";
+import { Button } from "@/src/components/ui/button";
+import {
+ DropdownMenuItem,
+ DropdownMenu,
+ DropdownMenuTrigger,
+ DropdownMenuContent,
+ DropdownMenuSeparator,
+ DropdownMenuCheckboxItem,
+ DropdownMenuLabel,
+} from "@/src/components/ui/dropdown-menu";
+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
+import { api } from "@/src/utils/api";
+import { cn } from "@/src/utils/tailwind";
+import {
+ AnnotationQueueStatus,
+ type AnnotationQueueObjectType,
+} from "@langfuse/shared";
+import { ChevronDown, ExternalLink } from "lucide-react";
+import { useSession } from "next-auth/react";
+import Link from "next/link";
+import { useState, useCallback } from "react";
+
+export const CreateNewAnnotationQueueItem = ({
+ projectId,
+ objectId,
+ objectType,
+}: {
+ projectId: string;
+ objectId: string;
+ objectType: AnnotationQueueObjectType;
+}) => {
+ const [isDropdownOpen, setIsDropdownOpen] = useState(false);
+ const session = useSession();
+ const hasAccess = useHasProjectAccess({
+ projectId: projectId,
+ scope: "annotationQueues:CUD",
+ });
+ const queues = api.annotationQueues.byObjectId.useQuery(
+ {
+ projectId,
+ objectId,
+ objectType,
+ },
+ { enabled: session.status === "authenticated" },
+ );
+ const utils = api.useUtils();
+ const addToQueueMutation = api.annotationQueueItems.createMany.useMutation();
+ const removeFromQueueMutation =
+ api.annotationQueueItems.deleteMany.useMutation();
+
+ const handleQueueItemToggle = useCallback(
+ async (queueId: string, queueName: string, itemId?: string) => {
+ try {
+ if (!itemId) {
+ await addToQueueMutation.mutateAsync({
+ projectId,
+ objectIds: [objectId],
+ objectType,
+ queueId,
+ });
+ } else {
+ const confirmRemoval = confirm(
+ `Are you sure you want to remove this item from the queue "${queueName}"?`,
+ );
+ if (confirmRemoval) {
+ await removeFromQueueMutation.mutateAsync({
+ projectId,
+ itemIds: [itemId],
+ });
+ }
+ }
+ // Manually invalidate the query to refresh the data
+ await utils.annotationQueues.byObjectId.invalidate({
+ projectId,
+ objectId,
+ objectType,
+ });
+ } catch (error) {
+ console.error("Error toggling queue item:", error);
+ }
+ },
+ [
+ addToQueueMutation,
+ removeFromQueueMutation,
+ projectId,
+ objectId,
+ objectType,
+ utils.annotationQueues,
+ ],
+ );
+
+ if (session.status !== "authenticated" || queues.isLoading) {
+ return (
+ <Button
+ variant="secondary"
+ disabled
+ className="rounded-l-none rounded-r-md border-l-2"
+ >
+ <ChevronDown className="h-3 w-3" />
+ </Button>
+ );
+ }
+
+ return (
+ <DropdownMenu
+ key="queue"
+ open={isDropdownOpen}
+ onOpenChange={() => {
+ if (hasAccess) {
+ setIsDropdownOpen(!isDropdownOpen);
+ }
+ }}
+ >
+ <DropdownMenuTrigger asChild>
+ <Button
+ variant="secondary"
+ disabled={!hasAccess}
+ className="rounded-l-none rounded-r-md border-l-2"
+ >
+ {queues.data?.totalCount ? (
+ <span className="relative mr-1 text-xs">
+ <ChevronDown className="h-3 w-3 text-secondary-foreground" />
+ <span className="absolute -top-1.5 left-2.5 flex max-h-[0.8rem] min-w-[0.8rem] items-center justify-center rounded-full border border-muted-foreground bg-accent-light-blue px-[0.2rem] text-[8px]">
+ {queues.data?.totalCount > 99 ? "99+" : queues.data?.totalCount}
+ </span>
+ </span>
+ ) : (
+ <span className="relative mr-1 text-xs">
+ <ChevronDown className="h-3 w-3" />
+ </span>
+ )}
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent>
+ <DropdownMenuLabel>In queue(s)</DropdownMenuLabel>
+ {queues.data?.queues.length ? (
+ queues.data?.queues.map((queue) => (
+ <DropdownMenuCheckboxItem
+ key={queue.id}
+ className="hover:bg-accent"
+ checked={!!queue.itemId}
+ onSelect={(event) => {
+ event.preventDefault();
+ }}
+ onClick={(event) => {
+ event.preventDefault();
+ event.stopPropagation();
+ handleQueueItemToggle(queue.id, queue.name, queue.itemId);
+ }}
+ >
+ {queue.name}
+ {queue.status && (
+ <Badge
+ className={cn(
+ "ml-2 px-1 py-0.5 text-[10px] capitalize",
+ queue.status === AnnotationQueueStatus.COMPLETED
+ ? "bg-light-green text-dark-green"
+ : "bg-light-yellow text-dark-yellow",
+ )}
+ variant="outline"
+ >
+ {queue.status.toLowerCase()}
+ </Badge>
+ )}
+ </DropdownMenuCheckboxItem>
+ ))
+ ) : (
+ <DropdownMenuItem
+ onClick={(event) => {
+ event.preventDefault();
+ event.stopPropagation();
+ }}
+ >
+ No queues defined
+ </DropdownMenuItem>
+ )}
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ key="manage-queues"
+ className="hover:bg-accent"
+ asChild
+ >
+ <div>
+ <ExternalLink className="mr-2 h-4 w-4" />
+ <Link href={`/project/${projectId}/annotation-queues`}>
+ Manage queues
+ </Link>
+ </div>
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+};
diff --git a/web/src/features/scores/components/CreateOrEditAnnotationQueueButton.tsx b/web/src/features/scores/components/CreateOrEditAnnotationQueueButton.tsx
new file mode 100644
index 0000000000..3478ba189c
--- /dev/null
+++ b/web/src/features/scores/components/CreateOrEditAnnotationQueueButton.tsx
@@ -0,0 +1,282 @@
+import { Button } from "@/src/components/ui/button";
+import React, { useEffect, useState } from "react";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/src/components/ui/dialog";
+import {
+ FormControl,
+ FormDescription,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/src/components/ui/form";
+import { Input } from "@/src/components/ui/input";
+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { Edit, LockIcon, PlusIcon } from "lucide-react";
+import { useForm } from "react-hook-form";
+import { Form } from "@/src/components/ui/form";
+import { Textarea } from "@/src/components/ui/textarea";
+import {
+ type CreateQueue,
+ CreateQueueData,
+ type ValidatedScoreConfig,
+} from "@langfuse/shared";
+import { api } from "@/src/utils/api";
+import { getScoreDataTypeIcon } from "@/src/features/scores/components/ScoreDetailColumnHelpers";
+import { MultiSelectKeyValues } from "@/src/features/scores/components/multi-select-key-values";
+import { CommandItem } from "@/src/components/ui/command";
+import { useRouter } from "next/router";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
+
+export const CreateOrEditAnnotationQueueButton = ({
+ projectId,
+ queueId,
+ variant = "secondary",
+}: {
+ projectId: string;
+ queueId?: string;
+ variant?: "secondary" | "ghost";
+}) => {
+ const [isOpen, setIsOpen] = useState(false);
+ const hasAccess = useHasProjectAccess({
+ projectId: projectId,
+ scope: "annotationQueues:CUD",
+ });
+ const router = useRouter();
+ const capture = usePostHogClientCapture();
+
+ const queueQuery = api.annotationQueues.byId.useQuery(
+ { projectId, queueId: queueId as string },
+ { enabled: !!queueId },
+ );
+
+ const form = useForm<CreateQueue>({
+ resolver: zodResolver(CreateQueueData),
+ });
+
+ useEffect(() => {
+ if (queueId && queueQuery.data) {
+ form.reset({
+ name: queueQuery.data.name,
+ description: queueQuery.data.description || undefined,
+ scoreConfigIds: queueQuery.data.scoreConfigs.map(
+ (config: ValidatedScoreConfig) => config.id,
+ ),
+ });
+ } else {
+ form.reset({
+ name: "",
+ scoreConfigIds: [],
+ });
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [queueId, queueQuery.data]);
+
+ const utils = api.useUtils();
+
+ const createQueueMutation = api.annotationQueues.create.useMutation({
+ onSuccess: async () => {
+ await Promise.all([utils.annotationQueues.invalidate()]);
+ form.reset();
+ setIsOpen(false);
+ },
+ });
+ const editQueueMutation = api.annotationQueues.update.useMutation({
+ onSuccess: async () => {
+ await Promise.all([utils.annotationQueues.invalidate()]);
+ form.reset();
+ setIsOpen(false);
+ },
+ });
+
+ const configsData = api.scoreConfigs.all.useQuery(
+ {
+ projectId,
+ },
+ {
+ enabled: hasAccess && isOpen,
+ },
+ );
+
+ const configs = configsData.data?.configs ?? [];
+
+ if (!hasAccess) {
+ return (
+ <Button variant={variant} disabled={true} className="justify-start">
+ <LockIcon className="-ml-0.5 mr-1.5 h-4 w-4" aria-hidden="true" />
+ <span className="text-sm font-normal">
+ {queueId ? "Edit" : "New queue"}
+ </span>
+ </Button>
+ );
+ }
+
+ const onSubmit = (data: CreateQueue) => {
+ if (queueId) {
+ editQueueMutation.mutateAsync({
+ ...data,
+ projectId,
+ queueId,
+ });
+ } else {
+ createQueueMutation.mutateAsync({
+ ...data,
+ projectId,
+ });
+ }
+ };
+
+ const handleOnValueChange = (values: Record<string, string>[]) => {
+ form.setValue(
+ "scoreConfigIds",
+ values.map((value) => value.key),
+ );
+
+ if (values.length === 0) {
+ form.setError("scoreConfigIds", {
+ type: "manual",
+ message: "At least 1 score config must be selected",
+ });
+ } else {
+ form.clearErrors("scoreConfigIds");
+ }
+ };
+
+ return (
+ <Dialog open={isOpen} onOpenChange={setIsOpen}>
+ <DialogTrigger asChild>
+ <Button
+ variant={variant}
+ onClick={() => setIsOpen(true)}
+ className="justify-start"
+ >
+ {queueId ? (
+ <Edit className="-ml-0.5 mr-1.5 h-4 w-4" aria-hidden="true" />
+ ) : (
+ <PlusIcon className="-ml-0.5 mr-1.5 h-4 w-4" aria-hidden="true" />
+ )}
+ <span className="ml-1 text-sm font-normal">
+ {queueId ? "Edit" : "New queue"}
+ </span>
+ </Button>
+ </DialogTrigger>
+ {configsData.data && (
+ <DialogContent className="max-h-[90vh] overflow-y-auto">
+ <DialogHeader>
+ <DialogTitle>
+ {queueId ? "Edit" : "New"} annotation queue
+ </DialogTitle>
+ <DialogDescription>
+ {queueId ? "Edit" : "Create a new"} queue to manage your
+ annotation workflows.
+ </DialogDescription>
+ </DialogHeader>
+ <Form {...form}>
+ <form className="space-y-6" onSubmit={form.handleSubmit(onSubmit)}>
+ <FormField
+ control={form.control}
+ name="name"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Name</FormLabel>
+ <FormControl>
+ <Input
+ {...field}
+ type="text"
+ className="text-xs"
+ onBlur={(e) => field.onChange(e.target.value.trimEnd())}
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ <FormField
+ control={form.control}
+ name="description"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Description (optional)</FormLabel>
+ <FormControl>
+ <Textarea
+ {...field}
+ placeholder="Add description..."
+ className="text-xs focus:outline-none focus:ring-0 focus-visible:ring-0 focus-visible:ring-offset-0 active:ring-0"
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ <FormField
+ control={form.control}
+ name="scoreConfigIds"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Score Configs</FormLabel>
+ <FormDescription>
+ Define which dimensions annotators should score for the
+ given queue.
+ </FormDescription>
+ <FormControl>
+ <MultiSelectKeyValues
+ title="Value"
+ align="end"
+ className="grid grid-cols-[auto,1fr,auto,auto] gap-2"
+ onValueChange={handleOnValueChange}
+ options={configs
+ .filter((config) => !config.isArchived)
+ .map((config) => ({
+ key: config.id,
+ value: `${getScoreDataTypeIcon(config.dataType)} ${config.name}`,
+ isArchived: config.isArchived,
+ }))}
+ values={field.value.map((configId) => {
+ const config = configs.find(
+ (config) => config.id === configId,
+ );
+ return {
+ value: config
+ ? `${getScoreDataTypeIcon(config.dataType)} ${config.name}`
+ : `${configId}`,
+ key: configId,
+ };
+ })}
+ controlButtons={
+ <CommandItem
+ onSelect={() => {
+ capture(
+ "score_configs:manage_configs_item_click",
+ { source: "AnnotationQueue" },
+ );
+ router.push(
+ `/project/${projectId}/settings/scores`,
+ );
+ }}
+ >
+ Manage score configs
+ </CommandItem>
+ }
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ <Button type="submit" className="text-xs">
+ {queueId ? "Save" : "Create"} queue
+ </Button>
+ </form>
+ </Form>
+ </DialogContent>
+ )}
+ </Dialog>
+ );
+};
diff --git a/web/src/features/scores/components/DeleteAnnotationQueueButton.tsx b/web/src/features/scores/components/DeleteAnnotationQueueButton.tsx
new file mode 100644
index 0000000000..4c8975aa51
--- /dev/null
+++ b/web/src/features/scores/components/DeleteAnnotationQueueButton.tsx
@@ -0,0 +1,88 @@
+import { Button } from "@/src/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/src/components/ui/dialog";
+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
+import { api } from "@/src/utils/api";
+import { LockIcon, Trash } from "lucide-react";
+import React, { useState } from "react";
+
+type DeleteAnnotationQueueButtonProps = {
+ projectId: string;
+ queueId: string;
+};
+
+export const DeleteAnnotationQueueButton = ({
+ projectId,
+ queueId,
+}: DeleteAnnotationQueueButtonProps) => {
+ const [isOpen, setIsOpen] = useState(false);
+ const hasAccess = useHasProjectAccess({
+ projectId: projectId,
+ scope: "annotationQueues:CUD",
+ });
+ const utils = api.useUtils();
+ const mutDelete = api.annotationQueues.delete.useMutation({
+ onSuccess: () => {
+ utils.annotationQueues.invalidate();
+ },
+ });
+
+ const button = (
+ <Button variant="ghost" disabled={!hasAccess}>
+ <div className="flex w-full flex-row items-center gap-1">
+ {hasAccess ? (
+ <Trash className="-ml-0.5 mr-1.5 h-4 w-4" />
+ ) : (
+ <LockIcon className="-ml-0.5 mr-1.5 h-4 w-4" aria-hidden="true" />
+ )}
+ <span className="text-sm font-normal">Delete</span>
+ </div>
+ </Button>
+ );
+
+ return hasAccess ? (
+ <Dialog
+ open={isOpen}
+ onOpenChange={(open) => {
+ if (!mutDelete.isLoading) {
+ setIsOpen(open);
+ }
+ }}
+ >
+ <DialogTrigger asChild>{button}</DialogTrigger>
+ <DialogContent className="sm:max-w-xl">
+ <DialogHeader>
+ <DialogTitle className="mb-4">Please confirm</DialogTitle>
+ <DialogDescription className="text-md p-0">
+ This action cannot be undone and removes queue items attached to
+ this queue. Scores added while annotating in this queue will not be
+ deleted.
+ </DialogDescription>
+ </DialogHeader>
+ <Button
+ variant="destructive"
+ loading={mutDelete.isLoading}
+ disabled={mutDelete.isLoading}
+ onClick={async (event) => {
+ event.preventDefault();
+ await mutDelete.mutateAsync({
+ projectId,
+ queueId,
+ });
+ setIsOpen(false);
+ }}
+ >
+ Delete Annotation Queue
+ </Button>
+ </DialogContent>
+ </Dialog>
+ ) : (
+ button
+ );
+};
diff --git a/web/src/pages/project/[projectId]/annotation-queues.tsx b/web/src/pages/project/[projectId]/annotation-queues.tsx
new file mode 100644
index 0000000000..fef21aaa5c
--- /dev/null
+++ b/web/src/pages/project/[projectId]/annotation-queues.tsx
@@ -0,0 +1,40 @@
+import Header from "@/src/components/layouts/header";
+import { useRouter } from "next/router";
+import { FullScreenPage } from "@/src/components/layouts/full-screen-page";
+import { AnnotationQueuesTable } from "@/src/features/scores/components/AnnotationQueuesTable";
+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
+import { useHasOrgEntitlement } from "@/src/features/entitlements/hooks";
+import { SupportOrUpgradePage } from "@/src/ee/features/billing/components/SupportOrUpgradePage";
+import { FeatureFlagToggle } from "@/src/features/feature-flags/components/FeatureFlagToggle";
+
+export default function AnnotationQueues() {
+ const router = useRouter();
+ const projectId = router.query.projectId as string;
+ const hasAccess = useHasProjectAccess({
+ projectId: projectId,
+ scope: "annotationQueues:read",
+ });
+ const hasEntitlement = useHasOrgEntitlement("annotation-queues");
+ if (!hasAccess || !hasEntitlement) return <SupportOrUpgradePage />;
+
+ return (
+ <FullScreenPage>
+ <FeatureFlagToggle
+ featureFlag="annotationQueues"
+ whenEnabled={
+ <>
+ <Header
+ title="Annotation Queues"
+ help={{
+ description:
+ "Annotation queues are used to manage scoring workflows for your LLM projects. See docs to learn more.",
+ href: "https://langfuse.com/docs/scores/annotation",
+ }}
+ />
+ <AnnotationQueuesTable projectId={projectId} />
+ </>
+ }
+ />
+ </FullScreenPage>
+ );
+}
diff --git a/web/src/pages/project/[projectId]/annotation-queues/[queueId]/index.tsx b/web/src/pages/project/[projectId]/annotation-queues/[queueId]/index.tsx
new file mode 100644
index 0000000000..41b9546d57
--- /dev/null
+++ b/web/src/pages/project/[projectId]/annotation-queues/[queueId]/index.tsx
@@ -0,0 +1,186 @@
+import Header from "@/src/components/layouts/header";
+import { api } from "@/src/utils/api";
+import { useRouter } from "next/router";
+import { FullScreenPage } from "@/src/components/layouts/full-screen-page";
+import { AnnotationQueueItemsTable } from "@/src/features/scores/components/AnnotationQueueItemsTable";
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from "@/src/components/ui/card";
+import { Button } from "@/src/components/ui/button";
+import { ChevronRight, ClipboardPen, Lock } from "lucide-react";
+import { Separator } from "@/src/components/ui/separator";
+import { useState } from "react";
+import { Badge } from "@/src/components/ui/badge";
+import { getScoreDataTypeIcon } from "@/src/features/scores/components/ScoreDetailColumnHelpers";
+import Link from "next/link";
+import { CreateOrEditAnnotationQueueButton } from "@/src/features/scores/components/CreateOrEditAnnotationQueueButton";
+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
+import { useHasOrgEntitlement } from "@/src/features/entitlements/hooks";
+import { SupportOrUpgradePage } from "@/src/ee/features/billing/components/SupportOrUpgradePage";
+import { FeatureFlagToggle } from "@/src/features/feature-flags/components/FeatureFlagToggle";
+import { Skeleton } from "@/src/components/ui/skeleton";
+
+const TableWithMetadataWrapper = ({
+ tableComponent,
+ cardTitleChildren,
+ cardContentChildren,
+}: {
+ tableComponent: React.ReactNode;
+ cardTitleChildren: React.ReactNode;
+ cardContentChildren: React.ReactNode;
+}) => {
+ const [isCollapsed, setIsCollapsed] = useState(false);
+
+ return (
+ <div
+ className={`grid h-[calc(100dvh-8rem)] ${isCollapsed ? "grid-cols-[2fr,auto]" : "grid-cols-[2fr,1fr]"} gap-4 overflow-hidden lg:h-[calc(100dvh-4rem)]`}
+ >
+ <div className="flex h-full flex-col overflow-hidden">
+ {tableComponent}
+ </div>
+ <div
+ className={`my-2 flex flex-row ${isCollapsed ? "w-8" : "w-full"} h-full overflow-hidden`}
+ >
+ <div className="grid h-full w-full grid-cols-[auto,1fr] items-start gap-2 overflow-hidden">
+ <div className="grid h-full w-full grid-rows-[auto,1fr] gap-2">
+ <Button
+ variant="outline"
+ size="icon"
+ onClick={() => setIsCollapsed(!isCollapsed)}
+ >
+ <ChevronRight
+ className={`h-4 w-4 transform ${isCollapsed ? "rotate-180" : ""}`}
+ />
+ </Button>
+ <Separator orientation="vertical" className="ml-4 h-full" />
+ </div>
+ <div
+ className={`${isCollapsed ? "hidden" : "block"} mt-8 grid h-[calc(100%-2rem)] w-full grid-rows-[auto,1fr] gap-2 overflow-hidden p-2`}
+ >
+ <Card className="flex h-full flex-col overflow-hidden">
+ <div className="flex h-full overflow-y-auto">
+ <CardHeader className="flex h-full w-full flex-col space-y-4">
+ <CardTitle className="flex justify-between text-xl font-bold leading-7 sm:tracking-tight">
+ {cardTitleChildren}
+ </CardTitle>
+ <CardContent className="flex-1 space-y-4 p-0">
+ {cardContentChildren}
+ </CardContent>
+ </CardHeader>
+ </div>
+ </Card>
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+};
+
+export default function QueueItems() {
+ const router = useRouter();
+ const projectId = router.query.projectId as string;
+ const queueId = router.query.queueId as string;
+
+ const queue = api.annotationQueues.byId.useQuery({
+ queueId,
+ projectId,
+ });
+
+ const hasReadAccess = useHasProjectAccess({
+ projectId,
+ scope: "annotationQueues:read",
+ });
+ const hasWriteAccess = useHasProjectAccess({
+ projectId,
+ scope: "annotationQueues:CUD",
+ });
+ const hasEntitlement = useHasOrgEntitlement("annotation-queues");
+ if (!hasReadAccess || !hasEntitlement) return <SupportOrUpgradePage />;
+
+ return (
+ <FullScreenPage>
+ <FeatureFlagToggle
+ featureFlag="annotationQueues"
+ whenEnabled={
+ <>
+ <Header
+ title={queue.data?.name ?? queueId}
+ breadcrumb={[
+ {
+ name: "Annotation Queues",
+ href: `/project/${projectId}/annotation-queues`,
+ },
+ { name: queue.data?.name ?? queueId },
+ ]}
+ actionButtons={
+ !hasWriteAccess ? (
+ <Button disabled>
+ <Lock className="mr-1 h-4 w-4" />
+ <span className="text-sm">Process queue</span>
+ </Button>
+ ) : (
+ <Button asChild>
+ <Link
+ href={`/project/${projectId}/annotation-queues/${queueId}/items`}
+ >
+ <ClipboardPen className="mr-1 h-4 w-4" />
+ <span className="text-sm">Process queue</span>
+ </Link>
+ </Button>
+ )
+ }
+ />
+ <TableWithMetadataWrapper
+ tableComponent={
+ <AnnotationQueueItemsTable
+ projectId={projectId}
+ queueId={queueId}
+ />
+ }
+ cardTitleChildren={
+ <div className="flex w-full flex-row items-center justify-between">
+ {queue.data ? (
+ <span>{queue.data.name}</span>
+ ) : (
+ <Skeleton className="h-full w-1/2" />
+ )}
+ <CreateOrEditAnnotationQueueButton
+ projectId={projectId}
+ queueId={queueId}
+ />
+ </div>
+ }
+ cardContentChildren={
+ <>
+ {queue.data?.description && (
+ <CardDescription className="text-sm">
+ {queue.data?.description}
+ </CardDescription>
+ )}
+ <Separator orientation="horizontal" />
+ <h5 className="text-md font-bold leading-7 sm:tracking-tight">
+ Score Configs
+ </h5>
+ {queue.data?.scoreConfigs.map((scoreConfig) => (
+ <Badge
+ key={scoreConfig.id}
+ className="mr-2"
+ variant="outline"
+ >
+ {getScoreDataTypeIcon(scoreConfig.dataType)}
+ <span className="ml-0.5">{scoreConfig.name}</span>
+ </Badge>
+ ))}
+ </>
+ }
+ />
+ </>
+ }
+ />
+ </FullScreenPage>
+ );
+}
diff --git a/web/src/pages/project/[projectId]/annotation-queues/[queueId]/items/[itemId].tsx b/web/src/pages/project/[projectId]/annotation-queues/[queueId]/items/[itemId].tsx
new file mode 100644
index 0000000000..a0a25679ac
--- /dev/null
+++ b/web/src/pages/project/[projectId]/annotation-queues/[queueId]/items/[itemId].tsx
@@ -0,0 +1,17 @@
+import { AnnotationQueuesItem } from "@/src/features/scores/components/AnnotationQueuesItem";
+import { useRouter } from "next/router";
+
+export default function AnnotationQueues() {
+ const router = useRouter();
+ const annotationQueueId = router.query.queueId as string;
+ const projectId = router.query.projectId as string;
+ const itemId = router.query.itemId as string;
+
+ return (
+ <AnnotationQueuesItem
+ annotationQueueId={annotationQueueId}
+ projectId={projectId}
+ itemId={itemId}
+ />
+ );
+}
diff --git a/web/src/pages/project/[projectId]/annotation-queues/[queueId]/items/index.tsx b/web/src/pages/project/[projectId]/annotation-queues/[queueId]/items/index.tsx
new file mode 100644
index 0000000000..96b1164cf5
--- /dev/null
+++ b/web/src/pages/project/[projectId]/annotation-queues/[queueId]/items/index.tsx
@@ -0,0 +1,15 @@
+import { AnnotationQueuesItem } from "@/src/features/scores/components/AnnotationQueuesItem";
+import { useRouter } from "next/router";
+
+export default function AnnotationQueues() {
+ const router = useRouter();
+ const annotationQueueId = router.query.queueId as string;
+ const projectId = router.query.projectId as string;
+
+ return (
+ <AnnotationQueuesItem
+ annotationQueueId={annotationQueueId}
+ projectId={projectId}
+ />
+ );
+}
diff --git a/web/src/server/api/root.ts b/web/src/server/api/root.ts
index 4ef8e3d8c8..6052dd3129 100644
--- a/web/src/server/api/root.ts
+++ b/web/src/server/api/root.ts
@@ -24,6 +24,8 @@ import { batchExportRouter } from "@/src/server/api/routers/batchExport";
import { utilsRouter } from "@/src/server/api/routers/utilities";
import { uiCustomizationRouter } from "@/src/ee/features/ui-customization/uiCustomizationRouter";
import { commentsRouter } from "@/src/server/api/routers/comments";
+import { queueRouter } from "@/src/server/api/routers/annotationQueues";
+import { queueItemRouter } from "@/src/server/api/routers/annotationQueueItems";
/**
* This is the primary router for your server.
@@ -31,6 +33,8 @@ import { commentsRouter } from "@/src/server/api/routers/comments";
* All routers added in /api/routers should be manually added here.
*/
export const appRouter = createTRPCRouter({
+ annotationQueues: queueRouter,
+ annotationQueueItems: queueItemRouter,
batchExport: batchExportRouter,
traces: traceRouter,
sessions: sessionRouter,
diff --git a/web/src/server/api/routers/annotationQueueItems.ts b/web/src/server/api/routers/annotationQueueItems.ts
new file mode 100644
index 0000000000..cd5fbfee95
--- /dev/null
+++ b/web/src/server/api/routers/annotationQueueItems.ts
@@ -0,0 +1,445 @@
+import { auditLog } from "@/src/features/audit-logs/auditLog";
+import { throwIfNoEntitlement } from "@/src/features/entitlements/server/hasEntitlement";
+import { throwIfNoProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
+import {
+ createTRPCRouter,
+ protectedProjectProcedure,
+} from "@/src/server/api/trpc";
+import {
+ type AnnotationQueueItem,
+ AnnotationQueueObjectType,
+ AnnotationQueueStatus,
+ paginationZod,
+ Prisma,
+} from "@langfuse/shared";
+import { logger } from "@langfuse/shared/src/server";
+import { TRPCError } from "@trpc/server";
+import { z } from "zod";
+
+const isItemLocked = (item: AnnotationQueueItem) => {
+ return (
+ item.lockedByUserId &&
+ item.lockedAt &&
+ new Date(item.lockedAt) > new Date(Date.now() - 5 * 60 * 1000)
+ );
+};
+
+export const queueItemRouter = createTRPCRouter({
+ byId: protectedProjectProcedure
+ .input(
+ z.object({
+ projectId: z.string(),
+ itemId: z.string(),
+ }),
+ )
+ .query(async ({ input, ctx }) => {
+ try {
+ throwIfNoEntitlement({
+ entitlement: "annotation-queues",
+ projectId: input.projectId,
+ sessionUser: ctx.session.user,
+ });
+
+ throwIfNoProjectAccess({
+ session: ctx.session,
+ projectId: input.projectId,
+ scope: "annotationQueues:read",
+ });
+
+ const item = await ctx.prisma.annotationQueueItem.findUnique({
+ where: {
+ id: input.itemId,
+ projectId: input.projectId,
+ },
+ });
+
+ // Expected behavior, non-error case: if user has seen item in given session, prior to it being deleted, we return null
+ if (!item) return null;
+ let lockedByUser: { name: string | null } | null = null;
+
+ if (isItemLocked(item)) {
+ lockedByUser = await ctx.prisma.user.findUnique({
+ where: {
+ id: item.lockedByUserId as string,
+ },
+ select: {
+ name: true,
+ },
+ });
+ }
+
+ const inflatedItem = {
+ ...item,
+ lockedByUser,
+ };
+
+ if (item.objectType === AnnotationQueueObjectType.OBSERVATION) {
+ const observation = await ctx.prisma.observation.findUnique({
+ where: {
+ id: item.objectId,
+ projectId: input.projectId,
+ },
+ select: {
+ id: true,
+ traceId: true,
+ },
+ });
+
+ return {
+ ...inflatedItem,
+ parentTraceId: observation?.traceId,
+ };
+ }
+
+ return inflatedItem;
+ } catch (error) {
+ logger.error(error);
+ if (error instanceof TRPCError) {
+ throw error;
+ }
+ throw new TRPCError({
+ code: "INTERNAL_SERVER_ERROR",
+ message: "Fetching annotation queue item by id failed.",
+ });
+ }
+ }),
+ itemsByQueueId: protectedProjectProcedure
+ .input(
+ z.object({
+ queueId: z.string(),
+ projectId: z.string(),
+ ...paginationZod,
+ }),
+ )
+ .query(async ({ input, ctx }) => {
+ try {
+ throwIfNoEntitlement({
+ entitlement: "annotation-queues",
+ projectId: input.projectId,
+ sessionUser: ctx.session.user,
+ });
+
+ throwIfNoProjectAccess({
+ session: ctx.session,
+ projectId: input.projectId,
+ scope: "annotationQueues:read",
+ });
+
+ const [queueItems, totalItems] = await Promise.all([
+ // queueItems
+ ctx.prisma.$queryRaw<
+ Array<{
+ id: string;
+ status: AnnotationQueueStatus;
+ objectId: string;
+ objectType: AnnotationQueueObjectType;
+ parentTraceId: string | null;
+ completedAt: string | null;
+ annotatorUserId: string | null;
+ annotatorUserImage: string | null;
+ annotatorUserName: string | null;
+ }>
+ >(Prisma.sql`
+ SELECT
+ aqi.id,
+ aqi.status,
+ aqi.object_id AS "objectId",
+ aqi.object_type AS "objectType",
+ o.trace_id AS "parentTraceId",
+ aqi.completed_at AS "completedAt",
+ aqi.annotator_user_id AS "annotatorUserId",
+ u.image AS "annotatorUserImage",
+ u.name AS "annotatorUserName"
+ FROM
+ annotation_queue_items aqi
+ LEFT JOIN
+ observations o ON o.id = aqi.object_id AND aqi.object_type = 'OBSERVATION' AND o.project_id = ${input.projectId}
+ LEFT JOIN
+ users u ON u.id = aqi.annotator_user_id AND u.id in (SELECT user_id FROM organization_memberships WHERE org_id = ${ctx.session.orgId})
+ WHERE
+ aqi.project_id = ${input.projectId} AND aqi.queue_id = ${input.queueId}
+ ORDER BY
+ aqi.created_at ASC,
+ aqi.object_id ASC,
+ aqi.object_type ASC
+ ${input.limit ? Prisma.sql`LIMIT ${input.limit}` : Prisma.empty}
+ ${input.page && input.limit ? Prisma.sql`OFFSET ${input.page * input.limit}` : Prisma.empty}
+ `),
+ // totalItems
+ ctx.prisma.annotationQueueItem.count({
+ where: {
+ queueId: input.queueId,
+ projectId: input.projectId,
+ },
+ }),
+ ]);
+
+ return { queueItems, totalItems };
+ } catch (error) {
+ logger.error(error);
+ if (error instanceof TRPCError) {
+ throw error;
+ }
+ throw new TRPCError({
+ code: "INTERNAL_SERVER_ERROR",
+ message: "Fetching annotation queue items failed.",
+ });
+ }
+ }),
+ unseenPendingItemCountByQueueId: protectedProjectProcedure
+ .input(
+ z.object({
+ queueId: z.string(),
+ projectId: z.string(),
+ seenItemIds: z.array(z.string()),
+ }),
+ )
+ .query(async ({ input, ctx }) => {
+ try {
+ throwIfNoEntitlement({
+ entitlement: "annotation-queues",
+ projectId: input.projectId,
+ sessionUser: ctx.session.user,
+ });
+
+ throwIfNoProjectAccess({
+ session: ctx.session,
+ projectId: input.projectId,
+ scope: "annotationQueues:read",
+ });
+
+ const count = await ctx.prisma.annotationQueueItem.count({
+ where: {
+ queueId: input.queueId,
+ projectId: input.projectId,
+ status: AnnotationQueueStatus.PENDING,
+ id: {
+ notIn: input.seenItemIds,
+ },
+ },
+ });
+ return count;
+ } catch (error) {
+ logger.error(error);
+ if (error instanceof TRPCError) {
+ throw error;
+ }
+ throw new TRPCError({
+ code: "INTERNAL_SERVER_ERROR",
+ message: "Fetching unseen pending item count by queueId failed.",
+ });
+ }
+ }),
+ createMany: protectedProjectProcedure
+ .input(
+ z.object({
+ projectId: z.string(),
+ queueId: z.string(),
+ objectIds: z
+ .array(z.string())
+ .min(1, "Minimum 1 object_id is required."),
+ objectType: z.nativeEnum(AnnotationQueueObjectType),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ try {
+ throwIfNoEntitlement({
+ entitlement: "annotation-queues",
+ projectId: input.projectId,
+ sessionUser: ctx.session.user,
+ });
+
+ throwIfNoProjectAccess({
+ session: ctx.session,
+ projectId: input.projectId,
+ scope: "annotationQueues:CUD",
+ });
+
+ const { count } = await ctx.prisma.annotationQueueItem.createMany({
+ data: input.objectIds.map((objectId) => ({
+ projectId: input.projectId,
+ queueId: input.queueId,
+ objectId,
+ objectType: input.objectType,
+ })),
+ skipDuplicates: true,
+ });
+
+ const createdItems = await ctx.prisma.annotationQueueItem.findMany({
+ where: {
+ projectId: input.projectId,
+ queueId: input.queueId,
+ objectId: { in: input.objectIds },
+ objectType: input.objectType,
+ },
+ orderBy: { createdAt: "desc" },
+ });
+
+ for (const item of createdItems) {
+ await auditLog(
+ {
+ session: ctx.session,
+ resourceType: "annotationQueueItem",
+ resourceId: item.id,
+ action: "create",
+ after: item,
+ },
+ ctx.prisma,
+ );
+ }
+
+ const queue = await ctx.prisma.annotationQueue.findUnique({
+ where: {
+ id: input.queueId,
+ projectId: input.projectId,
+ },
+ select: {
+ name: true,
+ id: true,
+ },
+ });
+
+ return {
+ createdCount: count,
+ queueName: queue?.name,
+ queueId: queue?.id,
+ };
+ } catch (error) {
+ logger.error(error);
+ if (error instanceof TRPCError) {
+ throw error;
+ }
+ throw new TRPCError({
+ code: "INTERNAL_SERVER_ERROR",
+ message: "Creating multiple annotation queue items failed.",
+ });
+ }
+ }),
+ deleteMany: protectedProjectProcedure
+ .input(
+ z.object({
+ itemIds: z.array(z.string()).min(1, "Minimum 1 item_id is required."),
+ projectId: z.string(),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ try {
+ throwIfNoEntitlement({
+ entitlement: "annotation-queues",
+ projectId: input.projectId,
+ sessionUser: ctx.session.user,
+ });
+
+ throwIfNoProjectAccess({
+ session: ctx.session,
+ projectId: input.projectId,
+ scope: "annotationQueues:CUD",
+ });
+
+ const items = await ctx.prisma.annotationQueueItem.findMany({
+ where: {
+ id: {
+ in: input.itemIds,
+ },
+ projectId: input.projectId,
+ },
+ });
+
+ for (const item of items) {
+ await auditLog({
+ resourceType: "annotationQueueItem",
+ resourceId: item.id,
+ before: item,
+ action: "delete",
+ session: ctx.session,
+ });
+ }
+
+ const { count } = await ctx.prisma.annotationQueueItem.deleteMany({
+ where: {
+ id: {
+ in: input.itemIds,
+ },
+ projectId: input.projectId,
+ },
+ });
+
+ return {
+ deletedCount: count,
+ };
+ } catch (error) {
+ logger.error(error);
+ if (error instanceof TRPCError) {
+ throw error;
+ }
+ throw new TRPCError({
+ code: "INTERNAL_SERVER_ERROR",
+ message: "Deleting annotation queue items failed.",
+ });
+ }
+ }),
+ complete: protectedProjectProcedure
+ .input(
+ z.object({
+ projectId: z.string(),
+ itemId: z.string(),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ try {
+ throwIfNoEntitlement({
+ entitlement: "annotation-queues",
+ projectId: input.projectId,
+ sessionUser: ctx.session.user,
+ });
+
+ throwIfNoProjectAccess({
+ session: ctx.session,
+ projectId: input.projectId,
+ scope: "annotationQueues:CUD",
+ });
+
+ const item = await ctx.prisma.annotationQueueItem.update({
+ where: {
+ id: input.itemId,
+ projectId: input.projectId,
+ status: AnnotationQueueStatus.PENDING,
+ },
+ data: {
+ status: AnnotationQueueStatus.COMPLETED,
+ completedAt: new Date(),
+ annotatorUserId: ctx.session.user.id,
+ },
+ });
+
+ await auditLog({
+ resourceType: "annotationQueueItem",
+ resourceId: item.id,
+ action: "complete",
+ after: item,
+ session: ctx.session,
+ });
+
+ return item;
+ } catch (error) {
+ logger.error(error);
+ if (error instanceof TRPCError) {
+ throw error;
+ }
+ if (
+ error instanceof Prisma.PrismaClientKnownRequestError &&
+ error.code === "P2025"
+ ) {
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message:
+ "The item to complete was not found, it was likely deleted.",
+ });
+ }
+ throw new TRPCError({
+ code: "INTERNAL_SERVER_ERROR",
+ message: "Completing annotation queue item failed.",
+ });
+ }
+ }),
+});
diff --git a/web/src/server/api/routers/annotationQueues.ts b/web/src/server/api/routers/annotationQueues.ts
new file mode 100644
index 0000000000..5a05fa4dea
--- /dev/null
+++ b/web/src/server/api/routers/annotationQueues.ts
@@ -0,0 +1,522 @@
+import { auditLog } from "@/src/features/audit-logs/auditLog";
+import { throwIfNoEntitlement } from "@/src/features/entitlements/server/hasEntitlement";
+import { throwIfNoProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
+import {
+ createTRPCRouter,
+ protectedProjectProcedure,
+} from "@/src/server/api/trpc";
+import {
+ AnnotationQueueObjectType,
+ AnnotationQueueStatus,
+ CreateQueueData,
+ filterAndValidateDbScoreConfigList,
+ LangfuseNotFoundError,
+ optionalPaginationZod,
+ Prisma,
+} from "@langfuse/shared";
+import { logger } from "@langfuse/shared/src/server";
+import { TRPCError } from "@trpc/server";
+import { z } from "zod";
+
+export const queueRouter = createTRPCRouter({
+ all: protectedProjectProcedure
+ .input(
+ z.object({
+ projectId: z.string(),
+ ...optionalPaginationZod,
+ }),
+ )
+ .query(async ({ input, ctx }) => {
+ try {
+ throwIfNoEntitlement({
+ entitlement: "annotation-queues",
+ projectId: input.projectId,
+ sessionUser: ctx.session.user,
+ });
+
+ throwIfNoProjectAccess({
+ session: ctx.session,
+ projectId: input.projectId,
+ scope: "annotationQueues:read",
+ });
+
+ const [queues, totalCount, scoreConfigs] = await Promise.all([
+ ctx.prisma.$queryRaw<
+ Array<{
+ id: string;
+ name: string;
+ description?: string | null;
+ scoreConfigIds: string[];
+ createdAt: string;
+ countCompletedItems: number;
+ countPendingItems: number;
+ }>
+ >(Prisma.sql`
+ SELECT
+ aq.id,
+ aq.name,
+ aq.description,
+ aq.score_config_ids AS "scoreConfigIds",
+ aq.created_at AS "createdAt",
+ COALESCE(SUM(CASE WHEN aqi.status = 'COMPLETED' THEN 1 ELSE 0 END), 0) AS "countCompletedItems",
+ COALESCE(SUM(CASE WHEN aqi.status = 'PENDING' THEN 1 ELSE 0 END), 0) AS "countPendingItems"
+ FROM
+ annotation_queues aq
+ LEFT JOIN
+ annotation_queue_items aqi ON aq.id = aqi.queue_id AND aqi.project_id = aq.project_id
+ WHERE
+ aq.project_id = ${input.projectId}
+ GROUP BY
+ aq.id, aq.name, aq.description, aq.created_at
+ ORDER BY
+ aq.created_at DESC
+ ${input.limit ? Prisma.sql`LIMIT ${input.limit}` : Prisma.empty}
+ ${input.page && input.limit ? Prisma.sql`OFFSET ${input.page * input.limit}` : Prisma.empty}
+ `),
+ ctx.prisma.annotationQueue.count({
+ where: {
+ projectId: input.projectId,
+ },
+ }),
+ ctx.prisma.scoreConfig.findMany({
+ where: {
+ projectId: input.projectId,
+ },
+ select: {
+ id: true,
+ name: true,
+ dataType: true,
+ },
+ }),
+ ]);
+
+ return {
+ totalCount,
+ queues: queues.map((queue) => ({
+ ...queue,
+ scoreConfigs: scoreConfigs.filter((config) =>
+ queue.scoreConfigIds.includes(config.id),
+ ),
+ })),
+ };
+ } catch (error) {
+ logger.error(error);
+ if (error instanceof TRPCError) {
+ throw error;
+ }
+ throw new TRPCError({
+ code: "INTERNAL_SERVER_ERROR",
+ message: "Fetching annotation queues failed.",
+ });
+ }
+ }),
+ allNamesAndIds: protectedProjectProcedure
+ .input(
+ z.object({
+ projectId: z.string(),
+ }),
+ )
+ .query(async ({ input, ctx }) => {
+ try {
+ throwIfNoEntitlement({
+ entitlement: "annotation-queues",
+ projectId: input.projectId,
+ sessionUser: ctx.session.user,
+ });
+
+ const queueNamesAndIds = await ctx.prisma.annotationQueue.findMany({
+ where: {
+ projectId: input.projectId,
+ },
+ select: {
+ id: true,
+ name: true,
+ },
+ });
+
+ return queueNamesAndIds;
+ } catch (error) {
+ logger.error(error);
+ if (error instanceof TRPCError) {
+ throw error;
+ }
+ throw new TRPCError({
+ code: "INTERNAL_SERVER_ERROR",
+ message: "Fetching annotation queues failed.",
+ });
+ }
+ }),
+ byId: protectedProjectProcedure
+ .input(z.object({ queueId: z.string(), projectId: z.string() }))
+ .query(async ({ input, ctx }) => {
+ try {
+ throwIfNoEntitlement({
+ entitlement: "annotation-queues",
+ projectId: input.projectId,
+ sessionUser: ctx.session.user,
+ });
+
+ throwIfNoProjectAccess({
+ session: ctx.session,
+ projectId: input.projectId,
+ scope: "annotationQueues:read",
+ });
+
+ const queue = await ctx.prisma.annotationQueue.findUnique({
+ where: { id: input.queueId, projectId: input.projectId },
+ });
+
+ const configs = await ctx.prisma.scoreConfig.findMany({
+ where: {
+ projectId: input.projectId,
+ id: {
+ in: queue?.scoreConfigIds ?? [],
+ },
+ },
+ });
+
+ return {
+ ...queue,
+ scoreConfigs: filterAndValidateDbScoreConfigList(configs),
+ };
+ } catch (error) {
+ logger.error(error);
+ if (error instanceof TRPCError) {
+ throw error;
+ }
+ throw new TRPCError({
+ code: "INTERNAL_SERVER_ERROR",
+ message: "Fetching annotation queue failed.",
+ });
+ }
+ }),
+ byObjectId: protectedProjectProcedure
+ .input(
+ z.object({
+ projectId: z.string(),
+ objectId: z.string(),
+ objectType: z.nativeEnum(AnnotationQueueObjectType),
+ }),
+ )
+ .query(async ({ input, ctx }) => {
+ try {
+ throwIfNoEntitlement({
+ entitlement: "annotation-queues",
+ projectId: input.projectId,
+ sessionUser: ctx.session.user,
+ });
+
+ throwIfNoProjectAccess({
+ session: ctx.session,
+ projectId: input.projectId,
+ scope: "annotationQueues:read",
+ });
+
+ const queues = await ctx.prisma.annotationQueue.findMany({
+ where: {
+ projectId: input.projectId,
+ },
+ select: {
+ id: true,
+ name: true,
+ annotationQueueItem: {
+ where: {
+ objectId: input.objectId,
+ objectType: input.objectType,
+ },
+ select: {
+ queueId: true,
+ status: true,
+ id: true,
+ },
+ },
+ },
+ });
+
+ let totalCount = 0;
+
+ return {
+ queues: queues.map((queue) => {
+ totalCount += queue.annotationQueueItem.length;
+ return {
+ id: queue.id,
+ name: queue.name,
+ itemId: queue.annotationQueueItem[0]?.id, // Safely access the first item's id
+ status: queue.annotationQueueItem[0]?.status, // Safely access the first item's status
+ // Since there may be multiple queue items in a given queue, but with the same objectId, we select only the first one
+ // to simplify the logic and because we are only interested in the first item's details.
+ };
+ }),
+ totalCount,
+ // If the given objectId has been added to the same queue more than once, the total count will reflect that, by counting each item (incl duplicates)
+ };
+ } catch (error) {
+ logger.error(error);
+ if (error instanceof TRPCError) {
+ throw error;
+ }
+ throw new TRPCError({
+ code: "INTERNAL_SERVER_ERROR",
+ message: "Fetching annotation queue by objectId failed.",
+ });
+ }
+ }),
+ create: protectedProjectProcedure
+ .input(
+ CreateQueueData.extend({
+ projectId: z.string(),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ try {
+ throwIfNoEntitlement({
+ entitlement: "annotation-queues",
+ projectId: input.projectId,
+ sessionUser: ctx.session.user,
+ });
+
+ throwIfNoProjectAccess({
+ session: ctx.session,
+ projectId: input.projectId,
+ scope: "annotationQueues:CUD",
+ });
+
+ const existingQueue = await ctx.prisma.annotationQueue.findFirst({
+ where: {
+ projectId: input.projectId,
+ name: input.name,
+ },
+ });
+
+ if (existingQueue) {
+ throw new TRPCError({
+ code: "CONFLICT",
+ message: "A queue with this name already exists in the project",
+ });
+ }
+
+ const queue = await ctx.prisma.annotationQueue.create({
+ data: {
+ name: input.name,
+ projectId: input.projectId,
+ description: input.description,
+ scoreConfigIds: input.scoreConfigIds,
+ },
+ });
+
+ await auditLog({
+ session: ctx.session,
+ resourceType: "annotationQueue",
+ resourceId: queue.id,
+ action: "create",
+ after: queue,
+ });
+
+ return queue;
+ } catch (error) {
+ logger.error(error);
+ if (error instanceof TRPCError) {
+ throw error;
+ }
+ throw new TRPCError({
+ code: "INTERNAL_SERVER_ERROR",
+ message: "Creating annotation queue failed.",
+ });
+ }
+ }),
+ update: protectedProjectProcedure
+ .input(
+ CreateQueueData.extend({
+ projectId: z.string(),
+ queueId: z.string(),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ try {
+ throwIfNoEntitlement({
+ entitlement: "annotation-queues",
+ projectId: input.projectId,
+ sessionUser: ctx.session.user,
+ });
+
+ throwIfNoProjectAccess({
+ session: ctx.session,
+ projectId: input.projectId,
+ scope: "annotationQueues:CUD",
+ });
+
+ const queue = await ctx.prisma.annotationQueue.findFirst({
+ where: {
+ id: input.queueId,
+ projectId: input.projectId,
+ name: input.name,
+ },
+ });
+
+ if (!queue) {
+ throw new LangfuseNotFoundError("Queue not found in project");
+ }
+
+ const updatedQueue = await ctx.prisma.annotationQueue.update({
+ where: { id: input.queueId, projectId: input.projectId },
+ data: {
+ name: input.name,
+ description: input.description,
+ scoreConfigIds: input.scoreConfigIds,
+ },
+ });
+
+ await auditLog({
+ session: ctx.session,
+ resourceType: "annotationQueue",
+ resourceId: queue.id,
+ action: "update",
+ before: queue,
+ after: updatedQueue,
+ });
+
+ return updatedQueue;
+ } catch (error) {
+ logger.error(error);
+ if (error instanceof TRPCError) {
+ throw error;
+ }
+ throw new TRPCError({
+ code: "INTERNAL_SERVER_ERROR",
+ message: "Updating annotation queue failed.",
+ });
+ }
+ }),
+ delete: protectedProjectProcedure
+ .input(z.object({ queueId: z.string(), projectId: z.string() }))
+ .mutation(async ({ input, ctx }) => {
+ try {
+ throwIfNoEntitlement({
+ entitlement: "annotation-queues",
+ projectId: input.projectId,
+ sessionUser: ctx.session.user,
+ });
+
+ throwIfNoProjectAccess({
+ session: ctx.session,
+ projectId: input.projectId,
+ scope: "annotationQueues:CUD",
+ });
+ const queue = await ctx.prisma.annotationQueue.delete({
+ where: { id: input.queueId, projectId: input.projectId },
+ });
+
+ await auditLog({
+ session: ctx.session,
+ resourceType: "annotationQueue",
+ resourceId: queue.id,
+ action: "delete",
+ before: queue,
+ });
+
+ return queue;
+ } catch (error) {
+ logger.error(error);
+ if (error instanceof TRPCError) {
+ throw error;
+ }
+ throw new TRPCError({
+ code: "INTERNAL_SERVER_ERROR",
+ message: "Deleting annotation queue failed.",
+ });
+ }
+ }),
+ fetchAndLockNext: protectedProjectProcedure
+ .input(
+ z.object({
+ queueId: z.string(),
+ projectId: z.string(),
+ seenItemIds: z.array(z.string()),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ try {
+ throwIfNoEntitlement({
+ entitlement: "annotation-queues",
+ projectId: input.projectId,
+ sessionUser: ctx.session.user,
+ });
+
+ throwIfNoProjectAccess({
+ session: ctx.session,
+ projectId: input.projectId,
+ scope: "annotationQueues:CUD",
+ });
+
+ const now = new Date();
+ const fiveMinutesAgo = new Date(now.getTime() - 5 * 60 * 1000);
+
+ const item = await ctx.prisma.annotationQueueItem.findFirst({
+ where: {
+ queueId: input.queueId,
+ projectId: input.projectId,
+ status: AnnotationQueueStatus.PENDING,
+ OR: [
+ { lockedAt: null },
+ { lockedAt: { lt: fiveMinutesAgo } },
+ { lockedByUserId: ctx.session.user.id },
+ ],
+ NOT: {
+ id: { in: input.seenItemIds },
+ },
+ },
+ orderBy: {
+ createdAt: "asc",
+ },
+ });
+
+ // Expected behavior, non-error case: all items have been seen AND/OR completed, no more unseen pending items
+ if (!item) return null;
+
+ const updatedItem = await ctx.prisma.annotationQueueItem.update({
+ where: {
+ id: item.id,
+ projectId: input.projectId,
+ },
+ data: {
+ lockedAt: now,
+ lockedByUserId: ctx.session.user.id,
+ },
+ });
+
+ const inflatedUpdatedItem = {
+ ...updatedItem,
+ lockedByUser: { name: ctx.session.user.name },
+ };
+
+ if (item.objectType === AnnotationQueueObjectType.OBSERVATION) {
+ const observation = await ctx.prisma.observation.findUnique({
+ where: {
+ id: item.objectId,
+ projectId: input.projectId,
+ },
+ select: {
+ id: true,
+ traceId: true,
+ },
+ });
+
+ return {
+ ...inflatedUpdatedItem,
+ parentTraceId: observation?.traceId,
+ };
+ }
+
+ return inflatedUpdatedItem;
+ } catch (error) {
+ logger.error(error);
+ if (error instanceof TRPCError) {
+ throw error;
+ }
+ throw new TRPCError({
+ code: "INTERNAL_SERVER_ERROR",
+ message: "Fetching and locking next annotation queue item failed.",
+ });
+ }
+ }),
+});
diff --git a/web/src/server/api/routers/scores.ts b/web/src/server/api/routers/scores.ts
index c11b6ccdc5..885a1fe8ac 100644
--- a/web/src/server/api/routers/scores.ts
+++ b/web/src/server/api/routers/scores.ts
@@ -213,6 +213,7 @@ export const scoresRouter = createTRPCRouter({
stringValue: input.stringValue,
comment: input.comment,
authorUserId: ctx.session.user.id,
+ queueId: input.queueId,
},
});
await auditLog({
@@ -239,6 +240,7 @@ export const scoresRouter = createTRPCRouter({
comment: input.comment,
authorUserId: ctx.session.user.id,
source: "ANNOTATION",
+ queueId: input.queueId,
},
});
@@ -279,6 +281,7 @@ export const scoresRouter = createTRPCRouter({
stringValue: input.stringValue,
comment: input.comment,
authorUserId: ctx.session.user.id,
+ queueId: input.queueId,
},
});