🪢 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
chore: remove hasCreateEvent check in ingestion pipeline (#3937)
Steffen Schmitzc8ff61057e26
diff --git a/worker/src/services/IngestionService/index.ts b/worker/src/services/IngestionService/index.tsindex 6bad0c6756..bd09dbbd89 100644--- a/worker/src/services/IngestionService/index.ts+++ b/worker/src/services/IngestionService/index.ts@@ -69,7 +69,7 @@ export class IngestionService {private redis: Redis,private prisma: PrismaClient,private clickHouseWriter: ClickhouseWriter,- private clickhouseClient: ClickhouseClientType+ private clickhouseClient: ClickhouseClientType,) {this.promptService = new PromptService(prisma, redis);}@@ -78,10 +78,10 @@ export class IngestionService {eventType: ClickhouseEntityType,projectId: string,eventBodyId: string,- events: IngestionEventType[]+ events: IngestionEventType[],): Promise<void> {logger.info(- `Merging ingestion ${eventType} event for project ${projectId} and event ${eventBodyId}`+ `Merging ingestion ${eventType} event for project ${projectId} and event ${eventBodyId}`,);switch (eventType) {@@ -153,12 +153,6 @@ export class IngestionService {table: TableName.Scores,});- if (!clickhouseScoreRecord && !this.hasCreateEvent(scoreEventList)) {- throw new Error(- `No create event or existing record found for score with id ${entityId} in project ${projectId}`- );- }-const finalScoreRecord: ScoreRecordInsertType =await this.mergeScoreRecords({clickhouseScoreRecord,@@ -191,12 +185,6 @@ export class IngestionService {table: TableName.Traces,});- if (!clickhouseTraceRecord && !this.hasCreateEvent(traceEventList)) {- throw new Error(- `No create event or existing record found for trace with id ${entityId} in project ${projectId}`- );- }-const finalTraceRecord = await this.mergeTraceRecords({clickhouseTraceRecord,traceRecords,@@ -230,15 +218,6 @@ export class IngestionService {table: TableName.Observations,});- if (- !clickhouseObservationRecord &&- !this.hasCreateEvent(observationEventList)- ) {- throw new Error(- `No create event or existing record found for observation with id ${entityId} in project ${projectId}`- );- }-const finalObservationRecord = await this.mergeObservationRecords({projectId,observationRecords,@@ -267,7 +246,7 @@ export class IngestionService {this.clickHouseWriter.addToQueue(TableName.Observations,- finalObservationRecord+ finalObservationRecord,);}@@ -283,13 +262,13 @@ export class IngestionService {const mergedRecord = this.mergeRecords(recordsToMerge,- immutableEntityKeys[TableName.Scores]+ immutableEntityKeys[TableName.Scores],);const parsedRecord = scoreRecordInsertSchema.parse(mergedRecord);parsedRecord.event_ts = Math.max(...scoreRecords.map((r) => r.event_ts),- clickhouseScoreRecord?.event_ts ?? -Infinity+ clickhouseScoreRecord?.event_ts ?? -Infinity,);return parsedRecord;}@@ -306,13 +285,13 @@ export class IngestionService {const mergedRecord = this.mergeRecords(recordsToMerge,- immutableEntityKeys[TableName.Traces]+ immutableEntityKeys[TableName.Traces],);const parsedRecord = traceRecordInsertSchema.parse(mergedRecord);parsedRecord.event_ts = Math.max(...traceRecords.map((r) => r.event_ts),- clickhouseTraceRecord?.event_ts ?? -Infinity+ clickhouseTraceRecord?.event_ts ?? -Infinity,);return parsedRecord;}@@ -331,7 +310,7 @@ export class IngestionService {const mergedRecord = this.mergeRecords(recordsToMerge,- immutableEntityKeys[TableName.Observations]+ immutableEntityKeys[TableName.Observations],);const parsedObservationRecord =@@ -355,14 +334,14 @@ export class IngestionService {...generationUsage,event_ts: Math.max(...observationRecords.map((r) => r.event_ts),- clickhouseObservationRecord?.event_ts ?? -Infinity+ clickhouseObservationRecord?.event_ts ?? -Infinity,),};}private mergeRecords<T extends InsertRecord>(records: T[],- immutableEntityKeys: string[]+ immutableEntityKeys: string[],): unknown {if (records.length === 0) {throw new Error("No records to merge");@@ -398,7 +377,7 @@ export class IngestionService {private async getPrompt(projectId: string,- observationEventList: ObservationEvent[]+ observationEventList: ObservationEvent[],): Promise<ObservationPrompt | null> {const lastObservationWithPromptInfo = observationEventList.slice()@@ -419,7 +398,7 @@ export class IngestionService {}private hasPromptInformation(- event: ObservationEvent+ event: ObservationEvent,): event is ObservationEvent & {body: { promptName: string; promptVersion: number };} {@@ -451,13 +430,13 @@ export class IngestionService {const final_usage_details = this.getUsageUnits(observationRecord,- internalModel+ internalModel,);const modelPrices = await this.getModelPrices(internalModel?.id);const final_cost_details = IngestionService.calculateUsageCosts(modelPrices,observationRecord,- final_usage_details.usage_details ?? {}+ final_usage_details.usage_details ?? {},);return {@@ -475,10 +454,10 @@ export class IngestionService {private getUsageUnits(observationRecord: ObservationRecordInsertType,- model: Model | null | undefined+ model: Model | null | undefined,): Pick<ObservationRecordInsertType, "usage_details"> {const providedUsageKeys = Object.entries(- observationRecord.provided_usage_details ?? {}+ observationRecord.provided_usage_details ?? {},).filter(([_, value]) => value != null).map(([key]) => key);@@ -519,7 +498,7 @@ export class IngestionService {static calculateUsageCosts(modelPrices: Price[] | null | undefined,observationRecord: ObservationRecordInsertType,- usageUnits: UsageCostType+ usageUnits: UsageCostType,): Pick<ObservationRecordInsertType, "cost_details" | "total_cost"> {const { provided_cost_details } = observationRecord;@@ -572,7 +551,7 @@ export class IngestionService {} else if (finalCostEntries.length > 0) {finalTotalCost = finalCostEntries.reduce((acc, [_, cost]) => acc + cost,- 0+ 0,);finalCostDetails.total = finalTotalCost;@@ -626,7 +605,7 @@ export class IngestionService {: table === TableName.Scores? convertScoreReadToInsert(recordParser[table].parse(result[0])): convertObservationReadToInsert(- recordParser[table].parse(result[0])+ recordParser[table].parse(result[0]),);});}@@ -644,7 +623,7 @@ export class IngestionService {// in the default implementation, we set timestamps server side if not provided.// we need to insert timestamps here and change the SDKs to send timestamps client side.timestamp: this.getMillisecondTimestamp(- trace.body.timestamp ?? trace.timestamp+ trace.body.timestamp ?? trace.timestamp,),name: trace.body.name,user_id: trace.body.userId,@@ -744,7 +723,7 @@ export class IngestionService {type: observationType,name: obs.body.name,start_time: this.getMillisecondTimestamp(- obs.body.startTime ?? obs.timestamp+ obs.body.startTime ?? obs.timestamp,),end_time:"endTime" in obs.body && obs.body.endTime@@ -789,7 +768,7 @@ export class IngestionService {}private stringify(- obj: string | object | number | boolean | undefined | null+ obj: string | object | number | boolean | undefined | null,): string | undefined {if (obj == null) return; // return undefined on undefined or null@@ -799,14 +778,6 @@ export class IngestionService {private getMillisecondTimestamp(timestamp?: string | null): number {return timestamp ? new Date(timestamp).getTime() : Date.now();}-- private hasCreateEvent(- eventList: ObservationEvent[] | ScoreEventType[] | TraceEventType[]- ): boolean {- return eventList.some((event) =>- event.type.toLowerCase().includes("create")- );- }}type ObservationPrompt = Pick<Prompt, "id" | "name" | "version">;diff --git a/worker/src/services/IngestionService/tests/IngestionService.integration.test.ts b/worker/src/services/IngestionService/tests/IngestionService.integration.test.tsindex 5000b12233..4137bf7100 100644--- a/worker/src/services/IngestionService/tests/IngestionService.integration.test.ts+++ b/worker/src/services/IngestionService/tests/IngestionService.integration.test.ts@@ -39,7 +39,7 @@ describe("Ingestion end-to-end tests", () => {redis,prisma,clickhouseWriter,- clickhouseClient+ clickhouseClient,);});@@ -198,7 +198,7 @@ describe("Ingestion end-to-end tests", () => {it(`should create trace, generation and score without matching models ${JSON.stringify(testConfig,null,- 2+ 2,)}`, async () => {const traceId = randomUUID();const generationId = randomUUID();@@ -322,7 +322,7 @@ describe("Ingestion end-to-end tests", () => {const generation = await getClickhouseRecord(TableName.Observations,- generationId+ generationId,);expect(generation.id).toBe(generationId);@@ -334,25 +334,25 @@ describe("Ingestion end-to-end tests", () => {expect(generation.model_parameters).toEqual(JSON.stringify({key: "value",- })+ }),);expect(generation.input).toEqual(JSON.stringify({ key: "value" }));expect(parseMetadata(generation.metadata)).toEqual({ key: "value" });expect(generation.version).toBe("2.0.0");expect(generation.internal_model_id).toBeNull();expect(generation.usage_details.input).toEqual(- testConfig.expectedInputUnits+ testConfig.expectedInputUnits,);expect(generation.usage_details.output).toEqual(- testConfig.expectedOutputUnits+ testConfig.expectedOutputUnits,);expect(generation.usage_details.total).toEqual(- testConfig.expectedTotalUnits+ testConfig.expectedTotalUnits,);expect(generation.output).toEqual(JSON.stringify({key: "this is a great gpt output",- })+ }),);const span = await getClickhouseRecord(TableName.Observations, spanId);@@ -561,7 +561,7 @@ describe("Ingestion end-to-end tests", () => {it(`should match observations to internal models ${JSON.stringify(testConfig,null,- 2+ 2,)}`, async () => {const traceId = randomUUID();const generationId = randomUUID();@@ -585,8 +585,8 @@ describe("Ingestion end-to-end tests", () => {: model.modelName,},},- })- )+ }),+ ),);const traceEventList: TraceEventType[] = [@@ -637,26 +637,26 @@ describe("Ingestion end-to-end tests", () => {const generation = await getClickhouseRecord(TableName.Observations,- generationId+ generationId,);expect(generation.id).toBe(generationId);expect(generation.trace_id).toBe(traceId);expect(generation.name).toBe("generation-name");expect(generation.start_time).toEqual(- testConfig.observationStartTime.toISOString()+ testConfig.observationStartTime.toISOString(),);expect(generation.provided_model_name).toBe(- testConfig.observationExternalModel+ testConfig.observationExternalModel,);expect(generation.usage_details.input).toBe(- testConfig.expectedInputUnits+ testConfig.expectedInputUnits,);expect(generation.usage_details.output).toBe(- testConfig.expectedOutputUnits+ testConfig.expectedOutputUnits,);expect(generation.internal_model_id).toBe(- testConfig.expectedInternalModelId+ testConfig.expectedInternalModelId,);});});@@ -796,7 +796,7 @@ describe("Ingestion end-to-end tests", () => {const generation = await getClickhouseRecord(TableName.Observations,- generationId+ generationId,);expect(generation?.id).toBe(generationId);@@ -806,7 +806,7 @@ describe("Ingestion end-to-end tests", () => {expect(generation?.model_parameters).toEqual(JSON.stringify({someKey: ["user-1", "user-2"],- })+ }),);const event = await getClickhouseRecord(TableName.Observations, eventId);@@ -891,116 +891,12 @@ describe("Ingestion end-to-end tests", () => {expect(trace.tags.length).toBe(4);});- it("should fail if no create event AND no existing record in CH", async () => {- const traceId = randomUUID();- const generationId = randomUUID();-- // First flush- const traceEventList1: TraceEventType[] = [- {- id: randomUUID(),- 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",- tags: ["tag-1", "tag-2", "tag-2"],- },- },- ];-- const generationEventListNoCreate: ObservationEvent[] = [- {- id: randomUUID(),- type: "observation-update",- timestamp: new Date().toISOString(),- body: {- id: generationId,- traceId: traceId,- type: "GENERATION",- output: { key: "this is a great gpt output" },- },- },- ];-- await ingestionService.processTraceEventList({- projectId,- entityId: traceId,- traceEventList: traceEventList1,- });-- expect(- ingestionService.processObservationEventList({- projectId,- entityId: generationId,- observationEventList: generationEventListNoCreate,- })- ).rejects.toThrow();-- const generationEventListWithCreate: ObservationEvent[] = [- {- id: randomUUID(),- type: "observation-create",- timestamp: new Date().toISOString(),- body: {- id: generationId,- traceId: traceId,- type: "GENERATION",- input: "This is a great prompt",- },- },- ];-- await ingestionService.processObservationEventList({- projectId,- entityId: generationId,- observationEventList: generationEventListWithCreate,- });-- await clickhouseWriter.flushAll(true);-- vi.useRealTimers();- await new Promise((resolve) => setTimeout(resolve, 1000));- vi.useFakeTimers();-- // Now the generation update should work- await ingestionService.processObservationEventList({- projectId,- entityId: generationId,- observationEventList: generationEventListNoCreate,- });-- await clickhouseWriter.flushAll(true);-- vi.useRealTimers();- await new Promise((resolve) => setTimeout(resolve, 1000));- vi.useFakeTimers();-- const generation = await getClickhouseRecord(- TableName.Observations,- generationId- );-- expect(generation.id).toBe(generationId);- expect(generation.trace_id).toBe(traceId);- expect(generation.output).toEqual(- JSON.stringify({- key: "this is a great gpt output",- })- );- expect(generation.input).toEqual("This is a great prompt");- });-it("should upsert traces in the right order", async () => {const traceId = randomUUID();const latestEvent = new Date();const oldEvent = new Date(latestEvent).setSeconds(- latestEvent.getSeconds() - 1+ latestEvent.getSeconds() - 1,);const traceEventList: TraceEventType[] = [@@ -1084,18 +980,18 @@ describe("Ingestion end-to-end tests", () => {const generation = await getClickhouseRecord(TableName.Observations,- generationId+ generationId,);expect(generation.output).toEqual(JSON.stringify({key: "this is a great gpt output",- })+ }),);expect(generation.input).toEqual(JSON.stringify({ key: "value" }));expect(generation.provided_model_name).toEqual("gpt-3.5");expect(generation.output).toEqual(- JSON.stringify({ key: "this is a great gpt output" })+ JSON.stringify({ key: "this is a great gpt output" }),);});@@ -1189,7 +1085,7 @@ describe("Ingestion end-to-end tests", () => {const generation = await getClickhouseRecord(TableName.Observations,- generationId+ generationId,);expect(generation.usage_details.input).toEqual(1285);@@ -1290,18 +1186,18 @@ describe("Ingestion end-to-end tests", () => {const generation = await getClickhouseRecord(TableName.Observations,- generationId+ generationId,);expect(generation?.output).toEqual(JSON.stringify({key: "this is a great gpt output",- })+ }),);expect(generation?.input).toEqual(JSON.stringify({ key: "value" }));expect(generation?.provided_model_name).toEqual("gpt-3.5");expect(generation?.output).toEqual(- JSON.stringify({ key: "this is a great gpt output" })+ JSON.stringify({ key: "this is a great gpt output" }),);expect(generation?.usage_details.input).toEqual(5);expect(generation?.usage_details.output).toEqual(11);@@ -1383,18 +1279,18 @@ describe("Ingestion end-to-end tests", () => {const trace = await getClickhouseRecord(TableName.Traces, traceId);const observation = await getClickhouseRecord(TableName.Observations,- generationId+ generationId,);expect(observation?.output).toEqual(JSON.stringify({key: "this is a great gpt output",- })+ }),);expect(observation?.input).toEqual(JSON.stringify({ key: "value" }));expect(observation?.provided_model_name).toEqual("gpt-3.5");expect(observation?.output).toEqual(- JSON.stringify({ key: "this is a great gpt output" })+ JSON.stringify({ key: "this is a great gpt output" }),);expect(observation?.usage_details.input).toEqual(5);expect(observation?.usage_details.output).toEqual(11);@@ -1482,7 +1378,7 @@ describe("Ingestion end-to-end tests", () => {},].forEach(({ inputs, output }) => {it(`merges metadata ${JSON.stringify(inputs)}, ${JSON.stringify(- output+ output,)}`, async () => {const traceId = randomUUID();const generationId = randomUUID();@@ -1558,7 +1454,7 @@ describe("Ingestion end-to-end tests", () => {const generation = await getClickhouseRecord(TableName.Observations,- generationId+ generationId,);expect(parseMetadata(generation.metadata)).toEqual(output);@@ -1568,7 +1464,7 @@ describe("Ingestion end-to-end tests", () => {async function getClickhouseRecord<T extends TableName>(tableName: T,- entityId: string+ entityId: string,): Promise<RecordReadType<T>> {const query = await clickhouseClient.query({query: `SELECT * FROM ${tableName} FINAL WHERE project_id = '${projectId}' AND id = '${entityId}'`,