Skip to content

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

Batch endpoint (#423)

Max Deichmann466b6d9cead4
diff --git a/fern/apis/client/definition/score.yml b/fern/apis/client/definition/score.yml
index 6f79d89726..57049a18f3 100644
--- a/fern/apis/client/definition/score.yml
+++ b/fern/apis/client/definition/score.yml
@@ -16,7 +16,6 @@ types:
properties:
id: optional<string>
traceId: string
- traceIdType: optional<TraceIdType>
name: string
value: double
observationId: optional<string>
@@ -30,7 +29,3 @@ types:
observationId: optional<string>
timestamp: datetime
comment: optional<string>
- TraceIdType:
- enum:
- - LANGFUSE
- - EXTERNAL
diff --git a/fern/apis/server/definition/commons.yml b/fern/apis/server/definition/commons.yml
index 4c4bbd082c..2a7b4b53bd 100644
--- a/fern/apis/server/definition/commons.yml
+++ b/fern/apis/server/definition/commons.yml
@@ -4,7 +4,6 @@ types:
properties:
id: optional<string>
traceId: optional<string>
- traceIdType: optional<TraceIdTypeEnum>
name: optional<string>
startTime: optional<datetime>
metadata: optional<unknown>
@@ -35,7 +34,6 @@ types:
type: string
docs: The unique identifier of a trace
timestamp: datetime
- externalId: optional<string>
name: optional<string>
release: optional<string>
version: optional<string>
@@ -135,10 +133,6 @@ types:
- optional<string>
- optional<integer>
- optional<boolean>
- TraceIdTypeEnum:
- enum:
- - LANGFUSE
- - EXTERNAL
LLMUsage:
properties:
promptTokens: optional<integer>
diff --git a/fern/apis/server/definition/ingestion.yml b/fern/apis/server/definition/ingestion.yml
new file mode 100644
index 0000000000..f3b81913a0
--- /dev/null
+++ b/fern/apis/server/definition/ingestion.yml
@@ -0,0 +1,48 @@
+# yaml-language-server: $schema=https://raw.githubusercontent.com/fern-api/fern/main/fern.schema.json
+imports:
+ pagination: ./utils/pagination.yml
+ commons: ./commons.yml
+service:
+ auth: true
+ base-path: /api/public
+ endpoints:
+ batch:
+ docs: Ingest multiple events to Langfuse
+ method: POST
+ path: /ingestion
+ request:
+ name: IngestionRequest
+ body:
+ properties:
+ batch: list<IngestionEvent>
+ response: commons.Score
+
+types:
+ IngestionEvent:
+ discriminant: "type"
+ union:
+ trace-create: TraceEvent
+ score-create: ScoreEvent
+ observation-create: ObservationCreateEvent
+ observation-update: ObservationUpdateEvent
+
+ TraceEvent:
+ properties:
+ id: string
+ timestamp: string
+ body: commons.Trace
+ ObservationCreateEvent:
+ properties:
+ id: string
+ timestamp: string
+ body: commons.Observation
+ ObservationUpdateEvent:
+ properties:
+ id: string
+ timestamp: string
+ body: commons.Observation
+ ScoreEvent:
+ properties:
+ id: string
+ timestamp: string
+ body: commons.Score
diff --git a/fern/apis/server/definition/score.yml b/fern/apis/server/definition/score.yml
index b1492a97ff..93cdd89425 100644
--- a/fern/apis/server/definition/score.yml
+++ b/fern/apis/server/definition/score.yml
@@ -29,7 +29,6 @@ types:
properties:
id: optional<string>
traceId: string
- traceIdType: optional<commons.TraceIdTypeEnum>
name: string
value: double
observationId: optional<string>
diff --git a/fern/fern.config.json b/fern/fern.config.json
index 4d00149d8b..0aeeb3e013 100644
--- a/fern/fern.config.json
+++ b/fern/fern.config.json
@@ -1,4 +1,4 @@
{
"organization": "finto",
- "version": "0.15.0-rc47"
+ "version": "0.15.0-rc68"
}
\ No newline at end of file
diff --git a/generated/openapi-client/openapi.yml b/generated/openapi-client/openapi.yml
index eede8e8306..7aa215de2a 100644
--- a/generated/openapi-client/openapi.yml
+++ b/generated/openapi-client/openapi.yml
@@ -59,8 +59,6 @@ components:
type: string
traceId:
type: string
- traceIdType:
- $ref: '#/components/schemas/TraceIdType'
name:
type: string
value:
@@ -100,12 +98,6 @@ components:
- name
- value
- timestamp
- TraceIdType:
- title: TraceIdType
- type: string
- enum:
- - LANGFUSE
- - EXTERNAL
securitySchemes:
BearerAuth:
type: http
diff --git a/generated/openapi-server/openapi.yml b/generated/openapi-server/openapi.yml
index 1f49b8296c..96251f7496 100644
--- a/generated/openapi-server/openapi.yml
+++ b/generated/openapi-server/openapi.yml
@@ -412,6 +412,64 @@ paths:
application/json:
schema:
$ref: '#/components/schemas/UpdateGenerationRequest'
+ /api/public/ingestion:
+ post:
+ description: Ingest multiple events to Langfuse
+ operationId: ingestion_batch
+ tags:
+ - Ingestion
+ parameters: []
+ responses:
+ '200':
+ description: ''
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/Score'
+ '400':
+ description: ''
+ content:
+ application/json:
+ schema:
+ type: string
+ '401':
+ description: ''
+ content:
+ application/json:
+ schema:
+ type: string
+ '403':
+ description: ''
+ content:
+ application/json:
+ schema:
+ type: string
+ '404':
+ description: ''
+ content:
+ application/json:
+ schema:
+ type: string
+ '405':
+ description: ''
+ content:
+ application/json:
+ schema:
+ type: string
+ security: *ref_0
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ batch:
+ type: array
+ items:
+ $ref: '#/components/schemas/IngestionEvent'
+ required:
+ - batch
/api/public/observations/{observationId}:
get:
description: Get a specific observation
@@ -954,9 +1012,6 @@ components:
traceId:
type: string
nullable: true
- traceIdType:
- $ref: '#/components/schemas/TraceIdTypeEnum'
- nullable: true
name:
type: string
nullable: true
@@ -1027,9 +1082,6 @@ components:
timestamp:
type: string
format: date-time
- externalId:
- type: string
- nullable: true
name:
type: string
nullable: true
@@ -1308,12 +1360,6 @@ components:
nullable: true
- type: boolean
nullable: true
- TraceIdTypeEnum:
- title: TraceIdTypeEnum
- type: string
- enum:
- - LANGFUSE
- - EXTERNAL
LLMUsage:
title: LLMUsage
type: object
@@ -1415,6 +1461,109 @@ components:
nullable: true
required:
- generationId
+ IngestionEvent:
+ title: IngestionEvent
+ oneOf:
+ - type: object
+ allOf:
+ - type: object
+ properties:
+ type:
+ type: string
+ enum:
+ - trace-create
+ - $ref: '#/components/schemas/TraceEvent'
+ required:
+ - type
+ - type: object
+ allOf:
+ - type: object
+ properties:
+ type:
+ type: string
+ enum:
+ - score-create
+ - $ref: '#/components/schemas/ScoreEvent'
+ required:
+ - type
+ - type: object
+ allOf:
+ - type: object
+ properties:
+ type:
+ type: string
+ enum:
+ - observation-create
+ - $ref: '#/components/schemas/ObservationCreateEvent'
+ required:
+ - type
+ - type: object
+ allOf:
+ - type: object
+ properties:
+ type:
+ type: string
+ enum:
+ - observation-update
+ - $ref: '#/components/schemas/ObservationUpdateEvent'
+ required:
+ - type
+ TraceEvent:
+ title: TraceEvent
+ type: object
+ properties:
+ id:
+ type: string
+ timestamp:
+ type: string
+ body:
+ $ref: '#/components/schemas/Trace'
+ required:
+ - id
+ - timestamp
+ - body
+ ObservationCreateEvent:
+ title: ObservationCreateEvent
+ type: object
+ properties:
+ id:
+ type: string
+ timestamp:
+ type: string
+ body:
+ $ref: '#/components/schemas/Observation'
+ required:
+ - id
+ - timestamp
+ - body
+ ObservationUpdateEvent:
+ title: ObservationUpdateEvent
+ type: object
+ properties:
+ id:
+ type: string
+ timestamp:
+ type: string
+ body:
+ $ref: '#/components/schemas/Observation'
+ required:
+ - id
+ - timestamp
+ - body
+ ScoreEvent:
+ title: ScoreEvent
+ type: object
+ properties:
+ id:
+ type: string
+ timestamp:
+ type: string
+ body:
+ $ref: '#/components/schemas/Score'
+ required:
+ - id
+ - timestamp
+ - body
Observations:
title: Observations
type: object
@@ -1437,9 +1586,6 @@ components:
nullable: true
traceId:
type: string
- traceIdType:
- $ref: '#/components/schemas/TraceIdTypeEnum'
- nullable: true
name:
type: string
value:
diff --git a/generated/postman/collection.json b/generated/postman/collection.json
index b232c9c8a1..605e6cc5fa 100644
--- a/generated/postman/collection.json
+++ b/generated/postman/collection.json
@@ -256,7 +256,7 @@
"auth": null,
"body": {
"mode": "raw",
- "raw": "{\n \"id\": \"example\",\n \"traceId\": \"example\",\n \"traceIdType\": \"LANGFUSE\",\n \"name\": \"example\",\n \"startTime\": \"1994-11-05T13:15:30Z\",\n \"metadata\": \"UNKNOWN\",\n \"input\": \"UNKNOWN\",\n \"output\": \"UNKNOWN\",\n \"level\": \"DEBUG\",\n \"statusMessage\": \"example\",\n \"parentObservationId\": \"example\",\n \"version\": \"example\"\n}",
+ "raw": "{\n \"id\": \"example\",\n \"traceId\": \"example\",\n \"name\": \"example\",\n \"startTime\": \"1994-11-05T13:15:30Z\",\n \"metadata\": \"UNKNOWN\",\n \"input\": \"UNKNOWN\",\n \"output\": \"UNKNOWN\",\n \"level\": \"DEBUG\",\n \"statusMessage\": \"example\",\n \"parentObservationId\": \"example\",\n \"version\": \"example\"\n}",
"options": {
"raw": {
"language": "json"
@@ -296,7 +296,7 @@
"auth": null,
"body": {
"mode": "raw",
- "raw": "{\n \"completionStartTime\": \"1994-11-05T13:15:30Z\",\n \"model\": \"example\",\n \"modelParameters\": {\n \"example\": \"example\"\n },\n \"prompt\": \"UNKNOWN\",\n \"completion\": \"UNKNOWN\",\n \"usage\": {\n \"promptTokens\": 0,\n \"completionTokens\": 0,\n \"totalTokens\": 0\n },\n \"endTime\": \"1994-11-05T13:15:30Z\",\n \"id\": \"example\",\n \"traceId\": \"example\",\n \"traceIdType\": \"LANGFUSE\",\n \"name\": \"example\",\n \"startTime\": \"1994-11-05T13:15:30Z\",\n \"metadata\": \"UNKNOWN\",\n \"input\": \"UNKNOWN\",\n \"output\": \"UNKNOWN\",\n \"level\": \"DEBUG\",\n \"statusMessage\": \"example\",\n \"parentObservationId\": \"example\",\n \"version\": \"example\"\n}",
+ "raw": "{\n \"completionStartTime\": \"1994-11-05T13:15:30Z\",\n \"model\": \"example\",\n \"modelParameters\": {\n \"example\": \"example\"\n },\n \"prompt\": \"UNKNOWN\",\n \"completion\": \"UNKNOWN\",\n \"usage\": {\n \"promptTokens\": 0,\n \"completionTokens\": 0,\n \"totalTokens\": 0\n },\n \"endTime\": \"1994-11-05T13:15:30Z\",\n \"id\": \"example\",\n \"traceId\": \"example\",\n \"name\": \"example\",\n \"startTime\": \"1994-11-05T13:15:30Z\",\n \"metadata\": \"UNKNOWN\",\n \"input\": \"UNKNOWN\",\n \"output\": \"UNKNOWN\",\n \"level\": \"DEBUG\",\n \"statusMessage\": \"example\",\n \"parentObservationId\": \"example\",\n \"version\": \"example\"\n}",
"options": {
"raw": {
"language": "json"
@@ -341,6 +341,46 @@
}
]
},
+ {
+ "_type": "container",
+ "description": null,
+ "name": "Ingestion",
+ "item": [
+ {
+ "_type": "endpoint",
+ "name": "Batch",
+ "request": {
+ "description": "Ingest multiple events to Langfuse",
+ "url": {
+ "raw": "{{baseUrl}}/api/public/ingestion",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "api",
+ "public",
+ "ingestion"
+ ],
+ "query": [],
+ "variable": []
+ },
+ "header": [],
+ "method": "POST",
+ "auth": null,
+ "body": {
+ "mode": "raw",
+ "raw": "{\n \"batch\": [\n {\n \"type\": \"trace-create\",\n \"id\": \"example\",\n \"timestamp\": \"example\",\n \"body\": {\n \"id\": \"example\",\n \"timestamp\": \"1994-11-05T13:15:30Z\",\n \"name\": \"example\",\n \"release\": \"example\",\n \"version\": \"example\",\n \"userId\": \"example\",\n \"metadata\": \"UNKNOWN\"\n }\n }\n ]\n}",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ }
+ }
+ },
+ "response": []
+ }
+ ]
+ },
{
"_type": "container",
"description": null,
@@ -469,7 +509,7 @@
"auth": null,
"body": {
"mode": "raw",
- "raw": "{\n \"id\": \"example\",\n \"traceId\": \"example\",\n \"traceIdType\": \"LANGFUSE\",\n \"name\": \"example\",\n \"value\": 0,\n \"observationId\": \"example\",\n \"comment\": \"example\"\n}",
+ "raw": "{\n \"id\": \"example\",\n \"traceId\": \"example\",\n \"name\": \"example\",\n \"value\": 0,\n \"observationId\": \"example\",\n \"comment\": \"example\"\n}",
"options": {
"raw": {
"language": "json"
@@ -555,7 +595,7 @@
"auth": null,
"body": {
"mode": "raw",
- "raw": "{\n \"endTime\": \"1994-11-05T13:15:30Z\",\n \"id\": \"example\",\n \"traceId\": \"example\",\n \"traceIdType\": \"LANGFUSE\",\n \"name\": \"example\",\n \"startTime\": \"1994-11-05T13:15:30Z\",\n \"metadata\": \"UNKNOWN\",\n \"input\": \"UNKNOWN\",\n \"output\": \"UNKNOWN\",\n \"level\": \"DEBUG\",\n \"statusMessage\": \"example\",\n \"parentObservationId\": \"example\",\n \"version\": \"example\"\n}",
+ "raw": "{\n \"endTime\": \"1994-11-05T13:15:30Z\",\n \"id\": \"example\",\n \"traceId\": \"example\",\n \"name\": \"example\",\n \"startTime\": \"1994-11-05T13:15:30Z\",\n \"metadata\": \"UNKNOWN\",\n \"input\": \"UNKNOWN\",\n \"output\": \"UNKNOWN\",\n \"level\": \"DEBUG\",\n \"statusMessage\": \"example\",\n \"parentObservationId\": \"example\",\n \"version\": \"example\"\n}",
"options": {
"raw": {
"language": "json"
diff --git a/jest.config.mjs b/jest.config.mjs
index 9334c45099..34287d3b5a 100644
--- a/jest.config.mjs
+++ b/jest.config.mjs
@@ -22,6 +22,8 @@ const serverTestConfig = {
/** @type {import('jest').Config} */
const config = {
// Add more setup options before each test is run
+ silent: false,
+ verbose: true,
projects: [
await createJestConfig(clientTestConfig)(),
await createJestConfig(serverTestConfig)(),
diff --git a/package.json b/package.json
index 21184e6b10..362affea21 100644
--- a/package.json
+++ b/package.json
@@ -11,7 +11,7 @@
"prettier": "prettier --write ./src *.{ts,js}",
"clean": "rm -rf node_modules",
"start": "next start",
- "test": "jest --verbose=true --runInBand",
+ "test": "jest --runInBand",
"test:watch": "jest --watch --runInBand",
"test:e2e": "playwright test",
"db:migrate": "npx prisma migrate dev",
diff --git a/prisma/migrations/20231112095703_observations_add_unique_constraint/migration.sql b/prisma/migrations/20231112095703_observations_add_unique_constraint/migration.sql
new file mode 100644
index 0000000000..f25673cee2
--- /dev/null
+++ b/prisma/migrations/20231112095703_observations_add_unique_constraint/migration.sql
@@ -0,0 +1,8 @@
+/*
+ Warnings:
+
+ - A unique constraint covering the columns `[id,project_id]` on the table `observations` will be added. If there are existing duplicate values, this will fail.
+
+*/
+-- CreateIndex
+CREATE UNIQUE INDEX "observations_id_project_id_key" ON "observations"("id", "project_id");
diff --git a/prisma/schema.prisma b/prisma/schema.prisma
index 2ed8d48ce1..b06a7c6519 100644
--- a/prisma/schema.prisma
+++ b/prisma/schema.prisma
@@ -183,6 +183,7 @@ model Observation {
derivedDatasetItems DatasetItem[]
datasetRunItems DatasetRunItems[]
+ @@unique([id, projectId])
@@index([traceId])
@@index([type])
@@index(startTime)
diff --git a/src/__tests__/events.servertest.ts b/src/__tests__/events.servertest.ts
index c63772ee26..f160bac516 100644
--- a/src/__tests__/events.servertest.ts
+++ b/src/__tests__/events.servertest.ts
@@ -6,7 +6,6 @@ import { v4 as uuidv4 } from "uuid";
describe("/api/public/events API Endpoint", () => {
beforeEach(async () => await pruneDatabase());
- afterEach(async () => await pruneDatabase());
it("should create event after trace", async () => {
await pruneDatabase();
@@ -44,7 +43,7 @@ describe("/api/public/events API Endpoint", () => {
version: "2.0.0",
});
- expect(createEvent.status).toBe(200);
+ expect(createEvent.status).toBe(201);
const dbEvent = await prisma.observation.findUnique({
where: {
id: eventId,
@@ -78,7 +77,7 @@ describe("/api/public/events API Endpoint", () => {
version: "2.0.0",
});
- expect(createEvent.status).toBe(200);
+ expect(createEvent.status).toBe(201);
const dbEvent = await prisma.observation.findUnique({
where: {
id: eventId,
@@ -114,12 +113,12 @@ describe("/api/public/events API Endpoint", () => {
expect(dbTrace[0]?.id).toBe(traceId);
});
- it("should create event after trace based on externalId", async () => {
+ it("should create trace and ignore externalId and create event afterwards", async () => {
await pruneDatabase();
const traceId = uuidv4();
- await makeAPICall("POST", "/api/public/traces", {
+ const response = await makeAPICall("POST", "/api/public/traces", {
externalId: traceId,
name: "trace-name",
userId: "user-1",
@@ -129,21 +128,23 @@ describe("/api/public/events API Endpoint", () => {
version: "2.0.0",
});
+ expect(response.status).toBe(201);
+
const dbTrace = await prisma.trace.findMany({
where: {
- externalId: traceId,
+ name: "trace-name",
},
});
expect(dbTrace.length).toBeGreaterThan(0);
- expect(dbTrace[0]?.externalId).toBe(traceId);
+ expect(dbTrace[0]?.externalId).toBeNull();
expect(dbTrace[0]?.id).not.toBe(traceId);
- const spanId = uuidv4();
- const createEvent = await makeAPICall("POST", "/api/public/spans", {
- id: spanId,
+ const eventId = uuidv4();
+ const createEvent = await makeAPICall("POST", "/api/public/events", {
+ id: eventId,
traceIdType: "EXTERNAL",
- traceId: traceId,
+ traceId: dbTrace[0]?.id,
name: "event-name",
startTime: "2021-01-01T00:00:00.000Z",
input: { input: "value" },
@@ -152,14 +153,14 @@ describe("/api/public/events API Endpoint", () => {
version: "2.0.0",
});
- expect(createEvent.status).toBe(200);
+ expect(createEvent.status).toBe(201);
const dbEvent = await prisma.observation.findUnique({
where: {
- id: spanId,
+ id: eventId,
},
});
- expect(dbEvent?.id).toBe(spanId);
+ expect(dbEvent?.id).toBe(eventId);
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"));
@@ -193,50 +194,7 @@ describe("/api/public/events API Endpoint", () => {
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);
+ expect(createEvent.status).toBe(201);
const dbEvent = await prisma.observation.findUnique({
where: {
id: spanId,
@@ -274,14 +232,14 @@ describe("/api/public/events API Endpoint", () => {
const dbTrace = await prisma.trace.findMany({
where: {
- id: dbEvent.traceId,
+ id: dbEvent.traceId!,
},
});
expect(dbTrace.length).toBe(1);
expect(dbTrace[0]?.name).toBe(generationName);
- expect(createSpan.status).toBe(200);
+ expect(createSpan.status).toBe(201);
expect(dbEvent?.id).toBe(spanId);
expect(dbEvent?.traceId).toBe(dbTrace[0]?.id);
diff --git a/src/__tests__/generations.servertest.ts b/src/__tests__/generations.servertest.ts
index 2a76899f8b..734eca0eb3 100644
--- a/src/__tests__/generations.servertest.ts
+++ b/src/__tests__/generations.servertest.ts
@@ -50,7 +50,7 @@ describe("/api/public/generations API Endpoint", () => {
},
);
- expect(createGeneration.status).toBe(200);
+ expect(createGeneration.status).toBe(201);
const dbGeneration = await prisma.observation.findUnique({
where: {
id: generationId,
@@ -94,7 +94,7 @@ describe("/api/public/generations API Endpoint", () => {
},
);
- expect(createGeneration.status).toBe(200);
+ expect(createGeneration.status).toBe(201);
const dbGeneration = await prisma.observation.findUnique({
where: {
id: generationId,
@@ -134,12 +134,10 @@ describe("/api/public/generations API Endpoint", () => {
expect(dbTrace[0]?.id).toBe(traceId);
});
- it("should create generation after trace based on externalId", async () => {
- await pruneDatabase();
-
+ it("should create generation after trace ignoring externalId", async () => {
const traceId = uuidv4();
- await makeAPICall("POST", "/api/public/traces", {
+ const response = await makeAPICall("POST", "/api/public/traces", {
externalId: traceId,
name: "trace-name",
userId: "user-1",
@@ -149,14 +147,16 @@ describe("/api/public/generations API Endpoint", () => {
version: "2.0.0",
});
+ expect(response.status).toBe(201);
+
const dbTrace = await prisma.trace.findMany({
where: {
- externalId: traceId,
+ name: "trace-name",
},
});
expect(dbTrace.length).toBeGreaterThan(0);
- expect(dbTrace[0]?.externalId).toBe(traceId);
+ expect(dbTrace[0]?.externalId).toBeNull();
expect(dbTrace[0]?.id).not.toBe(traceId);
const generationId = uuidv4();
@@ -178,7 +178,7 @@ describe("/api/public/generations API Endpoint", () => {
},
);
- expect(createGeneration.status).toBe(200);
+ expect(createGeneration.status).toBe(201);
const dbGeneration = await prisma.observation.findUnique({
where: {
id: generationId,
@@ -186,7 +186,7 @@ describe("/api/public/generations API Endpoint", () => {
});
expect(dbGeneration?.id).toBe(generationId);
- expect(dbGeneration?.traceId).toBe(dbTrace[0]?.id);
+ expect(dbGeneration?.traceId).toBe(traceId);
expect(dbGeneration?.name).toBe("generation-name");
expect(dbGeneration?.startTime).toEqual(
new Date("2021-01-01T00:00:00.000Z"),
@@ -228,7 +228,7 @@ describe("/api/public/generations API Endpoint", () => {
expect(dbTrace.length).toBe(1);
expect(dbTrace[0]?.name).toBe(generationName);
- expect(createGeneration.status).toBe(200);
+ expect(createGeneration.status).toBe(201);
const dbGeneration = await prisma.observation.findUnique({
where: {
id: generationId,
@@ -269,7 +269,7 @@ describe("/api/public/generations API Endpoint", () => {
},
);
- expect(createGeneration.status).toBe(200);
+ expect(createGeneration.status).toBe(201);
const dbGeneration = await prisma.observation.findUnique({
where: {
id: generationId,
@@ -297,7 +297,7 @@ describe("/api/public/generations API Endpoint", () => {
parentObservationId: generationId,
},
);
- expect(createGeneration2.status).toBe(200);
+ expect(createGeneration2.status).toBe(201);
const dbGeneration2 = await prisma.observation.findUnique({
where: {
@@ -309,7 +309,7 @@ describe("/api/public/generations API Endpoint", () => {
expect(dbGeneration2?.parentObservationId).toBe(generationId);
});
- it("should create trace when creating generation without existing trace with externalId", async () => {
+ it("should not create trace when creating generation without existing trace with externalId", async () => {
const generationName = uuidv4();
const generationId = uuidv4();
@@ -332,34 +332,18 @@ describe("/api/public/generations API Endpoint", () => {
},
);
- const dbTrace = await prisma.trace.findMany({
- where: {
- externalId: externalTraceId,
- },
- });
-
- expect(dbTrace.length).toBe(1);
- expect(dbTrace[0]?.name).toBeNull();
+ expect(createGeneration.status).toBe(201);
- expect(createGeneration.status).toBe(200);
- const dbGeneration = await prisma.observation.findUnique({
+ const dbGeneration = await prisma.observation.findFirstOrThrow({
where: {
- id: generationId,
+ name: generationName,
},
});
-
expect(dbGeneration?.id).toBe(generationId);
- expect(dbGeneration?.traceId).toBe(dbTrace[0]?.id);
- expect(dbGeneration?.name).toBe(generationName);
- 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");
+ expect(dbGeneration?.traceId).toBe(externalTraceId);
+
+ const dbTraces = await prisma.trace.findMany();
+ expect(dbTraces.length).toBe(0);
});
it("should create trace when creating generation without existing trace without traceId", async () => {
@@ -397,7 +381,7 @@ describe("/api/public/generations API Endpoint", () => {
expect(dbTrace.length).toBe(1);
expect(dbTrace[0]?.name).toBe(generationName);
- expect(createGeneration.status).toBe(200);
+ expect(createGeneration.status).toBe(201);
expect(dbGeneration?.id).toBe(generationId);
expect(dbGeneration?.traceId).toBe(dbTrace[0]?.id);
@@ -433,7 +417,7 @@ describe("/api/public/generations API Endpoint", () => {
},
);
- expect(createGeneration.status).toBe(200);
+ expect(createGeneration.status).toBe(201);
const updateGeneration = await makeAPICall(
"PATCH",
@@ -443,7 +427,7 @@ describe("/api/public/generations API Endpoint", () => {
completion: "this is a great gpt response",
},
);
- expect(updateGeneration.status).toBe(200);
+ expect(updateGeneration.status).toBe(201);
const dbGeneration = await prisma.observation.findUnique({
where: {
@@ -489,7 +473,7 @@ describe("/api/public/generations API Endpoint", () => {
},
);
- expect(createGeneration.status).toBe(200);
+ expect(createGeneration.status).toBe(201);
const dbGeneration = await prisma.observation.findUnique({
where: {
@@ -512,7 +496,7 @@ describe("/api/public/generations API Endpoint", () => {
]);
});
- it("should fail update if generation does not exist", async () => {
+ it("should not succeed update if generation does not exist", async () => {
const generationId = uuidv4();
const updateGeneration = await makeAPICall(
@@ -524,5 +508,13 @@ describe("/api/public/generations API Endpoint", () => {
},
);
expect(updateGeneration.status).toBe(404);
+
+ const dbGeneration = await prisma.observation.findUnique({
+ where: {
+ id: generationId,
+ },
+ });
+
+ expect(dbGeneration).toBeNull();
});
});
diff --git a/src/__tests__/ingestion.servertest.ts b/src/__tests__/ingestion.servertest.ts
new file mode 100644
index 0000000000..877a3dad67
--- /dev/null
+++ b/src/__tests__/ingestion.servertest.ts
@@ -0,0 +1,587 @@
+/** @jest-environment node */
+
+import { makeAPICall, pruneDatabase } from "@/src/__tests__/test-utils";
+import { prisma } from "@/src/server/db";
+import { v4 } from "uuid";
+
+describe("/api/public/ingestion API Endpoint", () => {
+ beforeEach(async () => await pruneDatabase());
+
+ it("should create trace and generation", async () => {
+ const traceId = v4();
+ const generationId = v4();
+ const spanId = v4();
+ const scoreId = v4();
+
+ const response = await makeAPICall("POST", "/api/public/ingestion", {
+ batch: [
+ {
+ id: v4(),
+ type: "trace-create",
+ timestamp: new Date().toISOString(),
+ body: {
+ id: traceId,
+ name: "trace-name",
+ userId: "user-1",
+ metadata: { key: "value" },
+ release: "1.0.0",
+ version: "2.0.0",
+ },
+ },
+ {
+ id: v4(),
+ type: "observation-create",
+ timestamp: new Date().toISOString(),
+ body: {
+ id: generationId,
+ traceId: traceId,
+ type: "GENERATION",
+ name: "generation-name",
+ startTime: "2021-01-01T00:00:00.000Z",
+ endTime: "2021-01-01T00:00:00.000Z",
+ modelParameters: { key: "value" },
+ input: { key: "value" },
+ metadata: { key: "value" },
+ version: "2.0.0",
+ },
+ },
+ {
+ id: v4(),
+ type: "observation-update",
+ timestamp: new Date().toISOString(),
+ body: {
+ id: generationId,
+ type: "GENERATION",
+ output: { key: "this is a great gpt output" },
+ usage: { promptTokens: 400, completionTokens: 1000 },
+ },
+ },
+ {
+ id: v4(),
+ type: "observation-create",
+ timestamp: new Date().toISOString(),
+ body: {
+ id: spanId,
+ traceId: traceId,
+ type: "SPAN",
+ 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",
+ },
+ },
+ {
+ id: v4(),
+ type: "score-create",
+ timestamp: new Date().toISOString(),
+ body: {
+ id: scoreId,
+ name: "score-name",
+ value: 100.5,
+ traceId: traceId,
+ },
+ },
+ ],
+ });
+
+ expect(response.status).toBe(207);
+
+ const dbTrace = await prisma.trace.findMany({
+ where: {
+ name: "trace-name",
+ },
+ });
+
+ expect(dbTrace.length).toBeGreaterThan(0);
+ expect(dbTrace[0]?.name).toBe("trace-name");
+ expect(dbTrace[0]?.release).toBe("1.0.0");
+ expect(dbTrace[0]?.externalId).toBeNull();
+ expect(dbTrace[0]?.version).toBe("2.0.0");
+ expect(dbTrace[0]?.projectId).toBe("7a88fb47-b4e2-43b8-a06c-a5ce950dc53a");
+
+ 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).toBeNull();
+ 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");
+ expect(dbGeneration?.promptTokens).toEqual(400);
+ expect(dbGeneration?.completionTokens).toEqual(1000);
+ expect(dbGeneration?.output).toEqual({
+ key: "this is a great gpt output",
+ });
+
+ const dbSpan = await prisma.observation.findUnique({
+ where: {
+ id: spanId,
+ },
+ });
+
+ expect(dbSpan?.id).toBe(spanId);
+ 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-:00:00.000Z"));
+ expect(dbSpan?.input).toEqual({ input: "value" });
+ expect(dbSpan?.metadata).toEqual({ meta: "value" });
+ expect(dbSpan?.version).toBe("2.0.0");
+
+ const dbScore = await prisma.score.findUnique({
+ where: {
+ id: scoreId,
+ },
+ });
+
+ expect(dbScore?.id).toBe(scoreId);
+ expect(dbScore?.traceId).toBe(traceId);
+ expect(dbScore?.name).toBe("score-name");
+ expect(dbScore?.value).toBe(100.5);
+ expect(dbScore?.observationId).toBeNull();
+ });
+
+ it("should upsert threats", async () => {
+ const traceId = v4();
+
+ const responseOne = await makeAPICall("POST", "/api/public/ingestion", {
+ batch: [
+ {
+ id: v4(),
+ type: "trace-create",
+ timestamp: new Date().toISOString(),
+ body: {
+ id: traceId,
+ name: "trace-name",
+ userId: "user-1",
+ metadata: { key: "value" },
+ release: "1.0.0",
+ version: "2.0.0",
+ },
+ },
+ ],
+ });
+ expect(responseOne.status).toBe(207);
+
+ const responseTwo = await makeAPICall("POST", "/api/public/ingestion", {
+ batch: [
+ {
+ id: v4(),
+ type: "trace-create",
+ timestamp: new Date().toISOString(),
+ body: {
+ id: traceId,
+ name: "trace-name",
+ userId: "user-2",
+ },
+ },
+ ],
+ });
+
+ expect(responseTwo.status).toBe(207);
+
+ const dbTrace = await prisma.trace.findMany({
+ where: {
+ name: "trace-name",
+ },
+ });
+
+ expect(dbTrace.length).toBeGreaterThan(0);
+ expect(dbTrace[0]?.name).toBe("trace-name");
+ expect(dbTrace[0]?.userId).toBe("user-2");
+ expect(dbTrace[0]?.release).toBe("1.0.0");
+ expect(dbTrace[0]?.externalId).toBeNull();
+ expect(dbTrace[0]?.version).toBe("2.0.0");
+ expect(dbTrace[0]?.projectId).toBe("7a88fb47-b4e2-43b8-a06c-a5ce950dc53a");
+ });
+
+ it("should fail for wrong event formats", async () => {
+ const traceId = v4();
+
+ const responseOne = await makeAPICall("POST", "/api/public/ingestion", {
+ batch: [
+ {
+ id: "invalid-event",
+ },
+ {
+ id: v4(),
+ type: "trace-create",
+ timestamp: new Date().toISOString(),
+ body: {
+ id: traceId,
+ name: "trace-name",
+ userId: "user-1",
+ metadata: { key: "value" },
+ release: "1.0.0",
+ version: "2.0.0",
+ },
+ },
+ ],
+ });
+ expect(responseOne.status).toBe(207);
+
+ expect("errors" in responseOne.body).toBe(true);
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
+ expect(responseOne.body?.errors.length).toBe(1);
+ expect("successes" in responseOne.body).toBe(true);
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
+ expect(responseOne.body?.successes.length).toBe(1);
+
+ const dbTrace = await prisma.trace.findMany({
+ where: {
+ name: "trace-name",
+ },
+ });
+
+ expect(dbTrace.length).toBe(1);
+ });
+
+ it("should update all token counts if update does not contain model name", async () => {
+ const traceId = v4();
+ const generationId = v4();
+
+ const responseOne = await makeAPICall("POST", "/api/public/ingestion", {
+ batch: [
+ {
+ id: v4(),
+ type: "trace-create",
+ timestamp: new Date().toISOString(),
+ body: {
+ id: traceId,
+ name: "trace-name",
+ userId: "user-1",
+ },
+ },
+ {
+ id: v4(),
+ type: "observation-create",
+ timestamp: new Date().toISOString(),
+ body: {
+ id: generationId,
+ traceId: traceId,
+ type: "GENERATION",
+ name: "generation-name",
+ input: { key: "value" },
+ model: "gpt-3.5",
+ },
+ },
+ {
+ id: v4(),
+ type: "observation-update",
+ timestamp: new Date().toISOString(),
+ body: {
+ id: generationId,
+ type: "GENERATION",
+ output: { key: "this is a great gpt output" },
+ },
+ },
+ ],
+ });
+ expect(responseOne.status).toBe(207);
+
+ const dbTrace = await prisma.trace.findMany({
+ where: {
+ name: "trace-name",
+ },
+ });
+
+ expect(dbTrace.length).toEqual(1);
+
+ const observation = await prisma.observation.findUnique({
+ where: {
+ id: generationId,
+ },
+ });
+
+ expect(observation?.output).toEqual({
+ key: "this is a great gpt output",
+ });
+ expect(observation?.input).toEqual({ key: "value" });
+ expect(observation?.model).toEqual("gpt-3.5");
+ expect(observation?.output).toEqual({ key: "this is a great gpt output" });
+ expect(observation?.promptTokens).toEqual(5);
+ expect(observation?.completionTokens).toEqual(11);
+ });
+
+ it("should update all token counts if update does not contain model name and events come in wrong order", async () => {
+ const traceId = v4();
+ const generationId = v4();
+
+ const responseOne = await makeAPICall("POST", "/api/public/ingestion", {
+ batch: [
+ {
+ id: v4(),
+ type: "trace-create",
+ timestamp: new Date().toISOString(),
+ body: {
+ id: traceId,
+ name: "trace-name",
+ userId: "user-1",
+ },
+ },
+ {
+ id: v4(),
+ type: "observation-update",
+ timestamp: new Date().toISOString(),
+ body: {
+ id: generationId,
+ type: "GENERATION",
+ output: { key: "this is a great gpt output" },
+ },
+ },
+ {
+ id: v4(),
+ type: "observation-create",
+ timestamp: new Date().toISOString(),
+ body: {
+ id: generationId,
+ traceId: traceId,
+ type: "GENERATION",
+ name: "generation-name",
+ input: { key: "value" },
+ model: "gpt-3.5",
+ },
+ },
+ ],
+ });
+ expect(responseOne.status).toBe(207);
+
+ const dbTrace = await prisma.trace.findMany({
+ where: {
+ name: "trace-name",
+ },
+ });
+
+ expect(dbTrace.length).toEqual(1);
+
+ const observation = await prisma.observation.findUnique({
+ where: {
+ id: generationId,
+ },
+ });
+
+ expect(observation?.output).toEqual({
+ key: "this is a great gpt output",
+ });
+ expect(observation?.input).toEqual({ key: "value" });
+ expect(observation?.model).toEqual("gpt-3.5");
+ expect(observation?.output).toEqual({ key: "this is a great gpt output" });
+ expect(observation?.promptTokens).toEqual(5);
+ expect(observation?.completionTokens).toEqual(11);
+ });
+
+ it("null does not override set values", async () => {
+ const traceId = v4();
+
+ const responseOne = await makeAPICall("POST", "/api/public/ingestion", {
+ batch: [
+ {
+ id: v4(),
+ type: "trace-create",
+ timestamp: new Date().toISOString(),
+ body: {
+ id: traceId,
+ name: "trace-name",
+ userId: "user-1",
+ metadata: { key: "value" },
+ release: "1.0.0",
+ version: "2.0.0",
+ },
+ },
+ {
+ id: v4(),
+ type: "trace-create",
+ timestamp: new Date().toISOString(),
+ body: {
+ id: traceId,
+ name: "trace-name",
+ userId: "user-1",
+ metadata: { key: "value" },
+ release: null,
+ version: null,
+ },
+ },
+ ],
+ });
+ expect(responseOne.status).toBe(207);
+
+ const dbTrace = await prisma.trace.findMany({
+ where: {
+ name: "trace-name",
+ },
+ });
+
+ expect(dbTrace.length).toEqual(1);
+ expect(dbTrace[0]?.release).toBe("1.0.0");
+ expect(dbTrace[0]?.version).toBe("2.0.0");
+ });
+
+ [
+ {
+ inputs: [{ a: "a" }, { b: "b" }],
+ output: { a: "a", b: "b" },
+ },
+ {
+ inputs: [[{ a: "a" }], [{ b: "b" }]],
+ output: [{ a: "a", b: "b" }],
+ },
+ {
+ inputs: [
+ {
+ a: {
+ "1": 1,
+ },
+ },
+ {
+ b: "b",
+ a: {
+ "2": 2,
+ },
+ },
+ ],
+ output: { a: { "1": 1, "2": 2 }, b: "b" },
+ },
+ {
+ inputs: [{ a: "a" }, undefined],
+ output: { a: "a" },
+ },
+ {
+ inputs: [undefined, { b: "b" }],
+ output: { b: "b" },
+ },
+ ].forEach(({ inputs, output }) => {
+ it(`merges metadata ${JSON.stringify(inputs)}, ${JSON.stringify(
+ output,
+ )}`, async () => {
+ const traceId = v4();
+ const generationId = v4();
+
+ const responseOne = await makeAPICall("POST", "/api/public/ingestion", {
+ batch: [
+ {
+ id: v4(),
+ type: "trace-create",
+ timestamp: new Date().toISOString(),
+ body: {
+ id: traceId,
+ name: "trace-name",
+ userId: "user-1",
+ metadata: inputs[0],
+ },
+ },
+ {
+ id: v4(),
+ type: "trace-create",
+ timestamp: new Date().toISOString(),
+ body: {
+ id: traceId,
+ name: "trace-name",
+ metadata: inputs[1],
+ },
+ },
+ {
+ id: v4(),
+ type: "observation-create",
+ timestamp: new Date().toISOString(),
+ body: {
+ id: generationId,
+ traceId: traceId,
+ type: "GENERATION",
+ name: "generation-name",
+ metadata: inputs[0],
+ },
+ },
+ {
+ id: v4(),
+ type: "observation-update",
+ timestamp: new Date().toISOString(),
+ body: {
+ id: generationId,
+ traceId: traceId,
+ type: "GENERATION",
+ metadata: inputs[1],
+ },
+ },
+ ],
+ });
+ expect(responseOne.status).toBe(207);
+
+ const dbTrace = await prisma.trace.findMany({
+ where: {
+ name: "trace-name",
+ },
+ });
+
+ expect(dbTrace.length).toEqual(1);
+ expect(dbTrace[0]?.metadata).toEqual(output);
+
+ const dbGeneration = await prisma.observation.findMany({
+ where: {
+ name: "generation-name",
+ },
+ });
+
+ expect(dbGeneration.length).toEqual(1);
+ expect(dbGeneration[0]?.metadata).toEqual(output);
+ });
+ });
+
+ it("additional fields do not fail the API to support users sending traceidtype Langfuse", async () => {
+ const traceId = v4();
+ const generationId = v4();
+
+ const responseOne = await makeAPICall("POST", "/api/public/ingestion", {
+ batch: [
+ {
+ id: v4(),
+ type: "trace-create",
+ timestamp: new Date().toISOString(),
+ body: {
+ id: traceId,
+ name: "trace-name",
+ },
+ },
+ {
+ id: v4(),
+ type: "observation-create",
+ timestamp: new Date().toISOString(),
+ body: {
+ id: generationId,
+ traceId: traceId,
+ type: "GENERATION",
+ name: "generation-name",
+ traceIdType: "LANGFUSE",
+ },
+ },
+ ],
+ });
+ expect(responseOne.status).toBe(207);
+
+ const dbTrace = await prisma.trace.findMany({
+ where: {
+ id: traceId,
+ },
+ });
+
+ expect(dbTrace.length).toEqual(1);
+
+ const dbGeneration = await prisma.observation.findUnique({
+ where: {
+ id: generationId,
+ },
+ });
+
+ expect(dbGeneration).toBeTruthy();
+ });
+});
diff --git a/src/__tests__/scores.servertest.ts b/src/__tests__/scores.servertest.ts
index 99335e7a96..3cc88f92fe 100644
--- a/src/__tests__/scores.servertest.ts
+++ b/src/__tests__/scores.servertest.ts
@@ -40,7 +40,7 @@ describe("/api/public/scores API Endpoint", () => {
traceId: traceId,
});
- expect(createScore.status).toBe(200);
+ expect(createScore.status).toBe(201);
const dbScore = await prisma.score.findUnique({
where: {
id: scoreId,
@@ -86,7 +86,7 @@ describe("/api/public/scores API Endpoint", () => {
traceId: traceId,
});
- expect(createScore.status).toBe(200);
+ expect(createScore.status).toBe(201);
const dbScore = await prisma.score.findUnique({
where: {
id: scoreId,
@@ -135,7 +135,7 @@ describe("/api/public/scores API Endpoint", () => {
observationId: dbGeneration[0]!.id,
});
- expect(createScore.status).toBe(200);
+ expect(createScore.status).toBe(201);
const dbScore = await prisma.score.findUnique({
where: {
id: scoreId,
diff --git a/src/__tests__/spans.servertest.ts b/src/__tests__/spans.servertest.ts
index 66c3500942..de32ac4cb0 100644
--- a/src/__tests__/spans.servertest.ts
+++ b/src/__tests__/spans.servertest.ts
@@ -44,7 +44,7 @@ describe("/api/public/spans API Endpoint", () => {
version: "2.0.0",
});
- expect(createSpan.status).toBe(200);
+ expect(createSpan.status).toBe(201);
const dbSpan = await prisma.observation.findUnique({
where: {
id: spanId,
@@ -78,7 +78,7 @@ describe("/api/public/spans API Endpoint", () => {
version: "2.0.0",
});
- expect(createSpan.status).toBe(200);
+ expect(createSpan.status).toBe(201);
const dbSpan = await prisma.observation.findUnique({
where: {
id: spanId,
@@ -114,59 +114,34 @@ describe("/api/public/spans API Endpoint", () => {
expect(dbTrace[0]?.id).toBe(traceId);
});
- it("should create span after trace based on externalId", async () => {
- await pruneDatabase();
-
+ it("should create span after trace ignoring externalId", async () => {
const traceId = uuidv4();
+ const spanId = uuidv4();
- await makeAPICall("POST", "/api/public/traces", {
- externalId: traceId,
+ const response = await makeAPICall("POST", "/api/public/traces", {
+ externalId: uuidv4(),
+ 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: {
- externalId: traceId,
- },
- });
-
- expect(dbTrace.length).toBeGreaterThan(0);
- expect(dbTrace[0]?.externalId).toBe(traceId);
- expect(dbTrace[0]?.id).not.toBe(traceId);
-
- const spanId = uuidv4();
+ expect(response.status).toBe(201);
const createSpan = await makeAPICall("POST", "/api/public/spans", {
id: spanId,
- traceIdType: "EXTERNAL",
+ name: "spanName",
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
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",
+ externalTraceIdType: "EXTERNAL",
});
+ expect(createSpan.status).toBe(201);
- expect(createSpan.status).toBe(200);
- const dbSpan = await prisma.observation.findUnique({
+ const dbSpan = await prisma.observation.findFirstOrThrow({
where: {
- id: spanId,
+ name: "spanName",
},
});
-
expect(dbSpan?.id).toBe(spanId);
- expect(dbSpan?.traceId).toBe(dbTrace[0]?.id);
- 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");
+ expect(dbSpan?.traceId).toBe(traceId);
});
it("should create trace when creating span without existing trace", async () => {
@@ -192,7 +167,7 @@ describe("/api/public/spans API Endpoint", () => {
expect(dbTrace.length).toBe(1);
expect(dbTrace[0]?.name).toBe(spanName);
- expect(createSpan.status).toBe(200);
+ expect(createSpan.status).toBe(201);
const dbSpan = await prisma.observation.findUnique({
where: {
id: spanId,
@@ -213,11 +188,11 @@ describe("/api/public/spans API Endpoint", () => {
const spanName = uuidv4();
const spanId = uuidv4();
- const externalTraceId = uuidv4();
+ const traceId = uuidv4();
const createSpan = await makeAPICall("POST", "/api/public/spans", {
id: spanId,
traceIdType: "EXTERNAL",
- traceId: externalTraceId,
+ traceId: traceId,
name: spanName,
startTime: "2021-01-01T00:00:00.000Z",
endTime: "2021-01-01T00:00:00.000Z",
@@ -226,30 +201,20 @@ describe("/api/public/spans API Endpoint", () => {
version: "2.0.0",
});
- const dbTrace = await prisma.trace.findMany({
- where: {
- externalId: externalTraceId,
- },
- });
-
- expect(dbTrace.length).toBe(1);
- expect(dbTrace[0]?.name).toBeNull();
+ expect(createSpan.status).toBe(201);
- expect(createSpan.status).toBe(200);
- const dbSpan = await prisma.observation.findUnique({
+ const dbSpan = await prisma.observation.findMany({
where: {
- id: spanId,
+ name: spanName,
},
});
+ expect(dbSpan.length).toBe(1);
+ expect(dbSpan[0]?.name).toBe(spanName);
+ expect(dbSpan[0]?.id).toBe(spanId);
+ expect(dbSpan[0]?.traceId).toBe(traceId);
- expect(dbSpan?.id).toBe(spanId);
- expect(dbSpan?.traceId).toBe(dbTrace[0]?.id);
- 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?.input).toEqual({ input: "value" });
- expect(dbSpan?.metadata).toEqual({ meta: "value" });
- expect(dbSpan?.version).toBe("2.0.0");
+ const dbTraces = await prisma.trace.findMany();
+ expect(dbTraces.length).toBe(0);
});
it("should create trace when creating span without existing trace without traceId", async () => {
@@ -274,14 +239,14 @@ describe("/api/public/spans API Endpoint", () => {
const dbTrace = await prisma.trace.findMany({
where: {
- id: dbSpan.traceId,
+ id: dbSpan.traceId!,
},
});
expect(dbTrace.length).toBe(1);
expect(dbTrace[0]?.name).toBe(generationName);
- expect(createSpan.status).toBe(200);
+ expect(createSpan.status).toBe(201);
expect(dbSpan?.id).toBe(spanId);
expect(dbSpan?.traceId).toBe(dbTrace[0]?.id);
@@ -307,13 +272,13 @@ describe("/api/public/spans API Endpoint", () => {
version: "2.0.0",
});
- expect(createSpan.status).toBe(200);
+ expect(createSpan.status).toBe(201);
const updatedSpan = await makeAPICall("PATCH", "/api/public/spans", {
spanId: spanId,
output: { key: "this is a great gpt output" },
});
- expect(updatedSpan.status).toBe(200);
+ expect(updatedSpan.status).toBe(201);
const dbSpan = await prisma.observation.findUnique({
where: {
@@ -331,7 +296,7 @@ describe("/api/public/spans API Endpoint", () => {
expect(dbSpan?.version).toBe("2.0.0");
});
- it("should fail update span if span does not exist", async () => {
+ it("should not upsert span if span does not exist", async () => {
const spanId = uuidv4();
const updatedSpan = await makeAPICall("PATCH", "/api/public/spans", {
@@ -339,5 +304,13 @@ describe("/api/public/spans API Endpoint", () => {
output: { key: "this is a great gpt output" },
});
expect(updatedSpan.status).toBe(404);
+
+ const dbSpan = await prisma.observation.findUnique({
+ where: {
+ id: spanId,
+ },
+ });
+
+ expect(dbSpan).toBeNull();
});
});
diff --git a/src/__tests__/traces.servertest.ts b/src/__tests__/traces.servertest.ts
index 92470a6002..ad551e1d82 100644
--- a/src/__tests__/traces.servertest.ts
+++ b/src/__tests__/traces.servertest.ts
@@ -7,7 +7,7 @@ describe("/api/public/traces API Endpoint", () => {
beforeEach(async () => await pruneDatabase());
afterEach(async () => await pruneDatabase());
- it("should create ", async () => {
+ it("should create", async () => {
await pruneDatabase();
await makeAPICall("POST", "/api/public/traces", {
@@ -33,12 +33,12 @@ describe("/api/public/traces API Endpoint", () => {
expect(dbTrace[0]?.projectId).toBe("7a88fb47-b4e2-43b8-a06c-a5ce950dc53a");
});
- it("should create trace with externalId", async () => {
+ it("should upsert second trace", async () => {
await pruneDatabase();
await makeAPICall("POST", "/api/public/traces", {
- externalId: "some-externalId",
- name: "trace-name-externalId",
+ id: "trace-id",
+ name: "trace-name",
userId: "user-1",
projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
metadata: { key: "value" },
@@ -46,17 +46,27 @@ describe("/api/public/traces API Endpoint", () => {
version: "2.0.0",
});
+ await makeAPICall("POST", "/api/public/traces", {
+ id: "trace-id",
+ name: "trace-name",
+ userId: "user-1",
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ metadata: { key: "value" },
+ release: "1.0.0",
+ version: "5.0.0",
+ });
+
const dbTrace = await prisma.trace.findMany({
where: {
- name: "trace-name-externalId",
+ name: "trace-name",
},
});
expect(dbTrace.length).toBeGreaterThan(0);
- expect(dbTrace[0]?.name).toBe("trace-name-externalId");
- expect(dbTrace[0]?.externalId).toBe("some-externalId");
+ expect(dbTrace[0]?.name).toBe("trace-name");
expect(dbTrace[0]?.release).toBe("1.0.0");
- expect(dbTrace[0]?.version).toBe("2.0.0");
+ expect(dbTrace[0]?.externalId).toBeNull();
+ expect(dbTrace[0]?.version).toBe("5.0.0");
expect(dbTrace[0]?.projectId).toBe("7a88fb47-b4e2-43b8-a06c-a5ce950dc53a");
});
});
diff --git a/src/features/dashboard/components/UserChart.tsx b/src/features/dashboard/components/UserChart.tsx
index f12d5c124d..785d745c98 100644
--- a/src/features/dashboard/components/UserChart.tsx
+++ b/src/features/dashboard/components/UserChart.tsx
@@ -5,7 +5,7 @@ import { DashboardCard } from "@/src/features/dashboard/components/cards/Dashboa
import { compactNumberFormatter, usdFormatter } from "@/src/utils/numbers";
import { TabComponent } from "@/src/features/dashboard/components/TabsComponent";
import { BarList } from "@tremor/react";
-import { isNotUndefinedOrNull } from "@/src/utils/types";
+import { isUndefinedOrNull } from "@/src/utils/types";
import { TotalMetric } from "@/src/features/dashboard/components/TotalMetric";
import { ExpandListButton } from "@/src/features/dashboard/components/cards/ChevronButton";
import { useState } from "react";
@@ -84,7 +84,7 @@ export const UserChart = ({
value: item.totalTokenCost ? (item.totalTokenCost as number) : 0,
};
})
- .filter((i) => (isNotUndefinedOrNull(i.name) ? true : false))
+ .filter((i) => (isUndefinedOrNull(i.name) ? true : false))
: [];
const totalCost = user.data?.reduce(
diff --git a/src/features/public-api/server/apiAuth.ts b/src/features/public-api/server/apiAuth.ts
index a7ea07e8f0..2a1874fe30 100644
--- a/src/features/public-api/server/apiAuth.ts
+++ b/src/features/public-api/server/apiAuth.ts
@@ -7,7 +7,7 @@ import { type ApiAccessScope } from "@/src/features/public-api/server/types";
import { prisma } from "@/src/server/db";
import { instrumentAsync } from "@/src/utils/instrumentation";
-type AuthHeaderVerificationResult =
+export type AuthHeaderVerificationResult =
| {
validKey: true;
scope: ApiAccessScope;
@@ -101,7 +101,6 @@ export async function verifyAuthHeaderAndReturnScope(
error: error instanceof Error ? error.message : "Authorization error",
};
}
-
return {
validKey: false,
error: "Invalid authorization header",
diff --git a/src/pages/api/public/dataset-items.ts b/src/pages/api/public/dataset-items.ts
index 1a8294fbfe..723154f801 100644
--- a/src/pages/api/public/dataset-items.ts
+++ b/src/pages/api/public/dataset-items.ts
@@ -23,7 +23,6 @@ export default async function handler(
);
if (!authCheck.validKey)
return res.status(401).json({
- success: false,
message: authCheck.error,
});
// END CHECK AUTH
@@ -43,7 +42,6 @@ export default async function handler(
// CHECK ACCESS SCOPE
if (authCheck.scope.accessLevel !== "all")
return res.status(403).json({
- success: false,
message: "Access denied",
});
// END CHECK ACCESS SCOPE
@@ -57,7 +55,6 @@ export default async function handler(
});
if (!dataset) {
return res.status(404).json({
- success: false,
message: "Dataset not found",
});
}
@@ -77,7 +74,6 @@ export default async function handler(
const errorMessage =
error instanceof Error ? error.message : "An unknown error occurred";
res.status(400).json({
- success: false,
message: "Invalid request data",
error: errorMessage,
});
diff --git a/src/pages/api/public/dataset-run-items.ts b/src/pages/api/public/dataset-run-items.ts
index c6ec9f62fd..6f6892f69e 100644
--- a/src/pages/api/public/dataset-run-items.ts
+++ b/src/pages/api/public/dataset-run-items.ts
@@ -22,14 +22,12 @@ export default async function handler(
);
if (!authCheck.validKey)
return res.status(401).json({
- success: false,
message: authCheck.error,
});
// END CHECK AUTH
if (authCheck.scope.accessLevel !== "all") {
return res.status(401).json({
- success: false,
message:
"Access denied - need to use basic auth with secret key to GET scores",
});
@@ -70,14 +68,12 @@ export default async function handler(
if (!item) {
console.error("item not found");
return res.status(404).json({
- success: false,
message: "Dataset item not found or not active",
});
}
if (!observation) {
console.error("observation not found");
return res.status(404).json({
- success: false,
message: "Observation not found",
});
}
@@ -110,7 +106,6 @@ export default async function handler(
const errorMessage =
error instanceof Error ? error.message : "An unknown error occurred";
res.status(400).json({
- success: false,
message: "Invalid request data",
error: errorMessage,
});
diff --git a/src/pages/api/public/datasets.ts b/src/pages/api/public/datasets.ts
index 4026738593..4464534053 100644
--- a/src/pages/api/public/datasets.ts
+++ b/src/pages/api/public/datasets.ts
@@ -20,7 +20,6 @@ export default async function handler(
);
if (!authCheck.validKey)
return res.status(401).json({
- success: false,
message: authCheck.error,
});
// END CHECK AUTH
@@ -39,7 +38,6 @@ export default async function handler(
// CHECK ACCESS SCOPE
if (authCheck.scope.accessLevel !== "all")
return res.status(403).json({
- success: false,
message: "Access denied",
});
// END CHECK ACCESS SCOPE
@@ -65,7 +63,6 @@ export default async function handler(
const errorMessage =
error instanceof Error ? error.message : "An unknown error occurred";
res.status(400).json({
- success: false,
message: "Invalid request data",
error: errorMessage,
});
diff --git a/src/pages/api/public/datasets/[name]/index.ts b/src/pages/api/public/datasets/[name]/index.ts
index 1ad82da5af..a36328911c 100644
--- a/src/pages/api/public/datasets/[name]/index.ts
+++ b/src/pages/api/public/datasets/[name]/index.ts
@@ -20,14 +20,12 @@ export default async function handler(
);
if (!authCheck.validKey)
return res.status(401).json({
- success: false,
message: authCheck.error,
});
// END CHECK AUTH
if (authCheck.scope.accessLevel !== "all") {
return res.status(401).json({
- success: false,
message:
"Access denied - need to use basic auth with secret key to GET scores",
});
@@ -67,7 +65,6 @@ export default async function handler(
if (!dataset) {
return res.status(404).json({
- success: false,
message: "Dataset not found or not active",
});
}
@@ -85,7 +82,6 @@ export default async function handler(
const errorMessage =
error instanceof Error ? error.message : "An unknown error occurred";
res.status(400).json({
- success: false,
message: "Invalid request data",
error: errorMessage,
});
diff --git a/src/pages/api/public/datasets/[name]/runs/[runName].ts b/src/pages/api/public/datasets/[name]/runs/[runName].ts
index 337b38d468..1d5025d32b 100644
--- a/src/pages/api/public/datasets/[name]/runs/[runName].ts
+++ b/src/pages/api/public/datasets/[name]/runs/[runName].ts
@@ -21,14 +21,12 @@ export default async function handler(
);
if (!authCheck.validKey)
return res.status(401).json({
- success: false,
message: authCheck.error,
});
// END CHECK AUTH
if (authCheck.scope.accessLevel !== "all") {
return res.status(401).json({
- success: false,
message:
"Access denied - need to use basic auth with secret key to GET dataset runs",
});
@@ -69,13 +67,11 @@ export default async function handler(
authCheck.scope.projectId,
);
return res.status(500).json({
- success: false,
message: "Found more than one dataset run with that name",
});
}
if (!datasetRuns[0])
return res.status(404).json({
- success: false,
message: "Dataset run not found",
});
@@ -85,7 +81,6 @@ export default async function handler(
const errorMessage =
error instanceof Error ? error.message : "An unknown error occurred";
res.status(400).json({
- success: false,
message: "Invalid request data",
error: errorMessage,
});
diff --git a/src/pages/api/public/events.ts b/src/pages/api/public/events.ts
index 09d474b2e2..961808ffd0 100644
--- a/src/pages/api/public/events.ts
+++ b/src/pages/api/public/events.ts
@@ -1,27 +1,17 @@
-import { prisma } from "@/src/server/db";
-import { ObservationLevel, ObservationType } from "@prisma/client";
import { type NextApiRequest, type NextApiResponse } from "next";
-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 { jsonSchema } from "@/src/utils/zod";
-import { persistEventMiddleware } from "@/src/pages/api/public/event-service";
-
-const ObservationSchema = z.object({
- id: z.string().nullish(),
- traceId: z.string().nullish(),
- traceIdType: z.enum(["LANGFUSE", "EXTERNAL"]).nullish(),
- name: z.string().nullish(),
- startTime: z.string().datetime({ offset: true }).nullish(),
- metadata: jsonSchema.nullish(),
- input: jsonSchema.nullish(),
- output: jsonSchema.nullish(),
- level: z.nativeEnum(ObservationLevel).nullish(),
- statusMessage: z.string().nullish(),
- parentObservationId: z.string().nullish(),
- version: z.string().nullish(),
-});
+import {
+ EventSchema,
+ eventTypes,
+ ingestionBatch,
+} from "./ingestion-api-schema";
+import {
+ handleBatch,
+ handleBatchResultLegacy,
+} from "@/src/pages/api/public/ingestion";
+import { type z } from "zod";
export default async function handler(
req: NextApiRequest,
@@ -39,7 +29,6 @@ export default async function handler(
);
if (!authCheck.validKey)
return res.status(401).json({
- success: false,
message: authCheck.error,
});
// END CHECK AUTH
@@ -52,93 +41,31 @@ export default async function handler(
);
try {
- const obj = ObservationSchema.parse(req.body);
- const {
- id,
- name,
- startTime,
- metadata,
- input,
- output,
- parentObservationId,
- level,
- statusMessage,
- version,
- } = obj;
-
- await persistEventMiddleware(prisma, authCheck.scope.projectId, req);
+ const convertToObservation = (generation: z.infer<typeof EventSchema>) => {
+ return {
+ ...generation,
+ type: "EVENT",
+ };
+ };
- 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,
- },
- },
- create: {
- projectId: authCheck.scope.projectId,
- externalId: obj.traceId,
- },
- update: {},
- })
- ).id
- : obj.traceId;
-
- 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,
- metadata: metadata ?? undefined,
- input: input ?? undefined,
- output: output ?? undefined,
- level: level ?? undefined,
- statusMessage: statusMessage ?? undefined,
- parentObservationId: parentObservationId ?? undefined,
- version: version ?? undefined,
- },
- });
+ const event = {
+ id: uuidv4(),
+ type: eventTypes.OBSERVATION_CREATE,
+ timestamp: new Date().toISOString(),
+ body: convertToObservation(EventSchema.parse(req.body)),
+ };
- res.status(200).json(newObservation);
+ const result = await handleBatch(
+ ingestionBatch.parse([event]),
+ req,
+ authCheck,
+ );
+ handleBatchResultLegacy(result.errors, result.results, res);
} catch (error: unknown) {
console.error(error);
const errorMessage =
error instanceof Error ? error.message : "An unknown error occurred";
res.status(400).json({
- success: false,
message: "Invalid request data",
error: errorMessage,
});
diff --git a/src/pages/api/public/generations.ts b/src/pages/api/public/generations.ts
index 531871ac77..9079172417 100644
--- a/src/pages/api/public/generations.ts
+++ b/src/pages/api/public/generations.ts
@@ -1,78 +1,19 @@
-import { prisma } from "@/src/server/db";
-import {
- ObservationLevel,
- ObservationType,
- type PrismaClient,
-} from "@prisma/client";
import { type NextApiRequest, type NextApiResponse } from "next";
-import { z } from "zod";
import { cors, runMiddleware } from "@/src/features/public-api/server/cors";
import { verifyAuthHeaderAndReturnScope } from "@/src/features/public-api/server/apiAuth";
-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 { jsonSchema } from "@/src/utils/zod";
-import { persistEventMiddleware } from "@/src/pages/api/public/event-service";
-
-export const GenerationsCreateSchema = z.object({
- id: z.string().nullish(),
- traceId: z.string().nullish(),
- traceIdType: z.enum(["LANGFUSE", "EXTERNAL"]).nullish(),
- name: z.string().nullish(),
- startTime: z.string().datetime({ offset: true }).nullish(),
- endTime: z.string().datetime({ offset: true }).nullish(),
- completionStartTime: z.string().datetime({ offset: true }).nullish(),
- model: z.string().nullish(),
- modelParameters: z
- .record(
- z.string(),
- z.union([z.string(), z.number(), z.boolean()]).nullish(),
- )
- .nullish(),
- prompt: jsonSchema.nullish(),
- completion: jsonSchema.nullish(),
- usage: z
- .object({
- promptTokens: z.number().nullish(),
- completionTokens: z.number().nullish(),
- totalTokens: z.number().nullish(),
- })
- .nullish(),
- metadata: jsonSchema.nullish(),
- parentObservationId: z.string().nullish(),
- level: z.nativeEnum(ObservationLevel).nullish(),
- statusMessage: z.string().nullish(),
- version: z.string().nullish(),
-});
-
-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(),
- model: z.string().nullish(),
- modelParameters: z
- .record(
- z.string(),
- z.union([z.string(), z.number(), z.boolean()]).nullish(),
- )
- .nullish(),
- prompt: jsonSchema.nullish(),
- completion: jsonSchema.nullish(),
- usage: z
- .object({
- promptTokens: z.number().nullish(),
- completionTokens: z.number().nullish(),
- totalTokens: z.number().nullish(),
- })
- .nullish(),
- metadata: jsonSchema.nullish(),
- level: z.nativeEnum(ObservationLevel).nullish(),
- statusMessage: z.string().nullish(),
- version: z.string().nullish(),
-});
+import { ResourceNotFoundError } from "../../../utils/exceptions";
+import {
+ GenerationPatchSchema,
+ GenerationsCreateSchema,
+ eventTypes,
+ ingestionBatch,
+} from "./ingestion-api-schema";
+import {
+ handleBatch,
+ handleBatchResultLegacy,
+} from "@/src/pages/api/public/ingestion";
+import { type z } from "zod";
export default async function handler(
req: NextApiRequest,
@@ -86,7 +27,6 @@ export default async function handler(
);
if (!authCheck.validKey)
return res.status(401).json({
- success: false,
message: authCheck.error,
});
// END CHECK AUTH
@@ -99,192 +39,81 @@ 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,
- name,
- startTime,
- endTime,
- completionStartTime,
- model,
- modelParameters,
- prompt,
- completion,
- usage,
- metadata,
- parentObservationId,
- level,
- statusMessage,
- version,
- } = obj;
-
- 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,
- },
- },
- create: {
- projectId: authCheck.scope.projectId,
- externalId: obj.traceId,
- },
- update: {},
- })
- ).id
- : obj.traceId;
-
- const newPromptTokens =
- usage?.promptTokens ??
- (model && prompt
- ? tokenCount({
- model: model,
- text: prompt,
- })
- : undefined);
- const newCompletionTokens =
- usage?.completionTokens ??
- (model && completion
- ? tokenCount({
- model: model,
- text: completion,
- })
- : undefined);
- const newId = uuidv4();
-
- // Check before upsert as Prisma only upserts in DB transaction when using unique key in select
- // Including projectid would lead to race conditions and unique key errors
- const observationWithSameId = await prisma.observation.count({
- where: {
- id: id ?? newId,
- projectId: {
- not: authCheck.scope.projectId,
- },
- },
- });
- if (observationWithSameId > 0)
- throw new Error(
- "Observation with same id already exists in another project",
- );
-
- const newObservation = await prisma.observation.upsert({
- where: {
- id: id ?? newId,
- },
- create: {
- id: id ?? newId,
- traceId: traceId,
- 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 ?? undefined,
- promptTokens: newPromptTokens,
- completionTokens: newCompletionTokens,
- totalTokens:
- usage?.totalTokens ??
- (newPromptTokens ?? 0) + (newCompletionTokens ?? 0),
- level: level ?? undefined,
- statusMessage: statusMessage ?? undefined,
- parentObservationId: parentObservationId ?? undefined,
- version: version ?? undefined,
- projectId: 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 ?? undefined,
- promptTokens: newPromptTokens,
- completionTokens: newCompletionTokens,
- totalTokens:
- usage?.totalTokens ??
- (newPromptTokens ?? 0) + (newCompletionTokens ?? 0),
- level: level ?? undefined,
- statusMessage: statusMessage ?? undefined,
- parentObservationId: parentObservationId ?? undefined,
- version: version ?? undefined,
- },
- });
+ const convertToObservation = (
+ generation: z.infer<typeof GenerationsCreateSchema>,
+ ) => {
+ return {
+ ...generation,
+ type: "GENERATION",
+ input: generation.prompt,
+ output: generation.completion,
+ };
+ };
+
+ const event = {
+ id: uuidv4(),
+ type: eventTypes.OBSERVATION_CREATE,
+ timestamp: new Date().toISOString(),
+ body: convertToObservation(GenerationsCreateSchema.parse(req.body)),
+ };
+
+ const result = await handleBatch(
+ ingestionBatch.parse([event]),
+ req,
+ authCheck,
+ );
- res.status(200).json(newObservation);
+ handleBatchResultLegacy(result.errors, result.results, res);
} catch (error: unknown) {
console.error(error);
const errorMessage =
error instanceof Error ? error.message : "An unknown error occurred";
res.status(400).json({
- success: false,
message: "Invalid request data",
error: errorMessage,
});
}
} else if (req.method === "PATCH") {
- console.log(
- "trying to update observation for generation, project ",
- authCheck.scope.projectId,
- ", body:",
- JSON.stringify(req.body, null, 2),
- );
- await persistEventMiddleware(prisma, authCheck.scope.projectId, req);
try {
- const newObservation = await backOff(
- async () =>
- await patchGeneration(
- prisma,
- GenerationPatchSchema.parse(req.body),
- authCheck.scope.projectId,
- ),
- {
- numOfAttempts: 5,
- retry: (e: Error, attemptNumber: number) => {
- if (e instanceof RessourceNotFoundError) {
- console.log(
- `retrying generation patch, attempt ${attemptNumber}`,
- );
- return true;
- }
- return false;
- },
- },
+ console.log(
+ "trying to update observation for generation, project ",
+ authCheck.scope.projectId,
+ ", body:",
+ JSON.stringify(req.body, null, 2),
+ );
+
+ const convertToObservation = (
+ generation: z.infer<typeof GenerationPatchSchema>,
+ ) => {
+ return {
+ ...generation,
+ id: generation.generationId,
+ type: "GENERATION",
+ input: generation.prompt,
+ output: generation.completion,
+ };
+ };
+
+ const event = {
+ id: uuidv4(),
+ type: eventTypes.OBSERVAION_UPDATE,
+ timestamp: new Date().toISOString(),
+ body: convertToObservation(GenerationPatchSchema.parse(req.body)),
+ };
+
+ const result = await handleBatch(
+ ingestionBatch.parse([event]),
+ req,
+ authCheck,
);
- res.status(200).json(newObservation);
+
+ handleBatchResultLegacy(result.errors, result.results, res);
} catch (error: unknown) {
console.error(error);
- if (error instanceof RessourceNotFoundError) {
+ if (error instanceof ResourceNotFoundError) {
return res.status(404).json({
- success: false,
message: "Observation not found",
});
}
@@ -292,7 +121,6 @@ export default async function handler(
const errorMessage =
error instanceof Error ? error.message : "An unknown error occurred";
res.status(400).json({
- success: false,
message: "Invalid request data",
error: errorMessage,
});
@@ -301,123 +129,3 @@ export default async function handler(
return res.status(405).json({ message: "Method not allowed" });
}
}
-
-const patchGeneration = async (
- prisma: PrismaClient,
- generationPatch: z.infer<typeof GenerationPatchSchema>,
- authenticatedProjectId: string,
-) => {
- const {
- generationId,
- traceId,
- endTime,
- completionStartTime,
- prompt,
- completion,
- usage,
- model,
- ...otherFields
- } = generationPatch;
-
- const existingObservation = await prisma.observation.findUnique({
- where: {
- id: generationPatch.generationId,
- projectId: authenticatedProjectId,
- },
- select: {
- promptTokens: true,
- completionTokens: true,
- model: true,
- },
- });
-
- if (!existingObservation) {
- console.log(`generation with id ${generationId} not found`);
- throw new RessourceNotFoundError("generation", generationId);
- }
-
- const mergedModel = model ?? existingObservation?.model ?? null;
-
- const newPromptTokens =
- usage?.promptTokens ??
- (mergedModel && prompt
- ? tokenCount({
- model: mergedModel,
- text: prompt,
- })
- : undefined);
-
- const newCompletionTokens =
- usage?.completionTokens ??
- (mergedModel && completion
- ? tokenCount({
- model: mergedModel,
- text: completion,
- })
- : undefined);
-
- const newTotalTokens =
- usage?.totalTokens ??
- (newPromptTokens ?? existingObservation?.promptTokens ?? 0) +
- (newCompletionTokens ?? existingObservation?.completionTokens ?? 0);
-
- // Check before upsert as Prisma only upserts in DB transaction when using unique key in select
- // Including projectid would lead to race conditions and unique key errors
- const observationWithSameId = await prisma.observation.count({
- where: {
- id: generationId,
- projectId: {
- not: authenticatedProjectId,
- },
- },
- });
- if (observationWithSameId > 0)
- throw new Error(
- "Observation with same id already exists in another project",
- );
-
- return await prisma.observation.upsert({
- where: {
- id: generationId,
- },
- create: {
- id: generationId,
- traceId: traceId ?? undefined,
- type: ObservationType.GENERATION,
- endTime: endTime ? new Date(endTime) : undefined,
- completionStartTime: completionStartTime
- ? new Date(completionStartTime)
- : undefined,
- input: prompt ?? undefined,
- output: completion ?? undefined,
- promptTokens: newPromptTokens,
- completionTokens: newCompletionTokens,
- totalTokens: newTotalTokens,
- model: model ?? undefined,
- ...Object.fromEntries(
- Object.entries(otherFields).filter(
- ([_, v]) => v !== null && v !== undefined,
- ),
- ),
- projectId: authenticatedProjectId,
- },
- update: {
- endTime: endTime ? new Date(endTime) : undefined,
- completionStartTime: completionStartTime
- ? new Date(completionStartTime)
- : undefined,
- input: prompt ?? undefined,
- output: 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,
- ),
- ),
- },
- });
-};
diff --git a/src/pages/api/public/ingestion-api-schema.ts b/src/pages/api/public/ingestion-api-schema.ts
new file mode 100644
index 0000000000..54f5794741
--- /dev/null
+++ b/src/pages/api/public/ingestion-api-schema.ts
@@ -0,0 +1,189 @@
+import { ObservationLevel } from "@prisma/client";
+import { jsonSchema } from "@/src/utils/zod";
+import { z } from "zod";
+
+export const TraceSchema = z.object({
+ id: z.string().nullish(),
+ name: z.string().nullish(),
+ externalId: z.string().nullish(),
+ userId: z.string().nullish(),
+ metadata: jsonSchema.nullish(),
+ release: z.string().nullish(),
+ version: z.string().nullish(),
+});
+export const SpanPostSchema = z.object({
+ id: z.string().nullish(),
+ traceId: z.string().nullish(),
+ name: z.string().nullish(),
+ startTime: z.string().datetime({ offset: true }).nullish(),
+ endTime: z.string().datetime({ offset: true }).nullish(),
+ metadata: jsonSchema.nullish(),
+ input: jsonSchema.nullish(),
+ output: jsonSchema.nullish(),
+ parentObservationId: z.string().nullish(),
+ level: z.nativeEnum(ObservationLevel).nullish(),
+ statusMessage: z.string().nullish(),
+ version: z.string().nullish(),
+});
+
+export const SpanPatchSchema = z.object({
+ spanId: z.string(),
+ traceId: z.string().nullish(),
+ name: z.string().nullish(),
+ endTime: z.string().datetime({ offset: true }).nullish(),
+ metadata: jsonSchema.nullish(),
+ input: jsonSchema.nullish(),
+ output: jsonSchema.nullish(),
+ level: z.nativeEnum(ObservationLevel).nullish(),
+ statusMessage: z.string().nullish(),
+ version: z.string().nullish(),
+});
+export const GenerationsCreateSchema = z.object({
+ id: z.string().nullish(),
+ traceId: z.string().nullish(),
+ name: z.string().nullish(),
+ startTime: z.string().datetime({ offset: true }).nullish(),
+ endTime: z.string().datetime({ offset: true }).nullish(),
+ completionStartTime: z.string().datetime({ offset: true }).nullish(),
+ model: z.string().nullish(),
+ modelParameters: z
+ .record(
+ z.string(),
+ z.union([z.string(), z.number(), z.boolean()]).nullish(),
+ )
+ .nullish(),
+ prompt: jsonSchema.nullish(),
+ completion: jsonSchema.nullish(),
+ usage: z
+ .object({
+ promptTokens: z.number().nullish(),
+ completionTokens: z.number().nullish(),
+ totalTokens: z.number().nullish(),
+ })
+ .nullish(),
+ metadata: jsonSchema.nullish(),
+ parentObservationId: z.string().nullish(),
+ level: z.nativeEnum(ObservationLevel).nullish(),
+ statusMessage: z.string().nullish(),
+ version: z.string().nullish(),
+});
+
+export 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(),
+ model: z.string().nullish(),
+ modelParameters: z
+ .record(
+ z.string(),
+ z.union([z.string(), z.number(), z.boolean()]).nullish(),
+ )
+ .nullish(),
+ prompt: jsonSchema.nullish(),
+ completion: jsonSchema.nullish(),
+ usage: z
+ .object({
+ promptTokens: z.number().nullish(),
+ completionTokens: z.number().nullish(),
+ totalTokens: z.number().nullish(),
+ })
+ .nullish(),
+ metadata: jsonSchema.nullish(),
+ level: z.nativeEnum(ObservationLevel).nullish(),
+ statusMessage: z.string().nullish(),
+ version: z.string().nullish(),
+});
+export const EventSchema = z.object({
+ id: z.string().nullish(),
+ traceId: z.string().nullish(),
+ name: z.string().nullish(),
+ startTime: z.string().datetime({ offset: true }).nullish(),
+ metadata: jsonSchema.nullish(),
+ input: jsonSchema.nullish(),
+ output: jsonSchema.nullish(),
+ level: z.nativeEnum(ObservationLevel).nullish(),
+ statusMessage: z.string().nullish(),
+ parentObservationId: z.string().nullish(),
+ version: z.string().nullish(),
+});
+
+export const ObservationSchema = z.object({
+ id: z.string().nullish(),
+ traceId: z.string().nullish(),
+ type: z.enum(["GENERATION", "SPAN", "EVENT"]),
+ name: z.string().nullish(),
+ startTime: z.string().datetime({ offset: true }).nullish(),
+ endTime: z.string().datetime({ offset: true }).nullish(),
+ completionStartTime: z.string().datetime({ offset: true }).nullish(),
+ model: z.string().nullish(),
+ modelParameters: z
+ .record(
+ z.string(),
+ z.union([z.string(), z.number(), z.boolean()]).nullish(),
+ )
+ .nullish(),
+ input: jsonSchema.nullish(),
+ output: jsonSchema.nullish(),
+ usage: z
+ .object({
+ promptTokens: z.number().nullish(),
+ completionTokens: z.number().nullish(),
+ totalTokens: z.number().nullish(),
+ })
+ .nullish(),
+ metadata: jsonSchema.nullish(),
+ parentObservationId: z.string().nullish(),
+ level: z.nativeEnum(ObservationLevel).nullish(),
+ statusMessage: z.string().nullish(),
+ version: z.string().nullish(),
+});
+
+export const ScoreSchema = z.object({
+ id: z.string().nullish(),
+ name: z.string(),
+ value: z.number(),
+ traceId: z.string(),
+ observationId: z.string().nullish(),
+ comment: z.string().nullish(),
+});
+
+export const eventTypes = {
+ TRACE_CREATE: "trace-create",
+ OBSERVATION_CREATE: "observation-create",
+ OBSERVAION_UPDATE: "observation-update",
+ SCORE_CREATE: "score-create",
+} as const;
+const base = z.object({
+ id: z.string(),
+ timestamp: z.string().datetime({ offset: true }),
+});
+export const traceEvent = base.extend({
+ type: z.literal(eventTypes.TRACE_CREATE),
+ body: TraceSchema,
+});
+export const observationEvent = base.extend({
+ type: z.literal(eventTypes.OBSERVATION_CREATE),
+ body: ObservationSchema,
+});
+export const observationUpdateEvent = base.extend({
+ type: z.literal(eventTypes.OBSERVAION_UPDATE),
+ body: ObservationSchema,
+});
+export const scoreEvent = base.extend({
+ type: z.literal(eventTypes.SCORE_CREATE),
+ body: ScoreSchema,
+});
+export const singleEventSchema = z.discriminatedUnion("type", [
+ traceEvent,
+ observationEvent,
+ observationUpdateEvent,
+ scoreEvent,
+]);
+
+export const ingestionBatch = z.array(singleEventSchema);
+
+export const ingestionApiSchema = z.object({
+ batch: ingestionBatch,
+});
diff --git a/src/pages/api/public/ingestion.ts b/src/pages/api/public/ingestion.ts
new file mode 100644
index 0000000000..0c6f945216
--- /dev/null
+++ b/src/pages/api/public/ingestion.ts
@@ -0,0 +1,309 @@
+import {
+ type AuthHeaderVerificationResult,
+ verifyAuthHeaderAndReturnScope,
+} from "@/src/features/public-api/server/apiAuth";
+import { cors, runMiddleware } from "@/src/features/public-api/server/cors";
+import { prisma } from "@/src/server/db";
+import { type NextApiRequest, type NextApiResponse } from "next";
+import { z } from "zod";
+import {
+ type ingestionApiSchema,
+ eventTypes,
+ singleEventSchema,
+} from "./ingestion-api-schema";
+import { type ApiAccessScope } from "@/src/features/public-api/server/types";
+import { persistEventMiddleware } from "@/src/server/api/services/event-service";
+import { backOff } from "exponential-backoff";
+import { ResourceNotFoundError } from "@/src/utils/exceptions";
+import { type EventProcessor } from "../../../server/api/services/EventProcessor";
+import { ObservationProcessor } from "../../../server/api/services/EventProcessor";
+import { TraceProcessor } from "../../../server/api/services/EventProcessor";
+import { ScoreProcessor } from "../../../server/api/services/EventProcessor";
+import { isNotNullOrUndefined } from "@/src/utils/types";
+
+export default async function handler(
+ req: NextApiRequest,
+ res: NextApiResponse,
+) {
+ try {
+ await runMiddleware(req, res, cors);
+
+ if (req.method !== "POST") {
+ return res.status(405).json({ message: "Method not allowed" });
+ }
+
+ // CHECK AUTH FOR ALL EVENTS
+ const authCheck = await verifyAuthHeaderAndReturnScope(
+ req.headers.authorization,
+ );
+
+ if (!authCheck.validKey)
+ return res.status(401).json({
+ message: authCheck.error,
+ });
+
+ if (authCheck.scope.accessLevel !== "all")
+ return res.status(403).json({
+ message: "Access denied",
+ });
+
+ const batchType = z.object({ batch: z.array(z.unknown()) });
+ const parsedSchema = batchType.safeParse(req.body);
+
+ if (!parsedSchema.success) {
+ console.log("Invalid request data", parsedSchema.error);
+ return res.status(400).json({
+ message: "Invalid request data",
+ errors: parsedSchema.error.issues.map((issue) => issue.message),
+ });
+ }
+
+ const errors: { id: string; error: unknown }[] = [];
+
+ const batch: (z.infer<typeof singleEventSchema> | undefined)[] =
+ parsedSchema.data.batch.map((event) => {
+ const parsed = singleEventSchema.safeParse(event);
+ if (!parsed.success) {
+ errors.push({
+ id:
+ typeof event === "object" && event && "id" in event
+ ? typeof event.id === "string"
+ ? event.id
+ : "unknown"
+ : "unknown",
+ error: new BadRequestError(parsed.error.message),
+ });
+ return undefined;
+ } else {
+ return parsed.data;
+ }
+ });
+ const filteredBatch: z.infer<typeof singleEventSchema>[] =
+ batch.filter(isNotNullOrUndefined);
+
+ const sortedBatch = sortBatch(filteredBatch);
+ const result = await handleBatch(sortedBatch, req, authCheck);
+
+ handleBatchResult([...errors, ...result.errors], result.results, res);
+ } catch (error: unknown) {
+ console.error(error);
+ const errorMessage =
+ error instanceof Error ? error.message : "An unknown error occurred";
+ res.status(400).json({
+ message: "Invalid request data",
+ errors: [errorMessage],
+ });
+ }
+}
+
+const sortBatch = (batch: Array<z.infer<typeof singleEventSchema>>) => {
+ // keep the order of events as they are. Order events in a way that types containing update come last
+ return batch.sort((a, b) => {
+ if (a.type === eventTypes.OBSERVAION_UPDATE) {
+ return 1;
+ }
+ if (b.type === eventTypes.OBSERVAION_UPDATE) {
+ return -1;
+ }
+ return 0;
+ });
+};
+
+export const handleBatch = async (
+ events: z.infer<typeof ingestionApiSchema>["batch"],
+ req: NextApiRequest,
+ authCheck: AuthHeaderVerificationResult,
+) => {
+ console.log("handling ingestion event", JSON.stringify(events, null, 2));
+
+ if (!authCheck.validKey) throw new AuthenticationError(authCheck.error);
+
+ const results = []; // Array to store the results
+ const errors = []; // Array to store the errors
+ for (const singleEvent of events) {
+ try {
+ const result = await retry(async () => {
+ return await handleSingleEvent(singleEvent, req, authCheck.scope);
+ });
+ results.push({ result: result, id: singleEvent.id }); // Push each result into the array
+ } catch (error) {
+ // Handle or log the error if `handleSingleEvent` fails
+ console.error("Error handling event:", error);
+ // Decide how to handle the error: rethrow, continue, or push an error object to results
+ // For example, push an error object:
+ errors.push({ error: error, id: singleEvent.id });
+ }
+ }
+
+ return { results, errors };
+};
+
+async function retry<T>(request: () => Promise<T>): Promise<T> {
+ return await backOff(request, {
+ numOfAttempts: 2,
+ retry: (e: Error, attemptNumber: number) => {
+ if (e instanceof AuthenticationError) {
+ console.log("not retrying auth error");
+ return false;
+ }
+ console.log(`retrying processing events ${attemptNumber}`);
+ return true;
+ },
+ });
+}
+export const getBadRequestError = (errors: Array<unknown>): BadRequestError[] =>
+ errors.filter(
+ (error): error is BadRequestError => error instanceof BadRequestError,
+ );
+
+export const getResourceNotFoundError = (
+ errors: Array<unknown>,
+): ResourceNotFoundError[] =>
+ errors.filter(
+ (error): error is ResourceNotFoundError =>
+ error instanceof ResourceNotFoundError,
+ );
+
+export const hasBadRequestError = (errors: Array<unknown>) =>
+ errors.some((error) => error instanceof BadRequestError);
+
+const handleSingleEvent = async (
+ event: z.infer<typeof singleEventSchema>,
+ req: NextApiRequest,
+ apiScope: ApiAccessScope,
+) => {
+ console.log(
+ `handling single event ${event.id}`,
+ JSON.stringify(event, null, 2),
+ );
+
+ const { type } = event;
+
+ await persistEventMiddleware(prisma, apiScope.projectId, req, event);
+
+ let processor: EventProcessor;
+ switch (type) {
+ case eventTypes.TRACE_CREATE:
+ processor = new TraceProcessor(event);
+ break;
+ case eventTypes.OBSERVATION_CREATE:
+ case eventTypes.OBSERVAION_UPDATE:
+ processor = new ObservationProcessor(event);
+ break;
+ case eventTypes.SCORE_CREATE: {
+ processor = new ScoreProcessor(event);
+ break;
+ }
+ }
+
+ return await processor.process(apiScope);
+};
+
+class BadRequestError extends Error {
+ constructor(msg: string) {
+ super(msg);
+
+ // Set the prototype explicitly.
+ Object.setPrototypeOf(this, BadRequestError.prototype);
+ }
+}
+
+export class AuthenticationError extends Error {
+ constructor(msg: string) {
+ super(msg);
+
+ // Set the prototype explicitly.
+ Object.setPrototypeOf(this, AuthenticationError.prototype);
+ }
+}
+
+export const handleBatchResult = (
+ errors: Array<{ id: string; error: unknown }>,
+ results: Array<{ id: string; result: unknown }>,
+ res: NextApiResponse,
+) => {
+ const returnedErrors: {
+ id: string;
+ status: number;
+ message?: string;
+ error?: string;
+ }[] = [];
+
+ const successes: {
+ id: string;
+ status: number;
+ }[] = [];
+
+ errors.forEach((error) => {
+ if (error.error instanceof BadRequestError) {
+ returnedErrors.push({
+ id: error.id,
+ status: 400,
+ message: "Invalid request data",
+ error: error.error.message,
+ });
+ } else if (error.error instanceof ResourceNotFoundError) {
+ if (!errors.some((res) => res.id === error.id)) {
+ returnedErrors.push({
+ id: error.id,
+ status: 404,
+ message: "Resource not found",
+ error: error.error.message,
+ });
+ }
+ } else {
+ if (!errors.some((res) => res.id === error.id)) {
+ returnedErrors.push({
+ id: error.id,
+ status: 500,
+ message: "Error processing events",
+ error: "Internal Server Error",
+ });
+ }
+ }
+ });
+
+ results.forEach((result) => {
+ successes.push({
+ id: result.id,
+ status: 201,
+ });
+ });
+
+ return res.status(207).send({ errors: returnedErrors, successes });
+};
+
+export const handleBatchResultLegacy = (
+ errors: Array<{ id: string; error: unknown }>,
+ results: Array<{ id: string; result: unknown }>,
+ res: NextApiResponse,
+) => {
+ const unknownErrors = errors.map((error) => error.error);
+
+ const badRequestErrors = getBadRequestError(unknownErrors);
+ if (badRequestErrors.length > 0) {
+ console.log("Bad request errors", badRequestErrors);
+ return res.status(400).json({
+ message: "Invalid request data",
+ errors: badRequestErrors.map((error) => error.message),
+ });
+ }
+
+ const ResourceNotFoundError = getResourceNotFoundError(unknownErrors);
+ if (ResourceNotFoundError.length > 0) {
+ return res.status(404).json({
+ message: "Resource not found",
+ errors: ResourceNotFoundError.map((error) => error.message),
+ });
+ }
+
+ if (errors.length > 0) {
+ console.log("Error processing events", unknownErrors);
+ return res.status(500).json({
+ message: "Error processing events",
+ errors: ["Internal Server Error"],
+ });
+ }
+
+ return res.status(201).send(results.length > 0 ? results[0] : {});
+};
diff --git a/src/pages/api/public/metrics/usage.ts b/src/pages/api/public/metrics/usage.ts
index fd34b1c770..2cbeb36f18 100644
--- a/src/pages/api/public/metrics/usage.ts
+++ b/src/pages/api/public/metrics/usage.ts
@@ -24,7 +24,6 @@ export default async function handler(
);
if (!authCheck.validKey)
return res.status(401).json({
- success: false,
message: authCheck.error,
});
// END CHECK AUTH
@@ -33,7 +32,6 @@ export default async function handler(
if (req.method === "GET") {
if (authCheck.scope.accessLevel !== "all") {
return res.status(401).json({
- success: false,
message:
"Access denied - need to use basic auth with secret key to GET scores",
});
@@ -193,7 +191,6 @@ export default async function handler(
});
} else {
return res.status(400).json({
- success: false,
message: "Invalid group_by value",
});
}
@@ -206,7 +203,6 @@ export default async function handler(
const errorMessage =
error instanceof Error ? error.message : "An unknown error occurred";
res.status(400).json({
- success: false,
message: "Invalid request data",
error: errorMessage,
});
diff --git a/src/pages/api/public/observations/[observationId].ts b/src/pages/api/public/observations/[observationId].ts
index 9eecd1e294..a0dd949b40 100644
--- a/src/pages/api/public/observations/[observationId].ts
+++ b/src/pages/api/public/observations/[observationId].ts
@@ -25,7 +25,6 @@ export default async function handler(
);
if (!authCheck.validKey)
return res.status(401).json({
- success: false,
message: authCheck.error,
});
// END CHECK AUTH
@@ -38,7 +37,6 @@ export default async function handler(
// CHECK ACCESS SCOPE
if (authCheck.scope.accessLevel !== "all") {
return res.status(401).json({
- success: false,
message:
"Access denied - need to use basic auth with secret key to GET traces",
});
@@ -53,7 +51,6 @@ export default async function handler(
});
if (!observation) {
return res.status(404).json({
- success: false,
message: "Observation not found within authorized project",
});
}
@@ -63,7 +60,6 @@ export default async function handler(
const errorMessage =
error instanceof Error ? error.message : "An unknown error occurred";
res.status(400).json({
- success: false,
message: "Invalid request data",
error: errorMessage,
});
diff --git a/src/pages/api/public/observations/index.ts b/src/pages/api/public/observations/index.ts
index 03c5cc76e4..d6a3b375f8 100644
--- a/src/pages/api/public/observations/index.ts
+++ b/src/pages/api/public/observations/index.ts
@@ -32,7 +32,6 @@ export default async function handler(
);
if (!authCheck.validKey)
return res.status(401).json({
- success: false,
message: authCheck.error,
});
// END CHECK AUTH
@@ -47,7 +46,6 @@ export default async function handler(
if (authCheck.scope.accessLevel !== "all") {
return res.status(401).json({
- success: false,
message:
"Access denied - need to use basic auth with secret key to GET generations",
});
@@ -75,7 +73,6 @@ export default async function handler(
const errorMessage =
error instanceof Error ? error.message : "An unknown error occurred";
res.status(400).json({
- success: false,
message: "Invalid request data",
error: errorMessage,
});
diff --git a/src/pages/api/public/scores.ts b/src/pages/api/public/scores.ts
index 2c4a9f311c..7b95576616 100644
--- a/src/pages/api/public/scores.ts
+++ b/src/pages/api/public/scores.ts
@@ -4,19 +4,17 @@ import { type NextApiRequest, type NextApiResponse } from "next";
import { z } from "zod";
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(),
- name: z.string(),
- value: z.number(),
- traceId: z.string(),
- traceIdType: z.enum(["LANGFUSE", "EXTERNAL"]).nullish(),
- observationId: z.string().nullish(),
- comment: z.string().nullish(),
-});
+import {
+ ScoreSchema,
+ eventTypes,
+ ingestionBatch,
+} from "@/src/pages/api/public/ingestion-api-schema";
+import { v4 } from "uuid";
+import {
+ handleBatch,
+ handleBatchResultLegacy,
+} from "@/src/pages/api/public/ingestion";
const ScoresGetSchema = z.object({
...paginationZod,
@@ -36,7 +34,6 @@ export default async function handler(
);
if (!authCheck.validKey)
return res.status(401).json({
- success: false,
message: authCheck.error,
});
// END CHECK AUTH
@@ -49,64 +46,26 @@ 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
- const traceId =
- obj.traceIdType === "EXTERNAL"
- ? (
- await prisma.trace.findUniqueOrThrow({
- where: {
- projectId_externalId: {
- projectId: authCheck.scope.projectId,
- externalId: obj.traceId,
- },
- },
- })
- ).id
- : obj.traceId;
-
- // CHECK ACCESS SCOPE
- const accessCheck = await checkApiAccessScope(
- authCheck.scope,
- [
- { type: "trace", id: traceId },
- ...(obj.observationId
- ? [{ type: "observation" as const, id: obj.observationId }]
- : []),
- ],
- "score",
- );
- if (!accessCheck)
- return res.status(403).json({
- success: false,
- message: "Access denied",
- });
- // END CHECK ACCESS SCOPE
- const data: Prisma.ScoreCreateInput = {
- id: obj.id ?? undefined,
- timestamp: new Date(),
- value: obj.value,
- name: obj.name,
- comment: obj.comment,
- trace: { connect: { id: traceId } },
- ...(obj.observationId && {
- observation: { connect: { id: obj.observationId } },
- }),
+ const event = {
+ id: v4(),
+ type: eventTypes.SCORE_CREATE,
+ timestamp: new Date().toISOString(),
+ body: ScoreSchema.parse(req.body),
};
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
- const newScore = await prisma.score.create({ data });
+ const result = await handleBatch(
+ ingestionBatch.parse([event]),
+ req,
+ authCheck,
+ );
- res.status(200).json(newScore);
+ handleBatchResultLegacy(result.errors, result.results, res);
} catch (error: unknown) {
console.error(error);
const errorMessage =
error instanceof Error ? error.message : "An unknown error occurred";
res.status(400).json({
- success: false,
message: "Invalid request data",
error: errorMessage,
});
@@ -115,7 +74,6 @@ export default async function handler(
try {
if (authCheck.scope.accessLevel !== "all") {
return res.status(401).json({
- success: false,
message:
"Access denied - need to use basic auth with secret key to GET scores",
});
@@ -173,7 +131,6 @@ export default async function handler(
const errorMessage =
error instanceof Error ? error.message : "An unknown error occurred";
res.status(400).json({
- success: false,
message: "Invalid request data",
error: errorMessage,
});
diff --git a/src/pages/api/public/spans.ts b/src/pages/api/public/spans.ts
index 1f39c84ef0..13605b541e 100644
--- a/src/pages/api/public/spans.ts
+++ b/src/pages/api/public/spans.ts
@@ -1,47 +1,19 @@
-import { prisma } from "@/src/server/db";
-import {
- ObservationLevel,
- ObservationType,
- type PrismaClient,
-} from "@prisma/client";
import { type NextApiRequest, type NextApiResponse } from "next";
-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 { backOff } from "exponential-backoff";
-import { RessourceNotFoundError } from "../../../utils/exceptions";
-import { jsonSchema } from "@/src/utils/zod";
-import { persistEventMiddleware } from "@/src/pages/api/public/event-service";
-
-const SpanPostSchema = z.object({
- id: z.string().nullish(),
- traceId: z.string().nullish(),
- traceIdType: z.enum(["LANGFUSE", "EXTERNAL"]).nullish(),
- name: z.string().nullish(),
- startTime: z.string().datetime({ offset: true }).nullish(),
- endTime: z.string().datetime({ offset: true }).nullish(),
- metadata: jsonSchema.nullish(),
- input: jsonSchema.nullish(),
- output: jsonSchema.nullish(),
- parentObservationId: z.string().nullish(),
- level: z.nativeEnum(ObservationLevel).nullish(),
- statusMessage: z.string().nullish(),
- version: z.string().nullish(),
-});
-
-const SpanPatchSchema = z.object({
- spanId: z.string(),
- traceId: z.string().nullish(),
- name: z.string().nullish(),
- endTime: z.string().datetime({ offset: true }).nullish(),
- metadata: jsonSchema.nullish(),
- input: jsonSchema.nullish(),
- output: jsonSchema.nullish(),
- level: z.nativeEnum(ObservationLevel).nullish(),
- statusMessage: z.string().nullish(),
- version: z.string().nullish(),
-});
+import { v4 } from "uuid";
+import { ResourceNotFoundError } from "../../../utils/exceptions";
+import {
+ SpanPatchSchema,
+ SpanPostSchema,
+ eventTypes,
+ ingestionBatch,
+} from "./ingestion-api-schema";
+import {
+ handleBatch,
+ handleBatchResultLegacy,
+} from "@/src/pages/api/public/ingestion";
+import { type z } from "zod";
export default async function handler(
req: NextApiRequest,
@@ -55,7 +27,6 @@ export default async function handler(
);
if (!authCheck.validKey)
return res.status(401).json({
- success: false,
message: authCheck.error,
});
// END CHECK AUTH
@@ -69,112 +40,31 @@ export default async function handler(
JSON.stringify(req.body, null, 2),
);
- await persistEventMiddleware(prisma, authCheck.scope.projectId, req);
-
- const obj = SpanPostSchema.parse(req.body);
- const {
- id,
- name,
- startTime,
- endTime,
- metadata,
- input,
- output,
- parentObservationId,
- level,
- statusMessage,
- version,
- } = obj;
-
- 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,
- },
- },
- create: {
- projectId: authCheck.scope.projectId,
- externalId: obj.traceId,
- },
- update: {},
- })
- ).id
- : obj.traceId;
-
- const newId = uuidv4();
-
- // Check before upsert as Prisma only upserts in DB transaction when using unique key in select
- // Including projectid would lead to race conditions and unique key errors
- const observationWithSameId = await prisma.observation.count({
- where: {
- id: id ?? newId,
- projectId: {
- not: authCheck.scope.projectId,
- },
- },
- });
- if (observationWithSameId > 0)
- throw new Error(
- "Observation with same id already exists in another project",
- );
-
- const newObservation = await prisma.observation.upsert({
- where: {
- id: id ?? newId,
- },
- 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,
- projectId: authCheck.scope.projectId,
- },
- update: {
- 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,
- },
- });
-
- res.status(200).json(newObservation);
+ const convertToObservation = (span: z.infer<typeof SpanPostSchema>) => {
+ return {
+ ...span,
+ type: "SPAN",
+ };
+ };
+
+ const event = {
+ id: v4(),
+ type: eventTypes.OBSERVATION_CREATE,
+ timestamp: new Date().toISOString(),
+ body: convertToObservation(SpanPostSchema.parse(req.body)),
+ };
+
+ const result = await handleBatch(
+ ingestionBatch.parse([event]),
+ req,
+ authCheck,
+ );
+ handleBatchResultLegacy(result.errors, result.results, res);
} catch (error: unknown) {
const errorMessage =
error instanceof Error ? error.message : "An unknown error occurred";
console.error(error, req.body);
res.status(400).json({
- success: false,
message: "Invalid request data",
error: errorMessage,
});
@@ -187,42 +77,40 @@ 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(
- prisma,
- SpanPatchSchema.parse(req.body),
- authCheck.scope.projectId,
- ),
- {
- numOfAttempts: 5,
- retry: (e: Error, attemptNumber: number) => {
- if (e instanceof RessourceNotFoundError) {
- console.log(
- `retrying generation patch, attempt ${attemptNumber}`,
- );
- return true;
- }
- return false;
- },
- },
+
+ const convertToObservation = (span: z.infer<typeof SpanPatchSchema>) => {
+ return {
+ ...span,
+ id: span.spanId,
+ type: "SPAN",
+ };
+ };
+
+ const event = {
+ id: v4(),
+ type: eventTypes.OBSERVAION_UPDATE,
+ timestamp: new Date().toISOString(),
+ body: convertToObservation(SpanPatchSchema.parse(req.body)),
+ };
+
+ const result = await handleBatch(
+ ingestionBatch.parse([event]),
+ req,
+ authCheck,
);
- res.status(200).json(newObservation);
+ handleBatchResultLegacy(result.errors, result.results, res);
} catch (error: unknown) {
console.error(error);
- if (error instanceof RessourceNotFoundError) {
+ if (error instanceof ResourceNotFoundError) {
return res.status(404).json({
- success: false,
message: "Span not found",
});
}
const errorMessage =
error instanceof Error ? error.message : "An unknown error occurred";
res.status(400).json({
- success: false,
message: "Invalid request data",
error: errorMessage,
});
@@ -231,61 +119,3 @@ export default async function handler(
res.status(405).json({ message: "Method not allowed" });
}
}
-
-const patchSpan = async (
- prisma: PrismaClient,
- spanPatch: z.infer<typeof SpanPatchSchema>,
- authenticatedProjectId: string,
-) => {
- const { spanId, endTime, ...fields } = spanPatch;
-
- // Check before upsert as Prisma only upserts in DB transaction when using unique key in select
- // Including projectid would lead to race conditions and unique key errors
- const observationsWithSameId = await prisma.observation.count({
- where: {
- id: spanId,
- projectId: {
- not: authenticatedProjectId,
- },
- },
- });
-
- if (observationsWithSameId > 0)
- throw new Error(
- "Observation with same id already exists in another project",
- );
-
- const existingSpan = await prisma.observation.findUnique({
- where: { id: spanId, projectId: authenticatedProjectId },
- });
-
- if (!existingSpan) {
- console.log(`span with id ${spanId} not found`);
- throw new RessourceNotFoundError("span", spanId);
- }
-
- return await prisma.observation.upsert({
- where: {
- id: spanId,
- },
- create: {
- id: spanId,
- type: ObservationType.SPAN,
- endTime: endTime ? new Date(endTime) : undefined,
- ...Object.fromEntries(
- Object.entries(fields).filter(
- ([_, v]) => v !== null && v !== undefined,
- ),
- ),
- projectId: authenticatedProjectId,
- },
- update: {
- endTime: endTime ? new Date(endTime) : undefined,
- ...Object.fromEntries(
- Object.entries(fields).filter(
- ([_, v]) => v !== null && v !== undefined,
- ),
- ),
- },
- });
-};
diff --git a/src/pages/api/public/traces.ts b/src/pages/api/public/traces.ts
index 65cc37e707..f7a359fbf2 100644
--- a/src/pages/api/public/traces.ts
+++ b/src/pages/api/public/traces.ts
@@ -4,19 +4,16 @@ import { cors, runMiddleware } from "@/src/features/public-api/server/cors";
import { prisma } from "@/src/server/db";
import { verifyAuthHeaderAndReturnScope } from "@/src/features/public-api/server/apiAuth";
import { Prisma, type Trace } from "@prisma/client";
-import { v4 as uuidv4 } from "uuid";
-import { jsonSchema, paginationZod } from "@/src/utils/zod";
-import { persistEventMiddleware } from "@/src/pages/api/public/event-service";
-
-const CreateTraceSchema = z.object({
- id: z.string().nullish(),
- name: z.string().nullish(),
- externalId: z.string().nullish(),
- userId: z.string().nullish(),
- metadata: jsonSchema.nullish(),
- release: z.string().nullish(),
- version: z.string().nullish(),
-});
+import { paginationZod } from "@/src/utils/zod";
+import {
+ handleBatch,
+ handleBatchResultLegacy,
+} from "@/src/pages/api/public/ingestion";
+import {
+ TraceSchema,
+ eventTypes,
+} from "@/src/pages/api/public/ingestion-api-schema";
+import { v4 } from "uuid";
const GetTracesSchema = z.object({
...paginationZod,
@@ -36,7 +33,6 @@ export default async function handler(
);
if (!authCheck.validKey)
return res.status(401).json({
- success: false,
message: authCheck.error,
});
// END CHECK AUTH
@@ -49,84 +45,25 @@ 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);
- // CHECK ACCESS SCOPE
if (authCheck.scope.accessLevel !== "all")
return res.status(403).json({
- success: false,
message: "Access denied",
});
- // END CHECK ACCESS SCOPE
- if (id && externalId)
- return res.status(400).json({
- success: false,
- message: "Cannot create trace with both id and externalId",
- });
+ const body = TraceSchema.parse(req.body);
+ const event = {
+ id: v4(),
+ type: eventTypes.TRACE_CREATE,
+ timestamp: new Date().toISOString(),
+ body: body,
+ };
- if (externalId) {
- // For traces created with external ids, allow upserts
- const newTrace = await prisma.trace.upsert({
- where: {
- projectId_externalId: {
- externalId: externalId,
- projectId: authCheck.scope.projectId,
- },
- },
- create: {
- timestamp: new Date(),
- projectId: authCheck.scope.projectId,
- externalId: externalId,
- name: name ?? undefined,
- userId: userId ?? undefined,
- metadata: metadata ?? undefined,
- 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);
- } else {
- 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,
- metadata: metadata ?? undefined,
- 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);
- }
+ const result = await handleBatch([event], req, authCheck);
+ handleBatchResultLegacy(result.errors, result.results, res);
} else if (req.method === "GET") {
if (authCheck.scope.accessLevel !== "all") {
return res.status(401).json({
- success: false,
message:
"Access denied - need to use basic auth with secret key to GET scores",
});
@@ -192,7 +129,6 @@ export default async function handler(
const errorMessage =
error instanceof Error ? error.message : "An unknown error occurred";
res.status(400).json({
- success: false,
message: "Invalid request data",
error: errorMessage,
});
diff --git a/src/pages/api/public/traces/[traceId].ts b/src/pages/api/public/traces/[traceId].ts
index 87703710a1..f9c5428eec 100644
--- a/src/pages/api/public/traces/[traceId].ts
+++ b/src/pages/api/public/traces/[traceId].ts
@@ -25,7 +25,6 @@ export default async function handler(
);
if (!authCheck.validKey)
return res.status(401).json({
- success: false,
message: authCheck.error,
});
// END CHECK AUTH
@@ -38,7 +37,6 @@ export default async function handler(
// CHECK ACCESS SCOPE
if (authCheck.scope.accessLevel !== "all") {
return res.status(401).json({
- success: false,
message:
"Access denied - need to use basic auth with secret key to GET traces",
});
@@ -65,7 +63,6 @@ export default async function handler(
if (!trace) {
return res.status(404).json({
- success: false,
message: "Trace not found within authorized project",
});
}
@@ -75,7 +72,6 @@ export default async function handler(
const errorMessage =
error instanceof Error ? error.message : "An unknown error occurred";
res.status(400).json({
- success: false,
message: "Invalid request data",
error: errorMessage,
});
diff --git a/src/pages/api/public/users.ts b/src/pages/api/public/users.ts
index 706a2e0b54..168fddbf41 100644
--- a/src/pages/api/public/users.ts
+++ b/src/pages/api/public/users.ts
@@ -21,7 +21,6 @@ export default async function handler(
);
if (!authCheck.validKey)
return res.status(401).json({
- success: false,
message: authCheck.error,
});
// END CHECK AUTH
@@ -30,7 +29,6 @@ export default async function handler(
if (req.method === "GET") {
if (authCheck.scope.accessLevel !== "all") {
return res.status(401).json({
- success: false,
message:
"Access denied - need to use basic auth with secret key to GET scores",
});
@@ -126,7 +124,6 @@ export default async function handler(
const errorMessage =
error instanceof Error ? error.message : "An unknown error occurred";
res.status(400).json({
- success: false,
message: "Invalid request data",
error: errorMessage,
});
diff --git a/src/server/api/services/EventProcessor.ts b/src/server/api/services/EventProcessor.ts
new file mode 100644
index 0000000000..b975ef9a96
--- /dev/null
+++ b/src/server/api/services/EventProcessor.ts
@@ -0,0 +1,309 @@
+import { tokenCount } from "@/src/features/ingest/lib/usage";
+import { checkApiAccessScope } from "@/src/features/public-api/server/apiScope";
+import { type ApiAccessScope } from "@/src/features/public-api/server/types";
+import { AuthenticationError } from "@/src/pages/api/public/ingestion";
+import {
+ type observationEvent,
+ eventTypes,
+ type traceEvent,
+ type scoreEvent,
+ type observationUpdateEvent,
+} from "@/src/pages/api/public/ingestion-api-schema";
+import { prisma } from "@/src/server/db";
+import { ResourceNotFoundError } from "@/src/utils/exceptions";
+import { mergeJson } from "@/src/utils/json";
+import {
+ type Trace,
+ type Observation,
+ type Score,
+ type Prisma,
+} from "@prisma/client";
+import { v4 } from "uuid";
+import { type z } from "zod";
+import { jsonSchema } from "@/src/utils/zod";
+
+export interface EventProcessor {
+ process(apiScope: ApiAccessScope): Promise<Trace | Observation | Score>;
+}
+export class ObservationProcessor implements EventProcessor {
+ event:
+ | z.infer<typeof observationEvent>
+ | z.infer<typeof observationUpdateEvent>;
+
+ constructor(
+ event:
+ | z.infer<typeof observationEvent>
+ | z.infer<typeof observationUpdateEvent>,
+ ) {
+ this.event = event;
+ }
+
+ async convertToObservation(apiScope: ApiAccessScope): Promise<{
+ id: string;
+ create: Prisma.ObservationCreateInput;
+ update: Prisma.ObservationUpdateInput;
+ }> {
+ const { body } = this.event;
+
+ const {
+ id,
+ traceId,
+ type,
+ name,
+ startTime,
+ endTime,
+ completionStartTime,
+ model,
+ modelParameters,
+ input,
+ output,
+ usage,
+ metadata,
+ parentObservationId,
+ level,
+ statusMessage,
+ version,
+ } = body;
+
+ const existingObservation = id
+ ? await prisma.observation.findUnique({
+ where: { id, projectId: apiScope.projectId },
+ })
+ : null;
+
+ if (
+ this.event.type === eventTypes.OBSERVAION_UPDATE &&
+ !existingObservation
+ ) {
+ throw new ResourceNotFoundError(this.event.id, "Observation not found");
+ }
+
+ const finalTraceId =
+ !traceId && !existingObservation
+ ? // Create trace if no traceid
+ (
+ await prisma.trace.create({
+ data: {
+ projectId: apiScope.projectId,
+ name: name,
+ },
+ })
+ ).id
+ : traceId;
+
+ const [newPromptTokens, newCompletionTokens] = this.calculateTokenCounts(
+ body,
+ existingObservation ?? undefined,
+ );
+
+ // merge metadata from existingObservation.metadata and metadata
+ const mergedMetadata = mergeJson(
+ existingObservation?.metadata
+ ? jsonSchema.parse(existingObservation.metadata)
+ : undefined,
+ metadata ?? undefined,
+ );
+
+ const observationId = id ?? v4();
+ return {
+ id: observationId,
+ create: {
+ id: observationId,
+ traceId: finalTraceId,
+ type: type,
+ name: name,
+ startTime: startTime ? new Date(startTime) : undefined,
+ endTime: endTime ? new Date(endTime) : undefined,
+ completionStartTime: completionStartTime
+ ? new Date(completionStartTime)
+ : undefined,
+ metadata: mergedMetadata ?? metadata ?? undefined,
+ model: model ?? undefined,
+ modelParameters: modelParameters ?? undefined,
+ input: input ?? undefined,
+ output: output ?? undefined,
+ promptTokens: newPromptTokens,
+ completionTokens: newCompletionTokens,
+ totalTokens:
+ usage?.totalTokens ??
+ (newPromptTokens ?? 0) + (newCompletionTokens ?? 0),
+ level: level ?? undefined,
+ statusMessage: statusMessage ?? undefined,
+ parentObservationId: parentObservationId ?? undefined,
+ version: version ?? undefined,
+ project: { connect: { id: apiScope.projectId } },
+ },
+ update: {
+ type: type,
+ name,
+ startTime: startTime ? new Date(startTime) : undefined,
+ endTime: endTime ? new Date(endTime) : undefined,
+ completionStartTime: completionStartTime
+ ? new Date(completionStartTime)
+ : undefined,
+ metadata: mergedMetadata ?? metadata ?? undefined,
+ model: model ?? undefined,
+ modelParameters: modelParameters ?? undefined,
+ input: input ?? undefined,
+ output: output ?? undefined,
+ promptTokens: newPromptTokens,
+ completionTokens: newCompletionTokens,
+ totalTokens:
+ usage?.totalTokens ??
+ (newPromptTokens ?? 0) + (newCompletionTokens ?? 0),
+ level: level ?? undefined,
+ statusMessage: statusMessage ?? undefined,
+ parentObservationId: parentObservationId ?? undefined,
+ version: version ?? undefined,
+ },
+ };
+ }
+
+ calculateTokenCounts(
+ body: z.infer<typeof observationEvent>["body"],
+ existingObservation?: Observation,
+ ) {
+ const mergedModel = body.model ?? existingObservation?.model;
+
+ const newPromptTokens =
+ body.usage?.promptTokens ??
+ ((body.input || existingObservation?.input) && mergedModel
+ ? tokenCount({
+ model: mergedModel,
+ text: body.input ?? existingObservation?.input,
+ })
+ : undefined);
+
+ const newCompletionTokens =
+ body.usage?.completionTokens ??
+ ((body.output || existingObservation?.output) && mergedModel
+ ? tokenCount({
+ model: mergedModel,
+ text: body.output ?? existingObservation?.output,
+ })
+ : undefined);
+ return [newPromptTokens, newCompletionTokens];
+ }
+
+ async process(
+ apiScope: ApiAccessScope,
+ ): Promise<Trace | Observation | Score> {
+ if (apiScope.accessLevel !== "all")
+ throw new AuthenticationError("Access denied for observation creation");
+
+ const obs = await this.convertToObservation(apiScope);
+
+ return await prisma.observation.upsert({
+ where: {
+ id_projectId: {
+ id: obs.id,
+ projectId: apiScope.projectId,
+ },
+ },
+ create: obs.create,
+ update: obs.update,
+ });
+ }
+}
+export class TraceProcessor implements EventProcessor {
+ event: z.infer<typeof traceEvent>;
+
+ constructor(event: z.infer<typeof traceEvent>) {
+ this.event = event;
+ }
+
+ async process(
+ apiScope: ApiAccessScope,
+ ): Promise<Trace | Observation | Score> {
+ const { body } = this.event;
+
+ if (apiScope.accessLevel !== "all")
+ throw new AuthenticationError("Access denied for trace creation");
+
+ const internalId = body.id ?? v4();
+
+ console.log(
+ "Trying to create trace, project ",
+ apiScope.projectId,
+ ", body:",
+ body,
+ );
+
+ const existingTrace = await prisma.trace.findUnique({
+ where: {
+ id: internalId,
+ },
+ });
+
+ const mergedMetadata = mergeJson(
+ existingTrace?.metadata
+ ? jsonSchema.parse(existingTrace.metadata)
+ : undefined,
+ body.metadata ?? undefined,
+ );
+
+ const upsertedTrace = await prisma.trace.upsert({
+ where: {
+ id: internalId,
+ projectId: apiScope.projectId,
+ },
+ create: {
+ id: internalId,
+ name: body.name ?? undefined,
+ userId: body.userId ?? undefined,
+ metadata: mergedMetadata ?? body.metadata ?? undefined,
+ release: body.release ?? undefined,
+ version: body.version ?? undefined,
+ project: { connect: { id: apiScope.projectId } },
+ },
+ update: {
+ name: body.name ?? undefined,
+ userId: body.userId ?? undefined,
+ metadata: mergedMetadata ?? body.metadata ?? undefined,
+ release: body.release ?? undefined,
+ version: body.version ?? undefined,
+ },
+ });
+ return upsertedTrace;
+ }
+}
+export class ScoreProcessor implements EventProcessor {
+ event: z.infer<typeof scoreEvent>;
+
+ constructor(event: z.infer<typeof scoreEvent>) {
+ this.event = event;
+ }
+
+ async process(
+ apiScope: ApiAccessScope,
+ ): Promise<Trace | Observation | Score> {
+ const { body } = this.event;
+
+ const accessCheck = await checkApiAccessScope(
+ apiScope,
+ [
+ { type: "trace", id: body.traceId },
+ ...(body.observationId
+ ? [{ type: "observation" as const, id: body.observationId }]
+ : []),
+ ],
+ "score",
+ );
+ if (!accessCheck)
+ throw new AuthenticationError("Access denied for score creation");
+
+ return await prisma.score.create({
+ data: {
+ id: body.id ?? v4(),
+ timestamp: new Date(),
+ value: body.value,
+ name: body.name,
+ comment: body.comment,
+ trace: { connect: { id: body.traceId } },
+ ...(body.observationId && {
+ observation: { connect: { id: body.observationId } },
+ }),
+ },
+ });
+ }
+}
diff --git a/src/pages/api/public/event-service.ts b/src/server/api/services/event-service.ts
similarity index 80%
rename from src/pages/api/public/event-service.ts
rename to src/server/api/services/event-service.ts
index b770bddfbd..817eaa1ff9 100644
--- a/src/pages/api/public/event-service.ts
+++ b/src/server/api/services/event-service.ts
@@ -1,9 +1,8 @@
-import { jsonSchema } from "@/src/utils/zod";
-import { type PrismaClient } from "@prisma/client";
+import { type Prisma, 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 relates each event to a project
// 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
@@ -12,9 +11,8 @@ export const persistEventMiddleware = async (
prisma: PrismaClient,
projectId: string,
req: NextApiRequest,
+ data: Prisma.JsonObject,
) => {
- const filteredEvent = jsonSchema.parse(req.body);
-
const langfuseHeadersObject = Object.fromEntries(
Object.entries(req.headers).filter(([key]) => key.startsWith("x-langfuse")),
);
@@ -24,7 +22,7 @@ export const persistEventMiddleware = async (
project: { connect: { id: projectId } },
url: req.url,
method: req.method,
- data: filteredEvent,
+ data: data,
headers: langfuseHeadersObject,
},
});
diff --git a/src/utils/exceptions.ts b/src/utils/exceptions.ts
index 0c59b43497..4d8f8541fa 100644
--- a/src/utils/exceptions.ts
+++ b/src/utils/exceptions.ts
@@ -1,6 +1,8 @@
-export class RessourceNotFoundError extends Error {
+export class ResourceNotFoundError extends Error {
+ id: string;
constructor(type: string, id: string) {
super(`${type} with ${id} not found}`);
- this.name = "RessourceNotFoundError";
+ this.name = "ResourceNotFoundError";
+ this.id = id;
}
}
diff --git a/src/utils/json.ts b/src/utils/json.ts
new file mode 100644
index 0000000000..a2cec8ddbf
--- /dev/null
+++ b/src/utils/json.ts
@@ -0,0 +1,13 @@
+import { type jsonSchema } from "@/src/utils/zod";
+import { type z } from "zod";
+import lodash from "lodash";
+
+export const mergeJson = (
+ json1?: z.infer<typeof jsonSchema>,
+ json2?: z.infer<typeof jsonSchema>,
+) => {
+ if (json1 === undefined) {
+ return json2;
+ }
+ return lodash.merge(json1, json2);
+};
diff --git a/src/utils/types.ts b/src/utils/types.ts
index f1807ee513..fbbe8d1e65 100644
--- a/src/utils/types.ts
+++ b/src/utils/types.ts
@@ -37,9 +37,12 @@ export type Generation = Observation & {
export type RouterInput = inferRouterInputs<AppRouter>;
export type RouterOutput = inferRouterOutputs<AppRouter>;
-export const isNotUndefinedOrNull = <T>(
+export const isUndefinedOrNull = <T>(val?: T | null): val is undefined | null =>
+ val === undefined || val === null;
+
+export const isNotNullOrUndefined = <T>(
val?: T | null,
-): val is undefined | null => val !== undefined || val !== null;
+): val is Exclude<T, null | undefined> => !isUndefinedOrNull(val);
export function isValidOption(
value: unknown,