Skip to content

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

Add events table (#354)

Max Deichmanne2d3a7760f50
diff --git a/prisma/migrations/20231012161041_add_events_table/migration.sql b/prisma/migrations/20231012161041_add_events_table/migration.sql
new file mode 100644
index 0000000000..1530f75563
--- /dev/null
+++ b/prisma/migrations/20231012161041_add_events_table/migration.sql
@@ -0,0 +1,15 @@
+-- CreateTable
+CREATE TABLE "events" (
+ "id" TEXT NOT NULL,
+ "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updated_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "project_id" TEXT NOT NULL,
+ "data" JSONB NOT NULL,
+ "url" TEXT,
+ "method" TEXT,
+
+ CONSTRAINT "events_pkey" PRIMARY KEY ("id")
+);
+
+-- AddForeignKey
+ALTER TABLE "events" ADD CONSTRAINT "events_project_id_fkey" FOREIGN KEY ("project_id") REFERENCES "projects"("id") ON DELETE CASCADE ON UPDATE CASCADE;
diff --git a/prisma/schema.prisma b/prisma/schema.prisma
index 7adfc1103e..b57712084a 100644
--- a/prisma/schema.prisma
+++ b/prisma/schema.prisma
@@ -82,6 +82,7 @@ model Project {
observations Observation[]
apiKeys ApiKey[]
dataset Dataset[]
+ RawEvents Events[]
@@map("projects")
}
@@ -302,3 +303,16 @@ model DatasetRunItems {
@@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
+ url String?
+ method String?
+
+ @@map("events")
+}
diff --git a/src/pages/api/public/event-service.ts b/src/pages/api/public/event-service.ts
new file mode 100644
index 0000000000..e9c4fddacd
--- /dev/null
+++ b/src/pages/api/public/event-service.ts
@@ -0,0 +1,26 @@
+import { jsonSchema } from "@/src/utils/zod";
+import { type PrismaClient } from "@prisma/client";
+import { type NextApiRequest } from "next";
+
+// This function persists raw events to the database which came via API
+// It relates each event to a peroject
+// It checks that the event is valid JSON to avoid DB errors
+// It persists over which URL and Method the event came in
+// It does not extract more data to avoid any early errors such as schema parsing errors
+// this table eventually becomes very large. Old data can be archived then in blob storage
+export const persistEventMiddleware = async (
+ prisma: PrismaClient,
+ projectId: string,
+ req: NextApiRequest,
+) => {
+ const filteredEvent = jsonSchema.parse(req.body);
+
+ await prisma.events.create({
+ data: {
+ project: { connect: { id: projectId } },
+ url: req.url,
+ method: req.method,
+ data: filteredEvent,
+ },
+ });
+};
diff --git a/src/pages/api/public/events.ts b/src/pages/api/public/events.ts
index 0b37818697..795a39d3bc 100644
--- a/src/pages/api/public/events.ts
+++ b/src/pages/api/public/events.ts
@@ -5,6 +5,7 @@ import { z } from "zod";
import { cors, runMiddleware } from "@/src/features/public-api/server/cors";
import { verifyAuthHeaderAndReturnScope } from "@/src/features/public-api/server/apiAuth";
import { v4 as uuidv4 } from "uuid";
+import { persistEventMiddleware } from "@/src/pages/api/public/event-service";
const ObservationSchema = z.object({
id: z.string().nullish(),
@@ -64,6 +65,8 @@ export default async function handler(
version,
} = obj;
+ await persistEventMiddleware(prisma, authCheck.scope.projectId, req);
+
const traceId = !obj.traceId
? // Create trace if no traceid - backwards compatibility
(
diff --git a/src/pages/api/public/generations.ts b/src/pages/api/public/generations.ts
index cc76fed9bc..a7348d87bf 100644
--- a/src/pages/api/public/generations.ts
+++ b/src/pages/api/public/generations.ts
@@ -12,6 +12,7 @@ import { tokenCount } from "@/src/features/ingest/lib/usage";
import { v4 as uuidv4 } from "uuid";
import { backOff } from "exponential-backoff";
import { RessourceNotFoundError } from "../../../utils/exceptions";
+import { persistEventMiddleware } from "@/src/pages/api/public/event-service";
export const GenerationsCreateSchema = z.object({
id: z.string().nullish(),
@@ -97,6 +98,8 @@ export default async function handler(
", body:",
JSON.stringify(req.body, null, 2),
);
+ await persistEventMiddleware(prisma, authCheck.scope.projectId, req);
+
const obj = GenerationsCreateSchema.parse(req.body);
const {
id,
@@ -252,7 +255,7 @@ export default async function handler(
", body:",
JSON.stringify(req.body, null, 2),
);
-
+ await persistEventMiddleware(prisma, authCheck.scope.projectId, req);
try {
const newObservation = await backOff(
async () =>
diff --git a/src/pages/api/public/scores.ts b/src/pages/api/public/scores.ts
index a7235498ca..2c4a9f311c 100644
--- a/src/pages/api/public/scores.ts
+++ b/src/pages/api/public/scores.ts
@@ -6,6 +6,7 @@ import { cors, runMiddleware } from "@/src/features/public-api/server/cors";
import { verifyAuthHeaderAndReturnScope } from "@/src/features/public-api/server/apiAuth";
import { checkApiAccessScope } from "@/src/features/public-api/server/apiScope";
import { paginationZod } from "@/src/utils/zod";
+import { persistEventMiddleware } from "@/src/pages/api/public/event-service";
const ScoreCreateSchema = z.object({
id: z.string().nullish(),
@@ -48,7 +49,7 @@ export default async function handler(
", body:",
JSON.stringify(req.body, null, 2),
);
-
+ await persistEventMiddleware(prisma, authCheck.scope.projectId, req);
const obj = ScoreCreateSchema.parse(req.body);
// If externalTraceId is provided, find the traceId
diff --git a/src/pages/api/public/spans.ts b/src/pages/api/public/spans.ts
index 1ded3e5333..a3b4319ece 100644
--- a/src/pages/api/public/spans.ts
+++ b/src/pages/api/public/spans.ts
@@ -11,6 +11,7 @@ import { verifyAuthHeaderAndReturnScope } from "@/src/features/public-api/server
import { v4 as uuidv4 } from "uuid";
import { backOff } from "exponential-backoff";
import { RessourceNotFoundError } from "../../../utils/exceptions";
+import { persistEventMiddleware } from "@/src/pages/api/public/event-service";
const SpanPostSchema = z.object({
id: z.string().nullish(),
@@ -66,6 +67,9 @@ export default async function handler(
", body:",
JSON.stringify(req.body, null, 2),
);
+
+ await persistEventMiddleware(prisma, authCheck.scope.projectId, req);
+
const obj = SpanPostSchema.parse(req.body);
const {
id,
@@ -182,6 +186,7 @@ export default async function handler(
", body:",
JSON.stringify(req.body, null, 2),
);
+ await persistEventMiddleware(prisma, authCheck.scope.projectId, req);
const newObservation = await backOff(
async () =>
await patchSpan(
diff --git a/src/pages/api/public/traces.ts b/src/pages/api/public/traces.ts
index 274aaf1cae..ede399b9f6 100644
--- a/src/pages/api/public/traces.ts
+++ b/src/pages/api/public/traces.ts
@@ -6,6 +6,7 @@ import { verifyAuthHeaderAndReturnScope } from "@/src/features/public-api/server
import { Prisma, type Trace } from "@prisma/client";
import { v4 as uuidv4 } from "uuid";
import { paginationZod } from "@/src/utils/zod";
+import { persistEventMiddleware } from "@/src/pages/api/public/event-service";
const CreateTraceSchema = z.object({
id: z.string().nullish(),
@@ -48,6 +49,7 @@ export default async function handler(
", body:",
JSON.stringify(req.body, null, 2),
);
+ await persistEventMiddleware(prisma, authCheck.scope.projectId, req);
const { id, name, metadata, externalId, userId, release, version } =
CreateTraceSchema.parse(req.body);