🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
feat: add metadata to ingestion api (#703)
Max Deichmann977f006a7421
diff --git a/fern/apis/server/definition/ingestion.yml b/fern/apis/server/definition/ingestion.ymlindex 160d168915..f5cd1b105b 100644--- a/fern/apis/server/definition/ingestion.yml+++ b/fern/apis/server/definition/ingestion.yml@@ -144,58 +144,55 @@ types:observationId: optional<string>comment: optional<string>- TraceEvent:+ BaseEvent:properties:id: stringtimestamp: string+ metadata: unknown++ TraceEvent:+ extends: BaseEvent+ properties:body: TraceBodyCreateObservationEvent:+ extends: BaseEventproperties:- id: string- timestamp: stringbody: ObservationBodyUpdateObservationEvent:+ extends: BaseEventproperties:- id: string- timestamp: stringbody: ObservationBodyScoreEvent:+ extends: BaseEventproperties:- id: string- timestamp: stringbody: ScoreBodyCreateGenerationEvent:+ extends: BaseEventproperties:- id: string- timestamp: stringbody: CreateGenerationBodyUpdateGenerationEvent:+ extends: BaseEventproperties:- id: string- timestamp: stringbody: UpdateGenerationBodyCreateSpanEvent:+ extends: BaseEventproperties:- id: string- timestamp: stringbody: CreateSpanBodyUpdateSpanEvent:+ extends: BaseEventproperties:- id: string- timestamp: stringbody: UpdateSpanBodyCreateEventEvent:+ extends: BaseEventproperties:- id: string- timestamp: stringbody: CreateEventBodyIngestionSuccess:diff --git a/generated/openapi-server/openapi.yml b/generated/openapi-server/openapi.ymlindex 772c6ba824..2b529b9f1f 100644--- a/generated/openapi-server/openapi.yml+++ b/generated/openapi-server/openapi.yml@@ -1547,132 +1547,109 @@ components:- traceId- name- value- TraceEvent:- title: TraceEvent+ BaseEvent:+ title: BaseEventtype: objectproperties:id:type: stringtimestamp:type: string- body:- $ref: '#/components/schemas/TraceBody'+ metadata: {}required:- id- timestamp+ - metadata+ TraceEvent:+ title: TraceEvent+ type: object+ properties:+ body:+ $ref: '#/components/schemas/TraceBody'+ required:- body+ allOf:+ - $ref: '#/components/schemas/BaseEvent'CreateObservationEvent:title: CreateObservationEventtype: objectproperties:- id:- type: string- timestamp:- type: stringbody:$ref: '#/components/schemas/ObservationBody'required:- - id- - timestamp- body+ allOf:+ - $ref: '#/components/schemas/BaseEvent'UpdateObservationEvent:title: UpdateObservationEventtype: objectproperties:- id:- type: string- timestamp:- type: stringbody:$ref: '#/components/schemas/ObservationBody'required:- - id- - timestamp- body+ allOf:+ - $ref: '#/components/schemas/BaseEvent'ScoreEvent:title: ScoreEventtype: objectproperties:- id:- type: string- timestamp:- type: stringbody:$ref: '#/components/schemas/ScoreBody'required:- - id- - timestamp- body+ allOf:+ - $ref: '#/components/schemas/BaseEvent'CreateGenerationEvent:title: CreateGenerationEventtype: objectproperties:- id:- type: string- timestamp:- type: stringbody:$ref: '#/components/schemas/CreateGenerationBody'required:- - id- - timestamp- body+ allOf:+ - $ref: '#/components/schemas/BaseEvent'UpdateGenerationEvent:title: UpdateGenerationEventtype: objectproperties:- id:- type: string- timestamp:- type: stringbody:$ref: '#/components/schemas/UpdateGenerationBody'required:- - id- - timestamp- body+ allOf:+ - $ref: '#/components/schemas/BaseEvent'CreateSpanEvent:title: CreateSpanEventtype: objectproperties:- id:- type: string- timestamp:- type: stringbody:$ref: '#/components/schemas/CreateSpanBody'required:- - id- - timestamp- body+ allOf:+ - $ref: '#/components/schemas/BaseEvent'UpdateSpanEvent:title: UpdateSpanEventtype: objectproperties:- id:- type: string- timestamp:- type: stringbody:$ref: '#/components/schemas/UpdateSpanBody'required:- - id- - timestamp- body+ allOf:+ - $ref: '#/components/schemas/BaseEvent'CreateEventEvent:title: CreateEventEventtype: objectproperties:- id:- type: string- timestamp:- type: stringbody:$ref: '#/components/schemas/CreateEventBody'required:- - id- - timestamp- body+ allOf:+ - $ref: '#/components/schemas/BaseEvent'IngestionSuccess:title: IngestionSuccesstype: objectdiff --git a/generated/postman/collection.json b/generated/postman/collection.jsonindex 3d6d61f0e0..0233c57063 100644--- a/generated/postman/collection.json+++ b/generated/postman/collection.json@@ -320,7 +320,7 @@"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 \"name\": \"example\",\n \"userId\": \"example\",\n \"input\": \"UNKNOWN\",\n \"output\": \"UNKNOWN\",\n \"sessionId\": \"example\",\n \"release\": \"example\",\n \"version\": \"example\",\n \"metadata\": \"UNKNOWN\",\n \"public\": true\n }\n }\n ]\n}",+ "raw": "{\n \"batch\": [\n {\n \"type\": \"trace-create\",\n \"body\": {\n \"id\": \"example\",\n \"name\": \"example\",\n \"userId\": \"example\",\n \"input\": \"UNKNOWN\",\n \"output\": \"UNKNOWN\",\n \"sessionId\": \"example\",\n \"release\": \"example\",\n \"version\": \"example\",\n \"metadata\": \"UNKNOWN\",\n \"public\": true\n },\n \"id\": \"example\",\n \"timestamp\": \"example\",\n \"metadata\": \"UNKNOWN\"\n }\n ]\n}","options": {"raw": {"language": "json"diff --git a/src/__tests__/ingestion.servertest.ts b/src/__tests__/ingestion.servertest.tsindex 3764e90d51..1ac027a025 100644--- a/src/__tests__/ingestion.servertest.ts+++ b/src/__tests__/ingestion.servertest.ts@@ -91,6 +91,10 @@ describe("/api/public/ingestion API Endpoint", () => {const scoreId = v4();const response = await makeAPICall("POST", "/api/public/ingestion", {+ metadata: {+ sdk_verion: "1.0.0",+ sdk_name: "python",+ },batch: [{id: v4(),diff --git a/src/features/public-api/server/ingestion-api-schema.ts b/src/features/public-api/server/ingestion-api-schema.tsindex 1963159026..6d4bac6191 100644--- a/src/features/public-api/server/ingestion-api-schema.ts+++ b/src/features/public-api/server/ingestion-api-schema.ts@@ -243,6 +243,7 @@ export const eventTypes = {const base = z.object({id: z.string(),timestamp: z.string().datetime({ offset: true }),+ metadata: jsonSchema.nullish(),});export const traceEvent = base.extend({type: z.literal(eventTypes.TRACE_CREATE),@@ -299,4 +300,5 @@ export const ingestionBatchEvent = z.array(ingestionEvent);export const ingestionApiSchema = z.object({batch: ingestionBatchEvent,+ metadata: jsonSchema.nullish(),});diff --git a/src/pages/api/public/events.ts b/src/pages/api/public/events.tsindex e2be1d81c2..7ca51ba683 100644--- a/src/pages/api/public/events.ts+++ b/src/pages/api/public/events.ts@@ -59,6 +59,7 @@ export default async function handler(const result = await handleBatch(ingestionBatchEvent.parse([event]),+ {},req,authCheck,);diff --git a/src/pages/api/public/generations.ts b/src/pages/api/public/generations.tsindex 733c50289b..726f437dcf 100644--- a/src/pages/api/public/generations.ts+++ b/src/pages/api/public/generations.ts@@ -62,6 +62,7 @@ export default async function handler(const result = await handleBatch(ingestionBatchEvent.parse([event]),+ {},req,authCheck,);@@ -106,6 +107,7 @@ export default async function handler(const result = await handleBatch(ingestionBatchEvent.parse([event]),+ {},req,authCheck,);diff --git a/src/pages/api/public/ingestion.ts b/src/pages/api/public/ingestion.tsindex e7cd1411db..14b1a1669d 100644--- a/src/pages/api/public/ingestion.ts+++ b/src/pages/api/public/ingestion.ts@@ -21,6 +21,7 @@ import { TraceProcessor } from "../../../server/api/services/EventProcessor";import { ScoreProcessor } from "../../../server/api/services/EventProcessor";import { isNotNullOrUndefined } from "@/src/utils/types";import { telemetry } from "@/src/features/telemetry";+import { jsonSchema } from "@/src/utils/zod";export default async function handler(req: NextApiRequest,@@ -48,7 +49,11 @@ export default async function handler(message: "Access denied",});- const batchType = z.object({ batch: z.array(z.unknown()) });+ const batchType = z.object({+ batch: z.array(z.unknown()),+ metadata: jsonSchema.nullish(),+ });+const parsedSchema = batchType.safeParse(req.body);if (!parsedSchema.success) {@@ -85,7 +90,12 @@ export default async function handler(await telemetry();const sortedBatch = sortBatch(filteredBatch);- const result = await handleBatch(sortedBatch, req, authCheck);+ const result = await handleBatch(+ sortedBatch,+ parsedSchema.data.metadata,+ req,+ authCheck,+ );handleBatchResult([...errors, ...result.errors], result.results, res);} catch (error: unknown) {@@ -117,6 +127,7 @@ const sortBatch = (batch: Array<z.infer<typeof ingestionEvent>>) => {export const handleBatch = async (events: z.infer<typeof ingestionApiSchema>["batch"],+ metadata: z.infer<typeof ingestionApiSchema>["metadata"],req: NextApiRequest,authCheck: AuthHeaderVerificationResult,) => {@@ -129,7 +140,12 @@ export const handleBatch = async (for (const singleEvent of events) {try {const result = await retry(async () => {- return await handleSingleEvent(singleEvent, req, authCheck.scope);+ return await handleSingleEvent(+ singleEvent,+ metadata,+ req,+ authCheck.scope,+ );});results.push({ result: result, id: singleEvent.id }); // Push each result into the array} catch (error) {@@ -175,6 +191,7 @@ export const hasBadRequestError = (errors: Array<unknown>) =>const handleSingleEvent = async (event: z.infer<typeof ingestionEvent>,+ metadata: z.infer<typeof ingestionApiSchema>["metadata"],req: NextApiRequest,apiScope: ApiAccessScope,) => {@@ -187,7 +204,14 @@ const handleSingleEvent = async (const { type } = cleanedEvent;- await persistEventMiddleware(prisma, apiScope.projectId, req, cleanedEvent);+ await persistEventMiddleware(+ prisma,++ apiScope.projectId,+ req,+ cleanedEvent,+ metadata,+ );let processor: EventProcessor;switch (type) {diff --git a/src/pages/api/public/scores.ts b/src/pages/api/public/scores.tsindex 870112746c..25a63b9724 100644--- a/src/pages/api/public/scores.ts+++ b/src/pages/api/public/scores.ts@@ -56,6 +56,7 @@ export default async function handler(const result = await handleBatch(ingestionBatchEvent.parse([event]),+ {},req,authCheck,);diff --git a/src/pages/api/public/spans.ts b/src/pages/api/public/spans.tsindex 9280be2c3e..8a5712526c 100644--- a/src/pages/api/public/spans.ts+++ b/src/pages/api/public/spans.ts@@ -58,6 +58,7 @@ export default async function handler(const result = await handleBatch(ingestionBatchEvent.parse([event]),+ {},req,authCheck,);@@ -99,6 +100,7 @@ export default async function handler(const result = await handleBatch(ingestionBatchEvent.parse([event]),+ {},req,authCheck,);diff --git a/src/pages/api/public/traces.ts b/src/pages/api/public/traces.tsindex c23bd3402d..d49ef09087 100644--- a/src/pages/api/public/traces.ts+++ b/src/pages/api/public/traces.ts@@ -63,7 +63,7 @@ export default async function handler(body: body,};- const result = await handleBatch([event], req, authCheck);+ const result = await handleBatch([event], {}, req, authCheck);handleBatchResultLegacy(result.errors, result.results, res);} else if (req.method === "GET") {if (authCheck.scope.accessLevel !== "all") {diff --git a/src/server/api/services/event-service.ts b/src/server/api/services/event-service.tsindex 817eaa1ff9..85bb7b6c69 100644--- a/src/server/api/services/event-service.ts+++ b/src/server/api/services/event-service.ts@@ -1,5 +1,7 @@import { type Prisma, type PrismaClient } from "@prisma/client";import { type NextApiRequest } from "next";+import { type jsonSchema } from "@/src/utils/zod";+import lodash from "lodash";// This function persists raw events to the database which came via API// It relates each event to a project@@ -12,18 +14,24 @@ export const persistEventMiddleware = async (projectId: string,req: NextApiRequest,data: Prisma.JsonObject,+ metadata?: Zod.infer<typeof jsonSchema> | null,) => {const langfuseHeadersObject = Object.fromEntries(Object.entries(req.headers).filter(([key]) => key.startsWith("x-langfuse")),);+ console.log("langfuseHeadersObject", langfuseHeadersObject);+ console.log("metadata", metadata);+ // combine metadata from the request and langfuseHeadersObject+ const combinedMetadata = lodash.merge(metadata, langfuseHeadersObject);+ console.log("combinedMetadata", combinedMetadata);await prisma.events.create({data: {project: { connect: { id: projectId } },url: req.url,method: req.method,data: data,- headers: langfuseHeadersObject,+ headers: combinedMetadata,},});};