Skip to content

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

Remove foreign key conditions (#74)

Maximilian Deichmann39d1abde525e
diff --git a/fern/server/definition/commons.yml b/fern/server/definition/commons.yml
index 26d00076cf..e7d3190ca6 100644
--- a/fern/server/definition/commons.yml
+++ b/fern/server/definition/commons.yml
@@ -58,7 +58,7 @@ types:
Observation:
properties:
id: string
- traceId: string
+ traceId: optional<string>
type: string
name: optional<string>
startTime: datetime
diff --git a/fern/server/definition/generations.yml b/fern/server/definition/generations.yml
index dac8178beb..0da37e6d58 100644
--- a/fern/server/definition/generations.yml
+++ b/fern/server/definition/generations.yml
@@ -20,6 +20,7 @@ types:
UpdateGenerationRequest:
properties:
generationId: string
+ traceId: optional<string>
name: optional<string>
endTime: optional<datetime>
completionStartTime: optional<datetime>
diff --git a/fern/server/definition/span.yml b/fern/server/definition/span.yml
index 64ac8d2e5c..bb953e0117 100644
--- a/fern/server/definition/span.yml
+++ b/fern/server/definition/span.yml
@@ -22,6 +22,7 @@ types:
UpdateSpanRequest:
properties:
spanId: string
+ traceId: optional<string>
endTime: optional<datetime>
metadata: optional<unknown>
input: optional<unknown>
diff --git a/fern/server/generators.yml b/fern/server/generators.yml
index 5ae76e188c..87fc86ebef 100644
--- a/fern/server/generators.yml
+++ b/fern/server/generators.yml
@@ -26,23 +26,23 @@ groups:
config:
namespaceExport: Langfuse
allowCustomFetcher: true
- published:
- generators:
- - name: fernapi/fern-python-sdk
- version: 0.3.7
- output:
- location: pypi
- url: pypi.buildwithfern.com
- package-name: finto-fern-langfuse
- config:
- namespaceExport: Langfuse
- allowCustomFetcher: true
- - name: fernapi/fern-typescript-node-sdk
- version: 0.7.1
- output:
- location: npm
- url: npm.buildwithfern.com
- package-name: "@finto-fern/langfuse-node"
- config:
- namespaceExport: Langfuse
- allowCustomFetcher: true
+ # published:
+ # generators:
+ # - name: fernapi/fern-python-sdk
+ # version: 0.3.7
+ # output:
+ # location: pypi
+ # url: pypi.buildwithfern.com
+ # package-name: finto-fern-langfuse
+ # config:
+ # namespaceExport: Langfuse
+ # allowCustomFetcher: true
+ # - name: fernapi/fern-typescript-node-sdk
+ # version: 0.7.1
+ # output:
+ # location: npm
+ # url: npm.buildwithfern.com
+ # package-name: "@finto-fern/langfuse-node"
+ # config:
+ # namespaceExport: Langfuse
+ # allowCustomFetcher: true
diff --git a/generated/openapi-server/openapi.yml b/generated/openapi-server/openapi.yml
index 9a33b6b223..843ce1f6a7 100644
--- a/generated/openapi-server/openapi.yml
+++ b/generated/openapi-server/openapi.yml
@@ -747,6 +747,7 @@ components:
type: string
traceId:
type: string
+ nullable: true
type:
type: string
name:
@@ -797,7 +798,6 @@ components:
nullable: true
required:
- id
- - traceId
- type
- startTime
- promptTokens
@@ -873,6 +873,9 @@ components:
properties:
generationId:
type: string
+ traceId:
+ type: string
+ nullable: true
name:
type: string
nullable: true
@@ -958,6 +961,9 @@ components:
properties:
spanId:
type: string
+ traceId:
+ type: string
+ nullable: true
endTime:
type: string
format: date-time
diff --git a/package-lock.json b/package-lock.json
index dcafd066b2..82e271e6e4 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1889,126 +1889,6 @@
"node": ">= 10"
}
},
- "node_modules/@next/swc-darwin-x64": {
- "version": "13.4.12",
- "resolved": "https://registry.npmjs.org/@next/swc-darwin-x64/-/swc-darwin-x64-13.4.12.tgz",
- "integrity": "sha512-WRvH7RxgRHlC1yb5oG0ZLx8F7uci9AivM5/HGGv9ZyG2Als8Ij64GC3d+mQ5sJhWjusyU6T6V1WKTUoTmOB0zQ==",
- "cpu": [
- "x64"
- ],
- "optional": true,
- "os": [
- "darwin"
- ],
- "engines": {
- "node": ">= 10"
- }
- },
- "node_modules/@next/swc-linux-arm64-gnu": {
- "version": "13.4.12",
- "resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-gnu/-/swc-linux-arm64-gnu-13.4.12.tgz",
- "integrity": "sha512-YEKracAWuxp54tKiAvvq73PUs9lok57cc8meYRibTWe/VdPB2vLgkTVWFcw31YDuRXdEhdX0fWS6Q+ESBhnEig==",
- "cpu": [
- "arm64"
- ],
- "optional": true,
- "os": [
- "linux"
- ],
- "engines": {
- "node": ">= 10"
- }
- },
- "node_modules/@next/swc-linux-arm64-musl": {
- "version": "13.4.12",
- "resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-musl/-/swc-linux-arm64-musl-13.4.12.tgz",
- "integrity": "sha512-LhJR7/RAjdHJ2Isl2pgc/JaoxNk0KtBgkVpiDJPVExVWA1c6gzY57+3zWuxuyWzTG+fhLZo2Y80pLXgIJv7g3g==",
- "cpu": [
- "arm64"
- ],
- "optional": true,
- "os": [
- "linux"
- ],
- "engines": {
- "node": ">= 10"
- }
- },
- "node_modules/@next/swc-linux-x64-gnu": {
- "version": "13.4.12",
- "resolved": "https://registry.npmjs.org/@next/swc-linux-x64-gnu/-/swc-linux-x64-gnu-13.4.12.tgz",
- "integrity": "sha512-1DWLL/B9nBNiQRng+1aqs3OaZcxC16Nf+mOnpcrZZSdyKHek3WQh6j/fkbukObgNGwmCoVevLUa/p3UFTTqgqg==",
- "cpu": [
- "x64"
- ],
- "optional": true,
- "os": [
- "linux"
- ],
- "engines": {
- "node": ">= 10"
- }
- },
- "node_modules/@next/swc-linux-x64-musl": {
- "version": "13.4.12",
- "resolved": "https://registry.npmjs.org/@next/swc-linux-x64-musl/-/swc-linux-x64-musl-13.4.12.tgz",
- "integrity": "sha512-kEAJmgYFhp0VL+eRWmUkVxLVunn7oL9Mdue/FS8yzRBVj7Z0AnIrHpTIeIUl1bbdQq1VaoOztnKicAjfkLTRCQ==",
- "cpu": [
- "x64"
- ],
- "optional": true,
- "os": [
- "linux"
- ],
- "engines": {
- "node": ">= 10"
- }
- },
- "node_modules/@next/swc-win32-arm64-msvc": {
- "version": "13.4.12",
- "resolved": "https://registry.npmjs.org/@next/swc-win32-arm64-msvc/-/swc-win32-arm64-msvc-13.4.12.tgz",
- "integrity": "sha512-GMLuL/loR6yIIRTnPRY6UGbLL9MBdw2anxkOnANxvLvsml4F0HNIgvnU3Ej4BjbqMTNjD4hcPFdlEow4XHPdZA==",
- "cpu": [
- "arm64"
- ],
- "optional": true,
- "os": [
- "win32"
- ],
- "engines": {
- "node": ">= 10"
- }
- },
- "node_modules/@next/swc-win32-ia32-msvc": {
- "version": "13.4.12",
- "resolved": "https://registry.npmjs.org/@next/swc-win32-ia32-msvc/-/swc-win32-ia32-msvc-13.4.12.tgz",
- "integrity": "sha512-PhgNqN2Vnkm7XaMdRmmX0ZSwZXQAtamBVSa9A/V1dfKQCV1rjIZeiy/dbBnVYGdj63ANfsOR/30XpxP71W0eww==",
- "cpu": [
- "ia32"
- ],
- "optional": true,
- "os": [
- "win32"
- ],
- "engines": {
- "node": ">= 10"
- }
- },
- "node_modules/@next/swc-win32-x64-msvc": {
- "version": "13.4.12",
- "resolved": "https://registry.npmjs.org/@next/swc-win32-x64-msvc/-/swc-win32-x64-msvc-13.4.12.tgz",
- "integrity": "sha512-Z+56e/Ljt0bUs+T+jPjhFyxYBcdY2RIq9ELFU+qAMQMteHo7ymbV7CKmlcX59RI9C4YzN8PgMgLyAoi916b5HA==",
- "cpu": [
- "x64"
- ],
- "optional": true,
- "os": [
- "win32"
- ],
- "engines": {
- "node": ">= 10"
- }
- },
"node_modules/@nodelib/fs.scandir": {
"version": "2.1.5",
"resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz",
@@ -13574,6 +13454,126 @@
"funding": {
"url": "https://github.com/sponsors/colinhacks"
}
+ },
+ "node_modules/@next/swc-darwin-x64": {
+ "version": "13.4.12",
+ "resolved": "https://registry.npmjs.org/@next/swc-darwin-x64/-/swc-darwin-x64-13.4.12.tgz",
+ "integrity": "sha512-WRvH7RxgRHlC1yb5oG0ZLx8F7uci9AivM5/HGGv9ZyG2Als8Ij64GC3d+mQ5sJhWjusyU6T6V1WKTUoTmOB0zQ==",
+ "cpu": [
+ "x64"
+ ],
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">= 10"
+ }
+ },
+ "node_modules/@next/swc-linux-arm64-gnu": {
+ "version": "13.4.12",
+ "resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-gnu/-/swc-linux-arm64-gnu-13.4.12.tgz",
+ "integrity": "sha512-YEKracAWuxp54tKiAvvq73PUs9lok57cc8meYRibTWe/VdPB2vLgkTVWFcw31YDuRXdEhdX0fWS6Q+ESBhnEig==",
+ "cpu": [
+ "arm64"
+ ],
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 10"
+ }
+ },
+ "node_modules/@next/swc-linux-arm64-musl": {
+ "version": "13.4.12",
+ "resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-musl/-/swc-linux-arm64-musl-13.4.12.tgz",
+ "integrity": "sha512-LhJR7/RAjdHJ2Isl2pgc/JaoxNk0KtBgkVpiDJPVExVWA1c6gzY57+3zWuxuyWzTG+fhLZo2Y80pLXgIJv7g3g==",
+ "cpu": [
+ "arm64"
+ ],
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 10"
+ }
+ },
+ "node_modules/@next/swc-linux-x64-gnu": {
+ "version": "13.4.12",
+ "resolved": "https://registry.npmjs.org/@next/swc-linux-x64-gnu/-/swc-linux-x64-gnu-13.4.12.tgz",
+ "integrity": "sha512-1DWLL/B9nBNiQRng+1aqs3OaZcxC16Nf+mOnpcrZZSdyKHek3WQh6j/fkbukObgNGwmCoVevLUa/p3UFTTqgqg==",
+ "cpu": [
+ "x64"
+ ],
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 10"
+ }
+ },
+ "node_modules/@next/swc-linux-x64-musl": {
+ "version": "13.4.12",
+ "resolved": "https://registry.npmjs.org/@next/swc-linux-x64-musl/-/swc-linux-x64-musl-13.4.12.tgz",
+ "integrity": "sha512-kEAJmgYFhp0VL+eRWmUkVxLVunn7oL9Mdue/FS8yzRBVj7Z0AnIrHpTIeIUl1bbdQq1VaoOztnKicAjfkLTRCQ==",
+ "cpu": [
+ "x64"
+ ],
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 10"
+ }
+ },
+ "node_modules/@next/swc-win32-arm64-msvc": {
+ "version": "13.4.12",
+ "resolved": "https://registry.npmjs.org/@next/swc-win32-arm64-msvc/-/swc-win32-arm64-msvc-13.4.12.tgz",
+ "integrity": "sha512-GMLuL/loR6yIIRTnPRY6UGbLL9MBdw2anxkOnANxvLvsml4F0HNIgvnU3Ej4BjbqMTNjD4hcPFdlEow4XHPdZA==",
+ "cpu": [
+ "arm64"
+ ],
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">= 10"
+ }
+ },
+ "node_modules/@next/swc-win32-ia32-msvc": {
+ "version": "13.4.12",
+ "resolved": "https://registry.npmjs.org/@next/swc-win32-ia32-msvc/-/swc-win32-ia32-msvc-13.4.12.tgz",
+ "integrity": "sha512-PhgNqN2Vnkm7XaMdRmmX0ZSwZXQAtamBVSa9A/V1dfKQCV1rjIZeiy/dbBnVYGdj63ANfsOR/30XpxP71W0eww==",
+ "cpu": [
+ "ia32"
+ ],
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">= 10"
+ }
+ },
+ "node_modules/@next/swc-win32-x64-msvc": {
+ "version": "13.4.12",
+ "resolved": "https://registry.npmjs.org/@next/swc-win32-x64-msvc/-/swc-win32-x64-msvc-13.4.12.tgz",
+ "integrity": "sha512-Z+56e/Ljt0bUs+T+jPjhFyxYBcdY2RIq9ELFU+qAMQMteHo7ymbV7CKmlcX59RI9C4YzN8PgMgLyAoi916b5HA==",
+ "cpu": [
+ "x64"
+ ],
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">= 10"
+ }
}
}
}
diff --git a/prisma/migrations/20230809093636_remove_foreign_keys/migration.sql b/prisma/migrations/20230809093636_remove_foreign_keys/migration.sql
new file mode 100644
index 0000000000..0a06e2c4df
--- /dev/null
+++ b/prisma/migrations/20230809093636_remove_foreign_keys/migration.sql
@@ -0,0 +1,5 @@
+-- DropForeignKey
+ALTER TABLE "observations" DROP CONSTRAINT "observations_parent_observation_id_fkey";
+
+-- DropForeignKey
+ALTER TABLE "observations" DROP CONSTRAINT "observations_trace_id_fkey";
diff --git a/prisma/migrations/20230809132331_add_project_id_to_observations/migration.sql b/prisma/migrations/20230809132331_add_project_id_to_observations/migration.sql
new file mode 100644
index 0000000000..be0538a9d7
--- /dev/null
+++ b/prisma/migrations/20230809132331_add_project_id_to_observations/migration.sql
@@ -0,0 +1,22 @@
+/*
+ Warnings:
+
+ - Added the required column `project_id` to the `observations` table without a default value. This is not possible if the table is not empty.
+
+*/
+-- AlterTable
+ALTER TABLE "observations" ADD COLUMN "project_id" TEXT;
+
+-- Backfill data in the new column
+UPDATE "observations" o
+SET "project_id" = t."project_id"
+FROM "traces" t
+WHERE o."trace_id" = t."id";
+
+-- To be applied in separate migration after application release to minimize ingestion downtime
+-- ALTER TABLE "observations"
+-- ALTER COLUMN "project_id" SET NOT NULL;
+
+
+-- AddForeignKey
+ALTER TABLE "observations" ADD CONSTRAINT "observations_project_id_fkey" FOREIGN KEY ("project_id") REFERENCES "projects"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
diff --git a/prisma/migrations/20230810191452_traceid_nullable_on_observations/migration.sql b/prisma/migrations/20230810191452_traceid_nullable_on_observations/migration.sql
new file mode 100644
index 0000000000..110a367db1
--- /dev/null
+++ b/prisma/migrations/20230810191452_traceid_nullable_on_observations/migration.sql
@@ -0,0 +1,2 @@
+-- AlterTable
+ALTER TABLE "observations" ALTER COLUMN "trace_id" DROP NOT NULL;
diff --git a/prisma/schema.prisma b/prisma/schema.prisma
index 7c792377ab..13e4cf0d22 100644
--- a/prisma/schema.prisma
+++ b/prisma/schema.prisma
@@ -73,12 +73,13 @@ model VerificationToken {
}
model Project {
- id String @id @default(cuid())
- createdAt DateTime @default(now()) @map("created_at")
- name String
- members Membership[]
- traces Trace[]
- apiKeys ApiKey[]
+ id String @id @default(cuid())
+ createdAt DateTime @default(now()) @map("created_at")
+ name String
+ members Membership[]
+ traces Trace[]
+ observations Observation[]
+ apiKeys ApiKey[]
@@map("projects")
}
@@ -130,8 +131,7 @@ model Trace {
projectId String @map("project_id")
project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
- observations Observation[]
- scores Score[]
+ scores Score[]
@@unique([projectId, externalId])
@@index([projectId])
@@ -143,8 +143,8 @@ model Trace {
model Observation {
id String @id @default(cuid())
- traceId String @map("trace_id")
- trace Trace @relation(fields: [traceId], references: [id], onDelete: Cascade)
+ traceId String? @map("trace_id")
+ projectId String @map("project_id")
type ObservationType
startTime DateTime @default(now()) @map("start_time")
endTime DateTime? @map("end_time")
@@ -165,9 +165,8 @@ model Observation {
totalTokens Int @default(0) @map("total_tokens")
completionStartTime DateTime? @map("completion_start_time")
- parent Observation? @relation("ParentChilds", fields: [parentObservationId], references: [id])
- childs Observation[] @relation("ParentChilds")
- scores Score[]
+ scores Score[]
+ Project Project @relation(fields: [projectId], references: [id])
@@index([traceId])
@@index([type])
diff --git a/prisma/seed.ts b/prisma/seed.ts
index be7951bc51..6f0a6e66ff 100755
--- a/prisma/seed.ts
+++ b/prisma/seed.ts
@@ -19,7 +19,7 @@ async function main() {
},
});
- const project = await prisma.project.create({
+ const project1 = await prisma.project.create({
data: {
id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
name: "llm-app",
@@ -42,6 +42,29 @@ async function main() {
},
});
+ const project2 = await prisma.project.create({
+ data: {
+ id: "239ad00f-562f-411d-af14-831c75ddd875",
+ name: "demo-app",
+ apiKeys: {
+ create: [
+ {
+ note: "seeded key",
+ hashedSecretKey: await hashSecretKey("sk-lf-asdfghjkl"),
+ displaySecretKey: getDisplaySecretKey("sk-lf-asdfghjkl"),
+ publishableKey: "pk-lf-asdfghjkl",
+ },
+ ],
+ },
+ members: {
+ create: {
+ role: "OWNER",
+ userId: user.id,
+ },
+ },
+ },
+ });
+
for (let i = 0; i < TRACE_VOLUME; i++) {
// print progress to console with a progress bar that refreshes every 10 iterations
if (i % 10 === 0) {
@@ -66,7 +89,7 @@ async function main() {
},
project: {
connect: {
- id: project.id,
+ id: [project1.id, project2.id][i % 2],
},
},
userId: `user-${i % 10}`,
@@ -120,22 +143,16 @@ async function main() {
metadata: {
user: `user-${i}@langfuse.com`,
},
- trace: {
- connect: {
- id: trace.id,
- },
- },
+ Project: { connect: { id: trace.projectId } },
+ traceId: trace.id,
// if this is the first span or in 50% of cases, add no parent; otherwise randomly select parent from existing spans
...(existingSpanIds.length === 0 || Math.random() > 0.5
? {}
: {
- parent: {
- connect: {
- id: existingSpanIds[
- Math.floor(Math.random() * existingSpanIds.length)
- ],
- },
- },
+ parentObservationId:
+ existingSpanIds[
+ Math.floor(Math.random() * existingSpanIds.length)
+ ],
}),
},
});
@@ -168,6 +185,7 @@ async function main() {
startTime: generationTsStart,
endTime: generationTsEnd,
name: `generation-${i}-${j}-${k}`,
+ Project: { connect: { id: trace.projectId } },
input:
Math.random() > 0.5
? [
@@ -242,16 +260,8 @@ async function main() {
promptTokens,
completionTokens,
totalTokens: promptTokens + completionTokens,
- parent: {
- connect: {
- id: span.id,
- },
- },
- trace: {
- connect: {
- id: trace.id,
- },
- },
+ parentObservationId: span.id,
+ traceId: trace.id,
},
});
@@ -273,16 +283,9 @@ async function main() {
metadata: {
user: `user-${i}@langfuse.com`,
},
- parent: {
- connect: {
- id: span.id,
- },
- },
- trace: {
- connect: {
- id: trace.id,
- },
- },
+ parentObservationId: span.id,
+ traceId: trace.id,
+ Project: { connect: { id: trace.projectId } },
},
});
}
diff --git a/src/__tests__/events.servertest.ts b/src/__tests__/events.servertest.ts
new file mode 100644
index 0000000000..9093c3c20f
--- /dev/null
+++ b/src/__tests__/events.servertest.ts
@@ -0,0 +1,300 @@
+/** @jest-environment node */
+
+import { prisma } from "@/src/server/db";
+import { makeAPICall } from "@/src/__tests__/test-utils";
+import { v4 as uuidv4 } from "uuid";
+
+describe("/api/public/events API Endpoint", () => {
+ const pruneDatabase = async () => {
+ await prisma.observation.deleteMany();
+ await prisma.score.deleteMany();
+ await prisma.trace.deleteMany();
+ };
+
+ beforeEach(async () => await pruneDatabase());
+ afterEach(async () => await pruneDatabase());
+
+ it("should create event after trace", async () => {
+ await pruneDatabase();
+
+ const traceId = uuidv4();
+
+ await makeAPICall("POST", "/api/public/traces", {
+ id: traceId,
+ name: "trace-name",
+ userId: "user-1",
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ metadata: { key: "value" },
+ release: "1.0.0",
+ version: "2.0.0",
+ });
+
+ const dbTrace = await prisma.trace.findMany({
+ where: {
+ id: traceId,
+ },
+ });
+
+ expect(dbTrace.length).toBeGreaterThan(0);
+ expect(dbTrace[0]?.id).toBe(traceId);
+
+ const eventId = uuidv4();
+ const createEvent = await makeAPICall("POST", "/api/public/events", {
+ id: eventId,
+ traceId: traceId,
+ name: "event-name",
+ startTime: "2021-01-01T00:00:00.000Z",
+ input: { input: "value" },
+ output: { output: "value" },
+ metadata: { meta: "value" },
+ version: "2.0.0",
+ });
+
+ expect(createEvent.status).toBe(200);
+ const dbEvent = await prisma.observation.findUnique({
+ where: {
+ id: eventId,
+ },
+ });
+
+ expect(dbEvent?.id).toBe(eventId);
+ expect(dbEvent?.traceId).toBe(traceId);
+ expect(dbEvent?.name).toBe("event-name");
+ expect(dbEvent?.startTime).toEqual(new Date("2021-01-01T00:00:00.000Z"));
+ expect(dbEvent?.input).toEqual({ input: "value" });
+ expect(dbEvent?.output).toEqual({ output: "value" });
+ expect(dbEvent?.metadata).toEqual({ meta: "value" });
+ expect(dbEvent?.version).toBe("2.0.0");
+ });
+
+ it("should create event before trace", async () => {
+ await pruneDatabase();
+
+ const traceId = uuidv4();
+ const eventId = uuidv4();
+
+ const createEvent = await makeAPICall("POST", "/api/public/events", {
+ id: eventId,
+ traceId: traceId,
+ name: "event-name",
+ startTime: "2021-01-01T00:00:00.000Z",
+ input: { input: "value" },
+ output: { output: "value" },
+ metadata: { meta: "value" },
+ version: "2.0.0",
+ });
+
+ expect(createEvent.status).toBe(200);
+ const dbEvent = await prisma.observation.findUnique({
+ where: {
+ id: eventId,
+ },
+ });
+
+ expect(dbEvent?.id).toBe(eventId);
+ expect(dbEvent?.traceId).toBe(traceId);
+ expect(dbEvent?.name).toBe("event-name");
+ expect(dbEvent?.startTime).toEqual(new Date("2021-01-01T00:00:00.000Z"));
+ expect(dbEvent?.input).toEqual({ input: "value" });
+ expect(dbEvent?.output).toEqual({ output: "value" });
+ expect(dbEvent?.metadata).toEqual({ meta: "value" });
+ expect(dbEvent?.version).toBe("2.0.0");
+
+ await makeAPICall("POST", "/api/public/traces", {
+ id: traceId,
+ name: "trace-name",
+ userId: "user-1",
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ metadata: { key: "value" },
+ release: "1.0.0",
+ version: "2.0.0",
+ });
+
+ const dbTrace = await prisma.trace.findMany({
+ where: {
+ id: traceId,
+ },
+ });
+
+ expect(dbTrace.length).toBeGreaterThan(0);
+ expect(dbTrace[0]?.id).toBe(traceId);
+ });
+
+ it("should create event after trace based on externalId", async () => {
+ await pruneDatabase();
+
+ const traceId = uuidv4();
+
+ await makeAPICall("POST", "/api/public/traces", {
+ externalId: traceId,
+ name: "trace-name",
+ userId: "user-1",
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ metadata: { key: "value" },
+ release: "1.0.0",
+ version: "2.0.0",
+ });
+
+ const dbTrace = await prisma.trace.findMany({
+ where: {
+ externalId: traceId,
+ },
+ });
+
+ expect(dbTrace.length).toBeGreaterThan(0);
+ expect(dbTrace[0]?.externalId).toBe(traceId);
+ expect(dbTrace[0]?.id).not.toBe(traceId);
+
+ const spanId = uuidv4();
+ const createEvent = await makeAPICall("POST", "/api/public/spans", {
+ id: spanId,
+ traceIdType: "EXTERNAL",
+ traceId: traceId,
+ name: "event-name",
+ startTime: "2021-01-01T00:00:00.000Z",
+ input: { input: "value" },
+ output: { output: "value" },
+ metadata: { meta: "value" },
+ version: "2.0.0",
+ });
+
+ expect(createEvent.status).toBe(200);
+ const dbEvent = await prisma.observation.findUnique({
+ where: {
+ id: spanId,
+ },
+ });
+
+ expect(dbEvent?.id).toBe(spanId);
+ expect(dbEvent?.traceId).toBe(dbTrace[0]?.id);
+ expect(dbEvent?.name).toBe("event-name");
+ expect(dbEvent?.startTime).toEqual(new Date("2021-01-01T00:00:00.000Z"));
+ expect(dbEvent?.input).toEqual({ input: "value" });
+ expect(dbEvent?.output).toEqual({ output: "value" });
+ expect(dbEvent?.metadata).toEqual({ meta: "value" });
+ expect(dbEvent?.version).toBe("2.0.0");
+ });
+
+ it("should create trace when creating span without existing trace", async () => {
+ const eventName = uuidv4();
+
+ const spanId = uuidv4();
+ const createEvent = await makeAPICall("POST", "/api/public/events", {
+ id: spanId,
+ name: eventName,
+ startTime: "2021-01-01T00:00:00.000Z",
+ endTime: "2021-01-01T00:00:00.000Z",
+ input: { input: "value" },
+ output: { output: "value" },
+ metadata: { meta: "value" },
+ version: "2.0.0",
+ });
+
+ const dbTrace = await prisma.trace.findMany({
+ where: {
+ name: eventName,
+ },
+ });
+
+ expect(dbTrace.length).toBe(1);
+ expect(dbTrace[0]?.name).toBe(eventName);
+
+ expect(createEvent.status).toBe(200);
+ const dbEvent = await prisma.observation.findUnique({
+ where: {
+ id: spanId,
+ },
+ });
+
+ expect(dbEvent?.id).toBe(spanId);
+ expect(dbEvent?.traceId).toBe(dbTrace[0]?.id);
+ expect(dbEvent?.name).toBe(eventName);
+ expect(dbEvent?.startTime).toEqual(new Date("2021-01-01T00:00:00.000Z"));
+ expect(dbEvent?.input).toEqual({ input: "value" });
+ expect(dbEvent?.output).toEqual({ output: "value" });
+ expect(dbEvent?.metadata).toEqual({ meta: "value" });
+ expect(dbEvent?.version).toBe("2.0.0");
+ });
+
+ it("should create trace when creating span without existing trace with externalId", async () => {
+ const eventName = uuidv4();
+
+ const spanId = uuidv4();
+ const externalTraceId = uuidv4();
+ const createEvent = await makeAPICall("POST", "/api/public/events", {
+ id: spanId,
+ traceIdType: "EXTERNAL",
+ traceId: externalTraceId,
+ name: eventName,
+ startTime: "2021-01-01T00:00:00.000Z",
+ input: { input: "value" },
+ output: { output: "value" },
+ metadata: { meta: "value" },
+ version: "2.0.0",
+ });
+
+ const dbTrace = await prisma.trace.findMany({
+ where: {
+ externalId: externalTraceId,
+ },
+ });
+
+ expect(dbTrace.length).toBe(1);
+ expect(dbTrace[0]?.name).toBeNull();
+
+ expect(createEvent.status).toBe(200);
+ const dbEvent = await prisma.observation.findUnique({
+ where: {
+ id: spanId,
+ },
+ });
+
+ expect(dbEvent?.id).toBe(spanId);
+ expect(dbEvent?.traceId).toBe(dbTrace[0]?.id);
+ expect(dbEvent?.name).toBe(eventName);
+ expect(dbEvent?.startTime).toEqual(new Date("2021-01-01T00:00:00.000Z"));
+ expect(dbEvent?.input).toEqual({ input: "value" });
+ expect(dbEvent?.output).toEqual({ output: "value" });
+ expect(dbEvent?.metadata).toEqual({ meta: "value" });
+ expect(dbEvent?.version).toBe("2.0.0");
+ });
+
+ it("should create event when creating generation without existing trace without traceId", async () => {
+ const generationName = uuidv4();
+
+ const spanId = uuidv4();
+ const createSpan = await makeAPICall("POST", "/api/public/events", {
+ id: spanId,
+ name: generationName,
+ startTime: "2021-01-01T00:00:00.000Z",
+ input: { key: "value" },
+ metadata: { key: "value" },
+ version: "2.0.0",
+ });
+
+ const dbEvent = await prisma.observation.findFirstOrThrow({
+ where: {
+ name: generationName,
+ },
+ });
+
+ const dbTrace = await prisma.trace.findMany({
+ where: {
+ id: dbEvent.traceId,
+ },
+ });
+
+ expect(dbTrace.length).toBe(1);
+ expect(dbTrace[0]?.name).toBe(generationName);
+
+ expect(createSpan.status).toBe(200);
+
+ expect(dbEvent?.id).toBe(spanId);
+ expect(dbEvent?.traceId).toBe(dbTrace[0]?.id);
+ expect(dbEvent?.name).toBe(generationName);
+ expect(dbEvent?.startTime).toEqual(new Date("2021-01-01T00:00:00.000Z"));
+ expect(dbEvent?.input).toEqual({ key: "value" });
+ expect(dbEvent?.metadata).toEqual({ key: "value" });
+ expect(dbEvent?.version).toBe("2.0.0");
+ });
+});
diff --git a/src/__tests__/generations.servertest.ts b/src/__tests__/generations.servertest.ts
index 3614ced76a..a951644b47 100644
--- a/src/__tests__/generations.servertest.ts
+++ b/src/__tests__/generations.servertest.ts
@@ -77,6 +77,69 @@ describe("/api/public/generations API Endpoint", () => {
expect(dbGeneration?.version).toBe("2.0.0");
});
+ it("should create generation before trace", async () => {
+ await pruneDatabase();
+
+ const traceId = uuidv4();
+
+ const generationId = uuidv4();
+ const createGeneration = await makeAPICall(
+ "POST",
+ "/api/public/generations",
+ {
+ id: generationId,
+ traceId: traceId,
+ name: "generation-name",
+ startTime: "2021-01-01T00:00:00.000Z",
+ endTime: "2021-01-01T00:00:00.000Z",
+ model: "model-name",
+ modelParameters: { key: "value" },
+ prompt: { key: "value" },
+ metadata: { key: "value" },
+ version: "2.0.0",
+ }
+ );
+
+ expect(createGeneration.status).toBe(200);
+ const dbGeneration = await prisma.observation.findUnique({
+ where: {
+ id: generationId,
+ },
+ });
+
+ expect(dbGeneration?.id).toBe(generationId);
+ expect(dbGeneration?.traceId).toBe(traceId);
+ expect(dbGeneration?.name).toBe("generation-name");
+ expect(dbGeneration?.startTime).toEqual(
+ new Date("2021-01-01T00:00:00.000Z")
+ );
+ expect(dbGeneration?.endTime).toEqual(new Date("2021-01-01T00:00:00.000Z"));
+ expect(dbGeneration?.model).toBe("model-name");
+ expect(dbGeneration?.modelParameters).toEqual({ key: "value" });
+ expect(dbGeneration?.input).toEqual({ key: "value" });
+ expect(dbGeneration?.metadata).toEqual({ key: "value" });
+ expect(dbGeneration?.version).toBe("2.0.0");
+
+ await makeAPICall("POST", "/api/public/traces", {
+ id: traceId,
+ name: "trace-name",
+ userId: "user-1",
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ metadata: { key: "value" },
+ release: "1.0.0",
+ version: "2.0.0",
+ });
+
+ const dbTrace = await prisma.trace.findMany({
+ where: {
+ id: traceId,
+ },
+ });
+
+ expect(dbTrace.length).toBeGreaterThan(0);
+ expect(dbTrace[0]?.id).toBe(traceId);
+ });
+
it("should create generation after trace based on externalId", async () => {
await pruneDatabase();
@@ -192,6 +255,66 @@ describe("/api/public/generations API Endpoint", () => {
expect(dbGeneration?.version).toBe("2.0.0");
});
+ it("should create nested generations", async () => {
+ const generationName = uuidv4();
+
+ const generationId = uuidv4();
+ const createGeneration = await makeAPICall(
+ "POST",
+ "/api/public/generations",
+ {
+ id: generationId,
+ name: generationName,
+ startTime: "2021-01-01T00:00:00.000Z",
+ endTime: "2021-01-01T00:00:00.000Z",
+ model: "model-name",
+ modelParameters: { key: "value" },
+ prompt: { key: "value" },
+ metadata: { key: "value" },
+ version: "2.0.0",
+ }
+ );
+
+ expect(createGeneration.status).toBe(200);
+ const dbGeneration = await prisma.observation.findUnique({
+ where: {
+ id: generationId,
+ },
+ });
+
+ expect(dbGeneration?.id).toBe(generationId);
+
+ const generationId2 = uuidv4();
+ const generationName2 = uuidv4();
+
+ const createGeneration2 = await makeAPICall(
+ "POST",
+ "/api/public/generations",
+ {
+ id: generationId2,
+ name: generationName2,
+ startTime: "2021-01-01T00:00:00.000Z",
+ endTime: "2021-01-01T00:00:00.000Z",
+ model: "model-name",
+ modelParameters: { key: "value" },
+ prompt: { key: "value" },
+ metadata: { key: "value" },
+ version: "2.0.0",
+ parentObservationId: generationId,
+ }
+ );
+ expect(createGeneration2.status).toBe(200);
+
+ const dbGeneration2 = await prisma.observation.findUnique({
+ where: {
+ id: generationId2,
+ },
+ });
+
+ expect(dbGeneration2?.id).toBe(generationId2);
+ expect(dbGeneration2?.parentObservationId).toBe(generationId);
+ });
+
it("should create trace when creating generation without existing trace with externalId", async () => {
const generationName = uuidv4();
diff --git a/src/__tests__/spans.servertest.ts b/src/__tests__/spans.servertest.ts
index c2806f5021..537042bd07 100644
--- a/src/__tests__/spans.servertest.ts
+++ b/src/__tests__/spans.servertest.ts
@@ -67,6 +67,59 @@ describe("/api/public/spans API Endpoint", () => {
expect(dbSpan?.version).toBe("2.0.0");
});
+ it("should create span before trace", async () => {
+ await pruneDatabase();
+
+ const traceId = uuidv4();
+ const spanId = uuidv4();
+
+ const createSpan = await makeAPICall("POST", "/api/public/spans", {
+ id: spanId,
+ traceId: traceId,
+ name: "span-name",
+ startTime: "2021-01-01T00:00:00.000Z",
+ endTime: "2021-01-01T00:00:00.000Z",
+ input: { input: "value" },
+ metadata: { meta: "value" },
+ version: "2.0.0",
+ });
+
+ expect(createSpan.status).toBe(200);
+ const dbSpan = await prisma.observation.findUnique({
+ where: {
+ id: spanId,
+ },
+ });
+
+ expect(dbSpan?.id).toBe(spanId);
+ expect(dbSpan?.traceId).toBe(traceId);
+ expect(dbSpan?.name).toBe("span-name");
+ expect(dbSpan?.startTime).toEqual(new Date("2021-01-01T00:00:00.000Z"));
+ expect(dbSpan?.endTime).toEqual(new Date("2021-01-01T00:00:00.000Z"));
+ expect(dbSpan?.input).toEqual({ input: "value" });
+ expect(dbSpan?.metadata).toEqual({ meta: "value" });
+ expect(dbSpan?.version).toBe("2.0.0");
+
+ await makeAPICall("POST", "/api/public/traces", {
+ id: traceId,
+ name: "trace-name",
+ userId: "user-1",
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ metadata: { key: "value" },
+ release: "1.0.0",
+ version: "2.0.0",
+ });
+
+ const dbTrace = await prisma.trace.findMany({
+ where: {
+ id: traceId,
+ },
+ });
+
+ expect(dbTrace.length).toBeGreaterThan(0);
+ expect(dbTrace[0]?.id).toBe(traceId);
+ });
+
it("should create span after trace based on externalId", async () => {
await pruneDatabase();
@@ -205,7 +258,7 @@ describe("/api/public/spans API Endpoint", () => {
expect(dbSpan?.version).toBe("2.0.0");
});
- it("should create trace when creating generation without existing trace without traceId", async () => {
+ it("should create trace when creating span without existing trace without traceId", async () => {
const generationName = uuidv4();
const spanId = uuidv4();
@@ -214,8 +267,6 @@ describe("/api/public/spans API Endpoint", () => {
name: generationName,
startTime: "2021-01-01T00:00:00.000Z",
endTime: "2021-01-01T00:00:00.000Z",
- model: "model-name",
- modelParameters: { key: "value" },
input: { key: "value" },
metadata: { key: "value" },
version: "2.0.0",
@@ -279,7 +330,7 @@ describe("/api/public/spans API Endpoint", () => {
expect(dbSpan?.id).toBe(spanId);
expect(dbSpan?.name).toBe(spanName);
expect(dbSpan?.startTime).toEqual(new Date("2021-01-01T00:00:00.000Z"));
- expect(dbSpan?.endTime).toEqual(new Date("2021-01-01T00:00:00.000Z"));
+ expect(dbSpan?.endTime).toEqual(new Date("2021-01-:00:00.000Z"));
expect(dbSpan?.input).toEqual({ input: "value" });
expect(dbSpan?.output).toEqual({ key: "this is a great gpt output" });
expect(dbSpan?.metadata).toEqual({ meta: "value" });
diff --git a/src/components/table/use-cases/traces.tsx b/src/components/table/use-cases/traces.tsx
index 4dc606e01e..569ef19546 100644
--- a/src/components/table/use-cases/traces.tsx
+++ b/src/components/table/use-cases/traces.tsx
@@ -76,7 +76,11 @@ export default function TracesTable({ projectId, userId }: TraceTableProps) {
metadata: JSON.stringify(trace.metadata),
userId: trace.userId ?? "",
scores: trace.scores,
- usage: trace.usage,
+ usage: {
+ promptTokens: trace.promptTokens,
+ completionTokens: trace.completionTokens,
+ totalTokens: trace.totalTokens,
+ },
};
};
diff --git a/src/components/trace/ObservationPreview.tsx b/src/components/trace/ObservationPreview.tsx
index f77b7cf3ef..1d869c1f63 100644
--- a/src/components/trace/ObservationPreview.tsx
+++ b/src/components/trace/ObservationPreview.tsx
@@ -19,7 +19,7 @@ import {
import { ManualScoreButton } from "@/src/features/manualScoring/components";
export const ObservationPreview = (props: {
- observations: Observation[];
+ observations: Array<Observation & { traceId: string }>;
projectId: string;
scores: Score[];
currentObservationId: string | undefined;
diff --git a/src/components/trace/index.tsx b/src/components/trace/index.tsx
index 0a96664b8a..91ba8e6a8b 100644
--- a/src/components/trace/index.tsx
+++ b/src/components/trace/index.tsx
@@ -5,7 +5,7 @@ import { ObservationPreview } from "./ObservationPreview";
import { TracePreview } from "./TracePreview";
export function Trace(props: {
- observations: Observation[];
+ observations: Array<Observation & { traceId: string }>;
trace: Trace;
scores: Score[];
projectId: string;
diff --git a/src/features/publicApi/server/apiAuth.ts b/src/features/publicApi/server/apiAuth.ts
index 666ac96e06..03919ceff1 100644
--- a/src/features/publicApi/server/apiAuth.ts
+++ b/src/features/publicApi/server/apiAuth.ts
@@ -16,7 +16,7 @@ export async function verifyAuthHeaderAndReturnScope(
authHeader: string | undefined
): Promise<AuthHeaderVerificationResult> {
if (!authHeader) {
- console.log("No authorization header");
+ console.error("No authorization header");
return {
validKey: false,
error: "No authorization header",
@@ -57,7 +57,7 @@ export async function verifyAuthHeaderAndReturnScope(
};
}
} catch (error: unknown) {
- console.log("Error verifying auth header: ", error);
+ console.error("Error verifying auth header: ", error);
return {
validKey: false,
error: error instanceof Error ? error.message : "Authorization error",
@@ -79,7 +79,6 @@ function extractBasicAuthCredentials(basicAuthHeader: string): {
const [username, password] = atob(authValue).split(":");
if (!username || !password) throw new Error("Invalid authorization header");
-
return { username, password };
}
diff --git a/src/features/publicApi/server/apiAuthAndScope.ts b/src/features/publicApi/server/apiAuthAndScope.ts
deleted file mode 100644
index e69de29bb2..0000000000
diff --git a/src/features/publicApi/server/apiScope.ts b/src/features/publicApi/server/apiScope.ts
index fcaf7c1b7f..03ff0b6139 100644
--- a/src/features/publicApi/server/apiScope.ts
+++ b/src/features/publicApi/server/apiScope.ts
@@ -26,29 +26,34 @@ export async function checkApiAccessScope(
async function isResourceInProject(resource: Resource, projectId: string) {
switch (resource.type) {
case "project":
- const checkProject = resource.id === projectId;
- if (!checkProject)
- return console.log(
- `Project ressource denied ${resource.id}, ${projectId}`
- );
- return checkProject;
+ const projectCheck = resource.id === projectId;
+ if (!projectCheck)
+ console.log("project check", projectCheck, resource.id, projectId);
+ return projectCheck;
+
case "trace":
- const checkTrace =
+ const traceCheck =
(await prisma.trace.count({
where: { id: resource.id, projectId },
})) === 1;
- if (!checkTrace)
- console.log(`Trace ressource denied ${resource.id} ${projectId}`);
+ if (!traceCheck)
+ console.log("trace check", traceCheck, resource.id, projectId);
+ return traceCheck;
- return checkTrace;
case "observation":
const observationCheck =
(await prisma.observation.count({
- where: { id: resource.id, trace: { projectId } },
+ where: { id: resource.id, projectId },
})) === 1;
if (!observationCheck)
- console.log(`Observation ressource denied ${resource.id} ${projectId}`);
+ console.log(
+ "observation check",
+ observationCheck,
+ resource.id,
+ projectId
+ );
return observationCheck;
+
case "score":
const scoreCheck =
(await prisma.score.count({
@@ -58,7 +63,7 @@ async function isResourceInProject(resource: Resource, projectId: string) {
},
})) === 1;
if (!scoreCheck)
- console.log(`Score ressource denied ${resource.id} ${projectId}`);
+ console.log("score check", scoreCheck, resource.id, projectId);
return scoreCheck;
default:
return false;
diff --git a/src/pages/api/public/events.ts b/src/pages/api/public/events.ts
index 85d601ce49..3b86017788 100644
--- a/src/pages/api/public/events.ts
+++ b/src/pages/api/public/events.ts
@@ -4,7 +4,7 @@ import { type NextApiRequest, type NextApiResponse } from "next";
import { z } from "zod";
import { cors, runMiddleware } from "@/src/features/publicApi/server/cors";
import { verifyAuthHeaderAndReturnScope } from "@/src/features/publicApi/server/apiAuth";
-import { checkApiAccessScope } from "@/src/features/publicApi/server/apiScope";
+import { v4 as uuidv4 } from "uuid";
const ObservationSchema = z.object({
id: z.string().nullish(),
@@ -57,53 +57,57 @@ export default async function handler(
version,
} = obj;
- // If externalTraceId is provided, find or create the traceId
- const traceId =
- obj.traceIdType === "EXTERNAL" && obj.traceId
- ? (
- await prisma.trace.upsert({
- where: {
- projectId_externalId: {
- projectId: authCheck.scope.projectId,
- externalId: obj.traceId,
- },
- },
- create: {
+ const traceId = !obj.traceId
+ ? // Create trace if no traceid - backwards compatibility
+ (
+ await prisma.trace.create({
+ data: {
+ projectId: authCheck.scope.projectId,
+ name: obj.name,
+ },
+ })
+ ).id
+ : obj.traceIdType === "EXTERNAL"
+ ? // Find or create trace if externalTraceId
+ (
+ await prisma.trace.upsert({
+ where: {
+ projectId_externalId: {
projectId: authCheck.scope.projectId,
externalId: obj.traceId,
},
- update: {},
- })
- ).id
- : obj.traceId;
-
- // CHECK ACCESS SCOPE
- const accessCheck = await checkApiAccessScope(authCheck.scope, [
- ...(traceId ? [{ type: "trace" as const, id: traceId }] : []),
- ...(parentObservationId
- ? [{ type: "observation" as const, id: parentObservationId }]
- : []),
- ]);
- if (!accessCheck)
- return res.status(403).json({
- success: false,
- message: "Access denied",
- });
- // END CHECK ACCESS SCOPE
+ },
+ create: {
+ projectId: authCheck.scope.projectId,
+ externalId: obj.traceId,
+ },
+ update: {},
+ })
+ ).id
+ : obj.traceId;
- const newObservation = await prisma.observation.create({
- data: {
- id: id ?? undefined,
- ...(traceId
- ? { trace: { connect: { id: traceId } } }
- : {
- trace: {
- create: {
- name: name,
- project: { connect: { id: authCheck.scope.projectId } },
- },
- },
- }),
+ const newId = uuidv4();
+ const newObservation = await prisma.observation.upsert({
+ where: {
+ id: id ?? newId,
+ projectId: authCheck.scope.projectId,
+ },
+ create: {
+ id: id ?? newId,
+ traceId: traceId,
+ type: ObservationType.EVENT,
+ name,
+ startTime: startTime ? new Date(startTime) : undefined,
+ metadata: metadata ?? undefined,
+ input: input ?? undefined,
+ output: output ?? undefined,
+ level: level ?? undefined,
+ statusMessage: statusMessage ?? undefined,
+ parentObservationId: parentObservationId ?? undefined,
+ version: version ?? undefined,
+ Project: { connect: { id: authCheck.scope.projectId } },
+ },
+ update: {
type: ObservationType.EVENT,
name,
startTime: startTime ? new Date(startTime) : undefined,
@@ -112,9 +116,7 @@ export default async function handler(
output: output ?? undefined,
level: level ?? undefined,
statusMessage: statusMessage ?? undefined,
- parent: parentObservationId
- ? { connect: { id: parentObservationId } }
- : undefined,
+ parentObservationId: parentObservationId ?? undefined,
version: version ?? undefined,
},
});
diff --git a/src/pages/api/public/generations.ts b/src/pages/api/public/generations.ts
index b2a645942f..6f78f5c057 100644
--- a/src/pages/api/public/generations.ts
+++ b/src/pages/api/public/generations.ts
@@ -4,8 +4,8 @@ import { type NextApiRequest, type NextApiResponse } from "next";
import { z } from "zod";
import { cors, runMiddleware } from "@/src/features/publicApi/server/cors";
import { verifyAuthHeaderAndReturnScope } from "@/src/features/publicApi/server/apiAuth";
-import { checkApiAccessScope } from "@/src/features/publicApi/server/apiScope";
import { tokenCount } from "@/src/features/ingest/lib/usage";
+import { v4 as uuidv4 } from "uuid";
export const GenerationsCreateSchema = z.object({
id: z.string().nullish(),
@@ -40,6 +40,7 @@ export const GenerationsCreateSchema = z.object({
const GenerationPatchSchema = z.object({
generationId: z.string(),
+ traceId: z.string().nullish(),
name: z.string().nullish(),
endTime: z.string().datetime({ offset: true }).nullish(),
completionStartTime: z.string().datetime({ offset: true }).nullish(),
@@ -108,39 +109,34 @@ export default async function handler(
version,
} = obj;
- // If externalTraceId is provided, find or create the traceId
- const traceId =
- obj.traceIdType === "EXTERNAL" && obj.traceId
- ? (
- await prisma.trace.upsert({
- where: {
- projectId_externalId: {
- projectId: authCheck.scope.projectId,
- externalId: obj.traceId,
- },
- },
- create: {
+ const traceId = !obj.traceId
+ ? // Create trace if no traceid - backwards compatibility
+ (
+ await prisma.trace.create({
+ data: {
+ projectId: authCheck.scope.projectId,
+ name: obj.name,
+ },
+ })
+ ).id
+ : obj.traceIdType === "EXTERNAL"
+ ? // Find or create trace if externalTraceId
+ (
+ await prisma.trace.upsert({
+ where: {
+ projectId_externalId: {
projectId: authCheck.scope.projectId,
externalId: obj.traceId,
},
- update: {},
- })
- ).id
- : obj.traceId;
-
- // CHECK ACCESS SCOPE
- const accessCheck = await checkApiAccessScope(authCheck.scope, [
- ...(traceId ? [{ type: "trace" as const, id: traceId }] : []),
- ...(parentObservationId
- ? [{ type: "observation" as const, id: parentObservationId }]
- : []),
- ]);
- if (!accessCheck)
- return res.status(403).json({
- success: false,
- message: "Access denied",
- });
- // END CHECK ACCESS SCOPE
+ },
+ create: {
+ projectId: authCheck.scope.projectId,
+ externalId: obj.traceId,
+ },
+ update: {},
+ })
+ ).id
+ : obj.traceId;
const newPromptTokens =
usage?.promptTokens ??
@@ -159,19 +155,16 @@ export default async function handler(
})
: undefined);
- const newObservation = await prisma.observation.create({
- data: {
- id: id ?? undefined,
- ...(traceId
- ? { trace: { connect: { id: traceId } } }
- : {
- trace: {
- create: {
- name: name,
- project: { connect: { id: authCheck.scope.projectId } },
- },
- },
- }),
+ const newId = uuidv4();
+
+ const newObservation = await prisma.observation.upsert({
+ where: {
+ id: id ?? newId,
+ projectId: authCheck.scope.projectId,
+ },
+ create: {
+ id: id ?? newId,
+ traceId: traceId,
type: ObservationType.GENERATION,
name,
startTime: startTime ? new Date(startTime) : undefined,
@@ -191,9 +184,31 @@ export default async function handler(
(newPromptTokens ?? 0) + (newCompletionTokens ?? 0),
level: level ?? undefined,
statusMessage: statusMessage ?? undefined,
- parent: parentObservationId
- ? { connect: { id: parentObservationId } }
+ parentObservationId: parentObservationId ?? undefined,
+ version: version ?? undefined,
+ Project: { connect: { id: authCheck.scope.projectId } },
+ },
+ update: {
+ type: ObservationType.GENERATION,
+ name,
+ startTime: startTime ? new Date(startTime) : undefined,
+ endTime: endTime ? new Date(endTime) : undefined,
+ completionStartTime: completionStartTime
+ ? new Date(completionStartTime)
: undefined,
+ metadata: metadata ?? undefined,
+ model: model ?? undefined,
+ modelParameters: modelParameters ?? undefined,
+ input: prompt ?? undefined,
+ output: completion ? { completion: completion } : undefined,
+ promptTokens: newPromptTokens,
+ completionTokens: newCompletionTokens,
+ totalTokens:
+ usage?.totalTokens ??
+ (newPromptTokens ?? 0) + (newCompletionTokens ?? 0),
+ level: level ?? undefined,
+ statusMessage: statusMessage ?? undefined,
+ parentObservationId: parentObservationId ?? undefined,
version: version ?? undefined,
},
});
@@ -218,27 +233,16 @@ export default async function handler(
try {
const {
generationId,
+ traceId,
endTime,
completionStartTime,
prompt,
completion,
usage,
model,
- version,
- ...fields
+ ...otherFields
} = GenerationPatchSchema.parse(req.body);
- // CHECK ACCESS SCOPE
- const accessCheck = await checkApiAccessScope(authCheck.scope, [
- { type: "observation", id: generationId },
- ]);
- if (!accessCheck)
- return res.status(403).json({
- success: false,
- message: "Access denied",
- });
- // END CHECK ACCESS SCOPE
-
const existingObservation = await prisma.observation.findUnique({
where: { id: generationId },
select: {
@@ -272,9 +276,15 @@ export default async function handler(
(newPromptTokens ?? existingObservation?.promptTokens ?? 0) +
(newCompletionTokens ?? existingObservation?.completionTokens ?? 0);
- const newObservation = await prisma.observation.update({
- where: { id: generationId },
- data: {
+ const newObservation = await prisma.observation.upsert({
+ where: {
+ id: generationId,
+ projectId: authCheck.scope.projectId,
+ },
+ create: {
+ id: generationId,
+ traceId: traceId ?? undefined,
+ type: ObservationType.GENERATION,
endTime: endTime ? new Date(endTime) : undefined,
completionStartTime: completionStartTime
? new Date(completionStartTime)
@@ -286,11 +296,29 @@ export default async function handler(
totalTokens: newTotalTokens,
model: model ?? undefined,
...Object.fromEntries(
- Object.entries(fields).filter(
+ Object.entries(otherFields).filter(
+ ([_, v]) => v !== null && v !== undefined
+ )
+ ),
+ Project: { connect: { id: authCheck.scope.projectId } },
+ },
+ update: {
+ endTime: endTime ? new Date(endTime) : undefined,
+ completionStartTime: completionStartTime
+ ? new Date(completionStartTime)
+ : undefined,
+ input: prompt ?? undefined,
+ output: completion ? { completion: completion } : undefined,
+ promptTokens: newPromptTokens,
+ completionTokens: newCompletionTokens,
+ totalTokens: newTotalTokens,
+ traceId: traceId ?? undefined,
+ model: model ?? undefined,
+ ...Object.fromEntries(
+ Object.entries(otherFields).filter(
([_, v]) => v !== null && v !== undefined
)
),
- version: version ?? undefined,
},
});
diff --git a/src/pages/api/public/observations/[observationId].ts b/src/pages/api/public/observations/[observationId].ts
index 23819b6159..965b8772d6 100644
--- a/src/pages/api/public/observations/[observationId].ts
+++ b/src/pages/api/public/observations/[observationId].ts
@@ -48,9 +48,7 @@ export default async function handler(
const observation = await prisma.observation.findFirst({
where: {
id: observationId,
- trace: {
- projectId: authCheck.scope.projectId,
- },
+ projectId: authCheck.scope.projectId,
},
});
if (!observation) {
diff --git a/src/pages/api/public/scores.ts b/src/pages/api/public/scores.ts
index 8ea3420028..2e99bfe2b1 100644
--- a/src/pages/api/public/scores.ts
+++ b/src/pages/api/public/scores.ts
@@ -1,5 +1,5 @@
import { prisma } from "@/src/server/db";
-import { type Prisma } from "@prisma/client";
+import { Prisma, type Score } from "@prisma/client";
import { type NextApiRequest, type NextApiResponse } from "next";
import { z } from "zod";
import { cors, runMiddleware } from "@/src/features/publicApi/server/cors";
@@ -117,28 +117,31 @@ export default async function handler(
const obj = ScoresGetSchema.parse(req.query); // uses query and not body
+ const skipValue = (obj.page - 1) * obj.limit;
+ const userCondition = Prisma.sql`AND t."user_id" = ${obj.userId}`;
+ const nameCondition = Prisma.sql`AND s."name" = ${obj.name}`;
+
const [scores, totalItems] = await Promise.all([
- prisma.score.findMany({
- where: {
- name: obj.name ?? undefined, // optional filter
- trace: {
- projectId: authCheck.scope.projectId,
- userId: obj.userId ?? undefined, // optional filter
- },
- },
- include: {
- trace: {
- select: {
- userId: true,
- },
- },
- },
- skip: (obj.page - 1) * obj.limit,
- take: obj.limit,
- orderBy: {
- timestamp: "desc",
- },
- }),
+ prisma.$queryRaw<
+ Array<Score & { trace: { userId: string } }>
+ >(Prisma.sql`
+ SELECT
+ s.id,
+ s.timestamp,
+ s.name,
+ s.value,
+ s.comment,
+ s.trace_id as "traceId",
+ s.observation_id as "observationId",
+ json_build_object('userId', t.user_id) as "trace"
+ FROM "scores" AS s
+ JOIN "traces" AS t ON t.id = s.trace_id
+ WHERE t.project_id = ${authCheck.scope.projectId}
+ ${obj.userId ? userCondition : Prisma.empty}
+ ${obj.name ? nameCondition : Prisma.empty}
+ ORDER BY t."timestamp" DESC
+ LIMIT ${obj.limit} OFFSET ${skipValue}
+ `),
prisma.score.count({
where: {
name: obj.name ?? undefined, // optional filter
diff --git a/src/pages/api/public/spans.ts b/src/pages/api/public/spans.ts
index dbc884f758..2b5ab6c52d 100644
--- a/src/pages/api/public/spans.ts
+++ b/src/pages/api/public/spans.ts
@@ -4,7 +4,7 @@ import { type NextApiRequest, type NextApiResponse } from "next";
import { z } from "zod";
import { cors, runMiddleware } from "@/src/features/publicApi/server/cors";
import { verifyAuthHeaderAndReturnScope } from "@/src/features/publicApi/server/apiAuth";
-import { checkApiAccessScope } from "@/src/features/publicApi/server/apiScope";
+import { v4 as uuidv4 } from "uuid";
const SpanPostSchema = z.object({
id: z.string().nullish(),
@@ -24,6 +24,7 @@ const SpanPostSchema = z.object({
const SpanPatchSchema = z.object({
spanId: z.string(),
+ traceId: z.string().nullish(),
name: z.string().nullish(),
endTime: z.string().datetime({ offset: true }).nullish(),
metadata: z.unknown().nullish(),
@@ -51,10 +52,6 @@ export default async function handler(
});
// END CHECK AUTH
- if (req.method !== "POST" && req.method !== "PATCH") {
- return res.status(405).json({ message: "Method not allowed" });
- }
-
if (req.method === "POST") {
try {
console.log("Trying to generate span: ", req.body);
@@ -73,53 +70,60 @@ export default async function handler(
version,
} = obj;
- // If externalTraceId is provided, find or create the traceId
- const traceId =
- obj.traceIdType === "EXTERNAL" && obj.traceId
- ? (
- await prisma.trace.upsert({
- where: {
- projectId_externalId: {
- projectId: authCheck.scope.projectId,
- externalId: obj.traceId,
- },
- },
- create: {
+ const traceId = !obj.traceId
+ ? // Create trace if no traceid - backwards compatibility
+ (
+ await prisma.trace.create({
+ data: {
+ projectId: authCheck.scope.projectId,
+ name: obj.name,
+ },
+ })
+ ).id
+ : obj.traceIdType === "EXTERNAL"
+ ? // Find or create trace if externalTraceId
+ (
+ await prisma.trace.upsert({
+ where: {
+ projectId_externalId: {
projectId: authCheck.scope.projectId,
externalId: obj.traceId,
},
- update: {},
- })
- ).id
- : obj.traceId;
+ },
+ create: {
+ projectId: authCheck.scope.projectId,
+ externalId: obj.traceId,
+ },
+ update: {},
+ })
+ ).id
+ : obj.traceId;
- // CHECK ACCESS SCOPE
- const accessCheck = await checkApiAccessScope(authCheck.scope, [
- ...(traceId ? [{ type: "trace" as const, id: traceId }] : []),
- ...(parentObservationId
- ? [{ type: "observation" as const, id: parentObservationId }]
- : []),
- ]);
- if (!accessCheck)
- return res.status(403).json({
- success: false,
- message: "Access denied",
- });
- // END CHECK ACCESS SCOPE
+ const newId = uuidv4();
- const newObservation = await prisma.observation.create({
- data: {
- id: id ?? undefined,
- ...(traceId
- ? { trace: { connect: { id: traceId } } }
- : {
- trace: {
- create: {
- name: name,
- project: { connect: { id: authCheck.scope.projectId } },
- },
- },
- }),
+ const newObservation = await prisma.observation.upsert({
+ where: {
+ id: id ?? newId,
+ projectId: authCheck.scope.projectId,
+ },
+ create: {
+ id: id ?? newId,
+ traceId: traceId,
+ type: ObservationType.SPAN,
+ name,
+ startTime: startTime ? new Date(startTime) : undefined,
+ endTime: endTime ? new Date(endTime) : undefined,
+ metadata: metadata ?? undefined,
+ input: input ?? undefined,
+ output: output ?? undefined,
+ level: level ?? undefined,
+ statusMessage: statusMessage ?? undefined,
+ parentObservationId: parentObservationId ?? undefined,
+ version: version ?? undefined,
+ Project: { connect: { id: authCheck.scope.projectId } },
+ },
+ update: {
+ traceId: traceId,
type: ObservationType.SPAN,
name,
startTime: startTime ? new Date(startTime) : undefined,
@@ -129,9 +133,7 @@ export default async function handler(
output: output ?? undefined,
level: level ?? undefined,
statusMessage: statusMessage ?? undefined,
- parent: parentObservationId
- ? { connect: { id: parentObservationId } }
- : undefined,
+ parentObservationId: parentObservationId ?? undefined,
version: version ?? undefined,
},
});
@@ -150,31 +152,31 @@ export default async function handler(
} else if (req.method === "PATCH") {
try {
console.log("Trying to update span: ", req.body);
- const { spanId, endTime, version, ...fields } = SpanPatchSchema.parse(
- req.body
- );
-
- // CHECK ACCESS SCOPE
- const accessCheck = await checkApiAccessScope(authCheck.scope, [
- { type: "observation", id: spanId },
- ]);
- if (!accessCheck)
- return res.status(403).json({
- success: false,
- message: "Access denied",
- });
- // END CHECK ACCESS SCOPE
+ const { spanId, endTime, ...fields } = SpanPatchSchema.parse(req.body);
- const newObservation = await prisma.observation.update({
- where: { id: spanId },
- data: {
+ const newObservation = await prisma.observation.upsert({
+ where: {
+ id: spanId,
+ projectId: authCheck.scope.projectId,
+ },
+ create: {
+ id: spanId,
+ type: ObservationType.SPAN,
+ endTime: endTime ? new Date(endTime) : undefined,
+ ...Object.fromEntries(
+ Object.entries(fields).filter(
+ ([_, v]) => v !== null && v !== undefined
+ )
+ ),
+ Project: { connect: { id: authCheck.scope.projectId } },
+ },
+ update: {
endTime: endTime ? new Date(endTime) : undefined,
...Object.fromEntries(
Object.entries(fields).filter(
([_, v]) => v !== null && v !== undefined
)
),
- version: version ?? undefined,
},
});
@@ -189,5 +191,7 @@ export default async function handler(
error: errorMessage,
});
}
+ } else {
+ res.status(405).json({ message: "Method not allowed" });
}
}
diff --git a/src/pages/api/public/traces.ts b/src/pages/api/public/traces.ts
index 4c24fa196a..5d021c90de 100644
--- a/src/pages/api/public/traces.ts
+++ b/src/pages/api/public/traces.ts
@@ -3,6 +3,8 @@ import { z } from "zod";
import { cors, runMiddleware } from "@/src/features/publicApi/server/cors";
import { prisma } from "@/src/server/db";
import { verifyAuthHeaderAndReturnScope } from "@/src/features/publicApi/server/apiAuth";
+import { Prisma, type Trace } from "@prisma/client";
+import { v4 as uuidv4 } from "uuid";
const CreateTraceSchema = z.object({
id: z.string().nullish(),
@@ -88,10 +90,15 @@ export default async function handler(
});
res.status(200).json(newTrace);
} else {
- const newTrace = await prisma.trace.create({
- data: {
- id: id ?? undefined,
- timestamp: new Date(),
+ const internalId = id ?? uuidv4();
+
+ const newTrace = await prisma.trace.upsert({
+ where: {
+ id: internalId,
+ projectId: authCheck.scope.projectId,
+ },
+ create: {
+ id: internalId,
projectId: authCheck.scope.projectId,
name: name ?? undefined,
userId: userId ?? undefined,
@@ -99,6 +106,13 @@ export default async function handler(
release: release ?? undefined,
version: version ?? undefined,
},
+ update: {
+ name: name ?? undefined,
+ userId: userId ?? undefined,
+ metadata: metadata ?? undefined,
+ release: release ?? undefined,
+ version: version ?? undefined,
+ },
});
res.status(200).json(newTrace);
}
@@ -113,26 +127,32 @@ export default async function handler(
const obj = GetTracesSchema.parse(req.query); // uses query and not body
+ const skipValue = (obj.page - 1) * obj.limit;
+ const userCondition = Prisma.sql`AND t."user_id" = ${obj.userId}`;
+ const nameCondition = Prisma.sql`AND t."name" = ${obj.name}`;
+
const [traces, totalItems] = await Promise.all([
- prisma.trace.findMany({
- where: {
- projectId: authCheck.scope.projectId,
- name: obj.name ?? undefined,
- userId: obj.userId ?? undefined,
- },
- include: {
- observations: {
- select: {
- id: true,
- },
- },
- },
- skip: (obj.page - 1) * obj.limit,
- take: obj.limit,
- orderBy: {
- timestamp: "desc",
- },
- }),
+ prisma.$queryRaw<Array<Trace & { observations: string[] }>>(Prisma.sql`
+ SELECT
+ t.id,
+ t.timestamp,
+ t.name,
+ t.project_id as "projectId",
+ t.metadata,
+ t.external_id as "externalId",
+ t.user_id as "userId",
+ t.release,
+ t.version,
+ ARRAY_AGG(o.id) AS "observations"
+ FROM "traces" AS t
+ LEFT JOIN "observations" AS o ON t.id = o.trace_id
+ WHERE t.project_id = ${authCheck.scope.projectId}
+ ${obj.userId ? userCondition : Prisma.empty}
+ ${obj.name ? nameCondition : Prisma.empty}
+ GROUP BY t.id
+ ORDER BY t."timestamp" DESC
+ LIMIT ${obj.limit} OFFSET ${skipValue}
+ `),
prisma.trace.count({
where: {
projectId: authCheck.scope.projectId,
@@ -143,10 +163,7 @@ export default async function handler(
]);
return res.status(200).json({
- data: traces.map((trace) => ({
- ...trace,
- observations: trace.observations.map((observation) => observation.id),
- })),
+ data: traces,
meta: {
page: obj.page,
limit: obj.limit,
diff --git a/src/pages/api/public/traces/[traceId].ts b/src/pages/api/public/traces/[traceId].ts
index fa10ac9693..0af07f9bae 100644
--- a/src/pages/api/public/traces/[traceId].ts
+++ b/src/pages/api/public/traces/[traceId].ts
@@ -45,23 +45,31 @@ export default async function handler(
}
// END CHECK ACCESS SCOPE
- const trace = await prisma.trace.findFirst({
- where: {
- id: traceId,
- projectId: authCheck.scope.projectId,
- },
- include: {
- observations: true,
- scores: true,
- },
- });
+ const [trace, observations] = await Promise.all([
+ prisma.trace.findFirst({
+ where: {
+ id: traceId,
+ projectId: authCheck.scope.projectId,
+ },
+ include: {
+ scores: true,
+ },
+ }),
+ prisma.observation.findMany({
+ where: {
+ traceId: traceId,
+ projectId: authCheck.scope.projectId,
+ },
+ }),
+ ]);
+
if (!trace) {
return res.status(404).json({
success: false,
message: "Trace not found within authorized project",
});
}
- return res.status(200).json(trace);
+ return res.status(200).json({ ...trace, observations: observations });
} catch (error: unknown) {
console.error(error);
const errorMessage =
diff --git a/src/pages/project/[projectId]/traces/[traceId].tsx b/src/pages/project/[projectId]/traces/[traceId].tsx
index 8cbc759ab3..665e96bcbd 100644
--- a/src/pages/project/[projectId]/traces/[traceId].tsx
+++ b/src/pages/project/[projectId]/traces/[traceId].tsx
@@ -11,7 +11,6 @@ export default function TracePage() {
const projectId = router.query.projectId as string;
const trace = api.traces.byId.useQuery(traceId);
-
return (
<div className="md:container">
<Header
@@ -30,7 +29,6 @@ export default function TracePage() {
) : null}
<TraceAggUsageBadge observations={trace.data?.observations ?? []} />
</div>
-
{trace.data ? (
<>
<div className="mt-5 border-t pt-5">
diff --git a/src/server/api/routers/generations.ts b/src/server/api/routers/generations.ts
index 916800a3e7..b61799b55b 100644
--- a/src/server/api/routers/generations.ts
+++ b/src/server/api/routers/generations.ts
@@ -19,20 +19,25 @@ export const generationsRouter = createTRPCRouter({
const generations = (await ctx.prisma.observation.findMany({
where: {
type: "GENERATION",
- trace: {
- projectId: input.projectId,
+ projectId: input.projectId,
+ traceId: {
+ not: null,
+ ...(input.traceId
+ ? {
+ in: input.traceId,
+ }
+ : undefined),
},
- ...(input.traceId
- ? {
- traceId: { in: input.traceId },
- }
- : undefined),
},
orderBy: {
startTime: "desc",
},
take: 100, // TODO: pagination
- })) as Generation[];
+ })) as Array<
+ Generation & {
+ traceId: string;
+ }
+ >;
return generations;
}),
@@ -41,9 +46,7 @@ export const generationsRouter = createTRPCRouter({
.input(GenerationFilterOptions)
.query(async ({ input, ctx }) => {
const filter = {
- trace: {
- projectId: input.projectId,
- },
+ projectId: input.projectId,
...(input.traceId
? {
traceId: { in: input.traceId },
@@ -65,9 +68,11 @@ export const generationsRouter = createTRPCRouter({
return [
{
key: "traceId",
- occurrences: traceIds.map((i) => {
- return { key: i.traceId, count: i._count };
- }),
+ occurrences: traceIds
+ .filter((i) => i.traceId !== null)
+ .map((i) => {
+ return { key: i.traceId ?? "null", count: i._count };
+ }),
},
];
}),
@@ -77,24 +82,23 @@ export const generationsRouter = createTRPCRouter({
where: {
id: input,
type: "GENERATION",
- trace: {
- project: {
- members: {
- some: {
- userId: ctx.session.user.id,
- },
+ Project: {
+ members: {
+ some: {
+ userId: ctx.session.user.id,
},
},
},
},
})) as Generation;
- // No need to check for permissions as user has access to the trace
- const scores = await ctx.prisma.score.findMany({
- where: {
- traceId: generation.traceId,
- },
- });
+ const scores = generation.traceId
+ ? await ctx.prisma.score.findMany({
+ where: {
+ traceId: generation.traceId,
+ },
+ })
+ : [];
return { ...generation, scores };
}),
diff --git a/src/server/api/routers/traces.ts b/src/server/api/routers/traces.ts
index 1d99ea1559..1905caf9e7 100644
--- a/src/server/api/routers/traces.ts
+++ b/src/server/api/routers/traces.ts
@@ -5,6 +5,7 @@ import {
protectedProcedure,
protectedProjectProcedure,
} from "@/src/server/api/trpc";
+import { Prisma, type Score, type Trace } from "@prisma/client";
const ScoreFilter = z.object({
name: z.string(),
@@ -26,67 +27,99 @@ export const traceRouter = createTRPCRouter({
all: protectedProjectProcedure
.input(TraceFilterOptions)
.query(async ({ input, ctx }) => {
- const traces = await ctx.prisma.trace.findMany({
- where: {
- AND: [
- {
- projectId: input.projectId,
- ...(input.userId ? { userId: input.userId } : undefined),
- ...(input.name ? { name: { in: input.name } } : undefined),
- ...(input.scores
- ? { scores: { some: createScoreCondition(input.scores) } }
- : undefined),
- },
- input.searchQuery
- ? {
- OR: [
- { id: { contains: input.searchQuery } },
- { externalId: { contains: input.searchQuery } },
- { userId: { contains: input.searchQuery } },
- { name: { contains: input.searchQuery } },
- ],
- }
- : {},
- ],
- },
- orderBy: {
- timestamp: "desc",
- },
- include: {
- scores: true,
- observations: {
- select: {
- promptTokens: true,
- completionTokens: true,
- totalTokens: true,
- },
- },
- },
- take: 50, // TODO: pagination
- });
-
- const res = traces.map((trace) => {
- const { observations, ...t } = trace;
- return {
- ...t,
- usage: {
- promptTokens: observations.reduce(
- (acc, cur) => acc + cur.promptTokens,
- 0
- ),
- completionTokens: observations.reduce(
- (acc, cur) => acc + cur.completionTokens,
- 0
- ),
- totalTokens: observations.reduce(
- (acc, cur) => acc + cur.totalTokens,
- 0
- ),
- },
- };
- });
+ const userIdCondition = input.userId
+ ? Prisma.sql`AND t."user_id" = ${input.userId}`
+ : Prisma.empty;
+
+ const createNamesFilter = (names: string[]) => {
+ return Prisma.sql`AND t."name" IN (${Prisma.join(names)})`;
+ };
+
+ const nameCondition = input.name
+ ? createNamesFilter(input.name)
+ : Prisma.empty;
+
+ let scoreCondition = Prisma.empty;
+ if (input.scores) {
+ switch (input.scores.operator) {
+ case "lt":
+ scoreCondition = Prisma.sql`AND "trace_id" in (SELECT distinct trace_id from scores WHERE trace_id IS NOT NULL AND scores.value < ${input.scores.value})`;
+ break;
+ case "gt":
+ scoreCondition = Prisma.sql`AND "trace_id" in (SELECT distinct trace_id from scores WHERE trace_id IS NOT NULL AND scores.value > ${input.scores.value})`;
+ break;
+ case "equals":
+ scoreCondition = Prisma.sql`AND "trace_id" in (SELECT distinct trace_id from scores WHERE trace_id IS NOT NULL AND scores.value = ${input.scores.value})`;
+ break;
+ case "lte":
+ scoreCondition = Prisma.sql`AND "trace_id" in (SELECT distinct trace_id from scores WHERE trace_id IS NOT NULL AND scores.value <= ${input.scores.value})`;
+ break;
+ case "gte":
+ scoreCondition = Prisma.sql`AND "trace_id" in (SELECT distinct trace_id from scores WHERE trace_id IS NOT NULL AND scores.value >= ${input.scores.value})`;
+ break;
+ }
+ }
+
+ const searchCondition = input.searchQuery
+ ? Prisma.sql`AND (
+ t."id" ILIKE ${`%${input.searchQuery}%`} OR
+ t."external_id" ILIKE ${`%${input.searchQuery}%`} OR
+ t."user_id" ILIKE ${`%${input.searchQuery}%`} OR
+ t."name" ILIKE ${`%${input.searchQuery}%`}
+ )`
+ : Prisma.empty;
+
+ const traces = await ctx.prisma.$queryRaw<
+ Array<
+ Trace & {
+ promptTokens: number;
+ completionTokens: number;
+ totalTokens: number;
+ }
+ >
+ >(
+ Prisma.sql`
+ WITH usage as (
+ SELECT
+ trace_id,
+ sum(prompt_tokens) AS "promptTokens",
+ sum(completion_tokens) AS "completionTokens",
+ sum(total_tokens) AS "totalTokens"
+ FROM "observations"
+ WHERE "trace_id" IS NOT NULL AND "project_id" = ${input.projectId}
+ GROUP BY trace_id
+ )
+ SELECT
+ t.*,
+ COALESCE(u."promptTokens", 0)::int AS "promptTokens",
+ COALESCE(u."completionTokens", 0)::int AS "completionTokens",
+ COALESCE(u."totalTokens", 0)::int AS "totalTokens"
+ FROM "traces" AS t
+ LEFT JOIN usage AS u ON u.trace_id = t.id
+ WHERE
+ t."project_id" = ${input.projectId}
+ ${userIdCondition}
+ ${nameCondition}
+ ${searchCondition}
+ ${scoreCondition}
+ ORDER BY t."timestamp" DESC
+ LIMIT 50;
+ `
+ );
- return res;
+ const scores = await ctx.prisma.$queryRaw<Score[]>(
+ Prisma.sql`
+ SELECT s.*
+ FROM "scores" s
+ WHERE s."trace_id" IN (${Prisma.join(
+ traces.map((trace) => trace.id)
+ )})`
+ );
+
+ return traces.map((trace) => ({
+ ...trace,
+ scores: scores.filter((score) => score.traceId === trace.id),
+ }));
}),
availableFilterOptions: protectedProjectProcedure
.input(TraceFilterOptions)
@@ -180,13 +213,14 @@ export const traceRouter = createTRPCRouter({
}),
ctx.prisma.observation.findMany({
where: {
- traceId: input,
- trace: {
- project: {
- members: {
- some: {
- userId: ctx.session.user.id,
- },
+ traceId: {
+ equals: input,
+ not: null,
+ },
+ Project: {
+ members: {
+ some: {
+ userId: ctx.session.user.id,
},
},
},
@@ -196,7 +230,9 @@ export const traceRouter = createTRPCRouter({
return {
...trace,
- observations,
+ observations: observations as Array<
+ (typeof observations)[0] & { traceId: string }
+ >,
};
}),
});
diff --git a/src/server/api/routers/users.ts b/src/server/api/routers/users.ts
index 46d2a2fdc2..e18bd10e69 100644
--- a/src/server/api/routers/users.ts
+++ b/src/server/api/routers/users.ts
@@ -4,6 +4,7 @@ import {
createTRPCRouter,
protectedProjectProcedure,
} from "@/src/server/api/trpc";
+import { Prisma, type Score } from "@prisma/client";
const UserFilterOptions = z.object({
projectId: z.string(), // Required for protectedProjectProcedure
@@ -13,134 +14,82 @@ export const userRouter = createTRPCRouter({
all: protectedProjectProcedure
.input(UserFilterOptions)
.query(async ({ input, ctx }) => {
- const traces = await ctx.prisma.trace.groupBy({
- where: {
- AND: [
- {
- projectId: input.projectId,
- },
- ],
- },
- by: ["userId", "id"],
- });
+ const users = await ctx.prisma.$queryRaw<
+ {
+ userId: string;
+ firstTrace: Date;
+ lastTrace: Date;
+ totalTraces: number;
+ totalPromptTokens: number;
+ totalCompletionTokens: number;
+ totalTokens: number;
+ firstObservation: Date;
+ lastObservation: Date;
+ totalObservations: number;
+ }[]
+ >`
+ SELECT
+ t.user_id "userId",
+ min(t."timestamp") "firstTrace",
+ max(t."timestamp") "lastTrace",
+ COUNT(distinct t.id)::int "totalTraces",
+ COALESCE(SUM(o.prompt_tokens),0)::int "totalPromptTokens",
+ COALESCE(SUM(o.completion_tokens),0)::int "totalCompletionTokens",
+ COALESCE(SUM(o.total_tokens),0)::int "totalTokens",
+ MIN(o.start_time) "firstObservation",
+ MAX(o.start_time) "lastObservation",
+ COUNT(distinct o.id)::int "totalObservations"
+ FROM traces t
+ LEFT JOIN observations o on o.trace_id = t.id
+ WHERE t.user_id is not null
+ AND t.project_id = ${input.projectId}
+ AND o.project_id = ${input.projectId}
+ GROUP BY 1
+ ORDER BY "totalTokens" DESC
+ LIMIT 50
+ `;
- const userIdToTraceIdsMap = traces.reduce((map, trace) => {
- const userId = trace.userId;
- const traceId = trace.id;
-
- if (userId) {
- if (!map.has(userId)) {
- map.set(userId, [traceId]);
- } else {
- map.get(userId)?.push(traceId);
+ const lastScoresOfUsers = await ctx.prisma.$queryRaw<
+ Array<
+ Score & {
+ userId: string;
}
- }
-
- return map;
- }, new Map<string, string[]>());
-
- const userIds = Array.from(userIdToTraceIdsMap.keys());
-
- if (userIds.length === 0) {
- return [];
- }
-
- const [traceAnalytics, observationAnalytics, lastScore] =
- await Promise.all([
- ctx.prisma.trace.groupBy({
- where: {
- userId: {
- in: userIds,
- },
- },
- _count: {
- _all: true,
- },
- _min: {
- timestamp: true,
- },
- _max: {
- timestamp: true,
- },
- by: ["userId"],
- }),
- ctx.prisma.$queryRawUnsafe<
- {
- min_start_time: Date;
- max_start_time: Date;
- total_tokens: number;
- prompt_tokens: number;
- completion_tokens: number;
- total_observations: number;
- user_id: string;
- }[]
- >(`SELECT
- MIN(observations.start_time) AS min_start_time,
- MAX(observations.start_time) AS max_start_time,
- SUM(observations.total_tokens) AS total_tokens,
- SUM(observations.prompt_tokens) AS prompt_tokens,
- SUM(observations.completion_tokens) AS completion_tokens,
- count(*) as total_observations,
- traces.user_id as user_id
+ >
+ >`
+ WITH ranked_scores AS (
+ SELECT
+ t.user_id,
+ s.*,
+ ROW_NUMBER() OVER (PARTITION BY t.user_id ORDER BY s."timestamp" DESC) AS rn
+ FROM
+ scores s
+ JOIN traces t ON t.id = s.trace_id
+ WHERE
+ s.trace_id IS NOT NULL
+ AND t.project_id = ${input.projectId}
+ AND t.user_id IN (${Prisma.join(users.map((user) => user.userId))})
+ AND t.user_id IS NOT NULL
+ )
+ SELECT
+ user_id "userId",
+ "id",
+ "timestamp",
+ "name",
+ "value",
+ observation_id "observationId",
+ trace_id "traceId",
+ "comment"
FROM
- observations
- JOIN traces ON observations.trace_id = traces.id
- WHERE
- traces.user_id IN (${userIds.map((id) => `'${id}'`).join(",")})
- GROUP BY
- traces.user_id
- `),
- ctx.prisma.trace.findMany({
- distinct: ["userId"],
- orderBy: {
- timestamp: "desc",
- },
- include: {
- scores: {
- orderBy: {
- timestamp: "desc",
- },
- take: 1,
- },
- },
- where: {
- userId: {
- in: userIds,
- },
- },
- }),
- ]);
+ ranked_scores
+ WHERE rn = 1
+ `;
- return userIds.map((userId) => {
- const traceAnalyticsForUser = traceAnalytics.find(
- (t) => t.userId === userId
- );
- const observationAnalyticsForUser = observationAnalytics.find(
- (o) => o.user_id === userId
- );
-
- if (!traceAnalyticsForUser || !observationAnalyticsForUser) {
- throw new Error("User not found in analytics");
- }
-
- const returnedScore =
- lastScore.find((s) => s.userId === userId)?.scores[0] ?? null;
-
- return {
- userId: userId,
- firstTrace: traceAnalyticsForUser._min?.timestamp,
- lastTrace: traceAnalyticsForUser?._max?.timestamp,
- totalTraces: traceAnalyticsForUser?._count?._all,
- totalPromptTokens: observationAnalyticsForUser.prompt_tokens ?? 0,
- totalCompletionTokens:
- observationAnalyticsForUser.completion_tokens ?? 0,
- totalTokens: observationAnalyticsForUser.total_tokens ?? 0,
- firstObservation: observationAnalyticsForUser.min_start_time,
- lastObservation: observationAnalyticsForUser.max_start_time,
- totalObservations: observationAnalyticsForUser.total_observations,
- lastScore: returnedScore,
- };
- });
+ return users.map((user) => ({
+ ...user,
+ lastScore: lastScoresOfUsers.find(
+ (score) => score.userId === user.userId
+ ),
+ }));
}),
byId: protectedProjectProcedure
@@ -151,69 +100,91 @@ export const userRouter = createTRPCRouter({
})
)
.query(async ({ input, ctx }) => {
- const [traceAnalytics, observationAnalytics, lastScore] =
- await Promise.all([
- ctx.prisma.trace.groupBy({
- where: {
- userId: input.userId,
- },
- _count: {
- _all: true,
- },
- _min: {
- timestamp: true,
- },
- _max: {
- timestamp: true,
- },
- by: ["userId"],
- }),
- ctx.prisma.observation.aggregate({
- where: {
- trace: {
- userId: input.userId,
- },
- },
- _sum: {
- promptTokens: true,
- completionTokens: true,
- totalTokens: true,
- },
- _min: {
- startTime: true,
- },
- _max: {
- endTime: true,
- },
- _count: {
- _all: true,
- },
- }),
- ctx.prisma.score.findFirst({
- where: {
- trace: {
- userId: input.userId,
- },
- },
- orderBy: {
- timestamp: "desc",
- },
- take: 1,
- }),
- ]);
+ const [agg, lastScoresOfUsers] = await Promise.all([
+ ctx.prisma.$queryRaw<
+ {
+ userId: string;
+ firstTrace: Date;
+ lastTrace: Date;
+ totalTraces: number;
+ totalPromptTokens: number;
+ totalCompletionTokens: number;
+ totalTokens: number;
+ firstObservation: Date;
+ lastObservation: Date;
+ totalObservations: number;
+ }[]
+ >`
+ SELECT
+ t.user_id "userId",
+ min(t."timestamp") "firstTrace",
+ max(t."timestamp") "lastTrace",
+ COUNT(distinct t.id)::int "totalTraces",
+ COALESCE(SUM(o.prompt_tokens),0)::int "totalPromptTokens",
+ COALESCE(SUM(o.completion_tokens),0)::int "totalCompletionTokens",
+ COALESCE(SUM(o.total_tokens),0)::int "totalTokens",
+ MIN(o.start_time) "firstObservation",
+ MAX(o.start_time) "lastObservation",
+ COUNT(distinct o.id)::int "totalObservations"
+ FROM traces t
+ LEFT JOIN observations o on o.trace_id = t.id
+ WHERE t.user_id is not null
+ AND t.project_id = ${input.projectId}
+ AND o.project_id = ${input.projectId}
+ AND t.user_id = ${input.userId}
+ GROUP BY 1
+ ORDER BY "totalTokens" DESC
+ LIMIT 50
+ `,
+
+ ctx.prisma.$queryRaw<
+ Array<
+ Score & {
+ userId: string;
+ }
+ >
+ >`
+ WITH ranked_scores AS (
+ SELECT
+ t.user_id,
+ s.*,
+ ROW_NUMBER() OVER (PARTITION BY t.user_id ORDER BY s."timestamp" DESC) AS rn
+ FROM
+ scores s
+ JOIN traces t ON t.id = s.trace_id
+ WHERE
+ s.trace_id IS NOT NULL
+ AND t.project_id = ${input.projectId}
+ AND t.user_id = ${input.userId}
+ AND t.user_id IS NOT NULL
+ )
+ SELECT
+ user_id "userId",
+ "id",
+ "timestamp",
+ "name",
+ "value",
+ observation_id "observationId",
+ trace_id "traceId",
+ "comment"
+ FROM
+ ranked_scores
+ WHERE rn = 1
+ `,
+ ]);
return {
userId: input.userId,
- firstTrace: traceAnalytics[0]?._min?.timestamp,
- lastTrace: traceAnalytics[0]?._max?.timestamp,
- totalTraces: traceAnalytics[0]?._count?._all,
- totalPromptTokens: observationAnalytics._sum?.promptTokens ?? 0,
- totalCompletionTokens: observationAnalytics._sum?.completionTokens ?? 0,
- totalTokens: observationAnalytics._sum?.totalTokens ?? 0,
- firstObservation: observationAnalytics._min?.startTime,
- lastObservation: observationAnalytics._max?.endTime,
- totalObservations: observationAnalytics._count?._all,
- lastScore: lastScore,
+ firstTrace: agg[0]?.firstTrace,
+ lastTrace: agg[0]?.lastTrace,
+ totalTraces: agg[0]?.totalTraces ?? 0,
+ totalPromptTokens: agg[0]?.totalPromptTokens ?? 0,
+ totalCompletionTokens: agg[0]?.totalCompletionTokens ?? 0,
+ totalTokens: agg[0]?.totalTokens ?? 0,
+ firstObservation: agg[0]?.firstObservation,
+ lastObservation: agg[0]?.lastObservation,
+ totalObservations: agg[0]?.totalObservations ?? 0,
+ lastScore: lastScoresOfUsers[0],
};
}),
});