Skip to content

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

perf: reduce redundant parsing operations within ingestionservice (#5243)

Steffen Schmitz34eb3e3d7619
diff --git a/packages/shared/src/utils/json.ts b/packages/shared/src/utils/json.ts
index b481b86243..3632332949 100644
--- a/packages/shared/src/utils/json.ts
+++ b/packages/shared/src/utils/json.ts
@@ -1,6 +1,4 @@
-import { z } from "zod";
-import { merge } from "lodash";
-import { JsonNested, jsonSchema } from "./zod";
+import { JsonNested } from "./zod";
/**
* Deeply parses a JSON string or object for nested stringified JSON
@@ -40,16 +38,6 @@ export function deepParseJson(json: unknown): unknown {
return json;
}
-export const mergeJson = (
- json1?: z.infer<typeof jsonSchema>,
- json2?: z.infer<typeof jsonSchema>,
-) => {
- if (json1 === undefined) {
- return json2;
- }
- return merge(json1, json2);
-};
-
export const parseJsonPrioritised = (
json: string,
): JsonNested | string | undefined => {
@@ -59,24 +47,3 @@ export const parseJsonPrioritised = (
return json;
}
};
-
-export const convertRecordToJsonSchema = (
- record: Record<string, string>,
-): JsonNested | undefined => {
- const jsonSchema: JsonNested = {};
-
- // if record is empty, return undefined
- if (Object.keys(record).length === 0) {
- return undefined;
- }
-
- for (const key in record) {
- try {
- jsonSchema[key] = JSON.parse(record[key]);
- } catch (e) {
- jsonSchema[key] = record[key];
- }
- }
-
- return jsonSchema;
-};
diff --git a/worker/src/services/IngestionService/index.ts b/worker/src/services/IngestionService/index.ts
index 45993476a3..b4b74acbbc 100644
--- a/worker/src/services/IngestionService/index.ts
+++ b/worker/src/services/IngestionService/index.ts
@@ -43,7 +43,11 @@ import {
import { tokenCount } from "../../features/tokenisation/usage";
import { ClickhouseWriter, TableName } from "../ClickhouseWriter";
-import { convertJsonSchemaToRecord, overwriteObject } from "./utils";
+import {
+ convertJsonSchemaToRecord,
+ convertRecordValuesToString,
+ overwriteObject,
+} from "./utils";
import { randomUUID } from "crypto";
import { env } from "../../env";
@@ -256,6 +260,18 @@ export class IngestionService {
finalTraceRecord.created_at =
clickhouseTraceRecord?.created_at ?? createdAtTimestamp.getTime();
+ // Search for the first non-null input and output in the trace events and set them on the merged result.
+ // Fallback to the ClickHouse input/output if none are found within the events list.
+ const reversedRawRecords = timeSortedEvents.slice().reverse();
+ finalTraceRecord.input = this.stringify(
+ reversedRawRecords.find((record) => record?.body?.input)?.body?.input ??
+ clickhouseTraceRecord?.input,
+ );
+ finalTraceRecord.output = this.stringify(
+ reversedRawRecords.find((record) => record?.body?.output)?.body?.output ??
+ clickhouseTraceRecord?.output,
+ );
+
// If the trace has a sessionId, we upsert the corresponding session into Postgres.
if (finalTraceRecord.session_id) {
try {
@@ -359,14 +375,35 @@ export class IngestionService {
prompt,
});
- const finalObservationRecord = await this.mergeObservationRecords({
+ const mergedObservationRecord = await this.mergeObservationRecords({
projectId,
observationRecords,
clickhouseObservationRecord,
});
- finalObservationRecord.created_at =
+ mergedObservationRecord.created_at =
clickhouseObservationRecord?.created_at ?? createdAtTimestamp.getTime();
- finalObservationRecord.level = finalObservationRecord.level ?? "DEFAULT";
+ mergedObservationRecord.level = mergedObservationRecord.level ?? "DEFAULT";
+
+ // Search for the first non-null input and output in the observation events and set them on the merged result.
+ // Fallback to the ClickHouse input/output if none are found within the events list.
+ const reversedRawRecords = timeSortedEvents.slice().reverse();
+ mergedObservationRecord.input = this.stringify(
+ reversedRawRecords.find((record) => record?.body?.input)?.body?.input ??
+ clickhouseObservationRecord?.input,
+ );
+ mergedObservationRecord.output = this.stringify(
+ reversedRawRecords.find((record) => record?.body?.output)?.body?.output ??
+ clickhouseObservationRecord?.output,
+ );
+
+ const generationUsage = await this.getGenerationUsage({
+ projectId,
+ observationRecord: mergedObservationRecord,
+ });
+ const finalObservationRecord = {
+ ...mergedObservationRecord,
+ ...generationUsage,
+ };
// Backward compat: create wrapper trace for SDK < 2.0.0 events that do not have a traceId
if (!finalObservationRecord.trace_id) {
@@ -429,6 +466,11 @@ export class IngestionService {
immutableEntityKeys[TableName.Traces],
);
+ // If metadata exists, it is an object due to previous parsing
+ mergedRecord.metadata = convertRecordValuesToString(
+ (mergedRecord.metadata as Record<string, unknown>) ?? {},
+ );
+
return traceRecordInsertSchema.parse(mergedRecord);
}
@@ -451,6 +493,11 @@ export class IngestionService {
immutableEntityKeys[TableName.Observations],
);
+ // If metadata exists, it is an object due to previous parsing
+ mergedRecord.metadata = convertRecordValuesToString(
+ (mergedRecord.metadata as Record<string, unknown>) ?? {},
+ );
+
const parsedObservationRecord =
observationRecordInsertSchema.parse(mergedRecord);
@@ -462,15 +509,7 @@ export class IngestionService {
parsedObservationRecord.end_time = parsedObservationRecord.start_time;
}
- const generationUsage = await this.getGenerationUsage({
- projectId,
- observationRecord: parsedObservationRecord,
- });
-
- return {
- ...parsedObservationRecord,
- ...generationUsage,
- };
+ return parsedObservationRecord;
}
private mergeRecords<T extends InsertRecord>(
@@ -871,7 +910,7 @@ export class IngestionService {
traceEventList: TraceEventType[];
projectId: string;
entityId: string;
- }): TraceRecordInsertType[] {
+ }) {
const { traceEventList, projectId, entityId } = params;
return traceEventList.map((trace) => {
@@ -900,8 +939,10 @@ export class IngestionService {
public: trace.body.public ?? false,
bookmarked: false,
tags: trace.body.tags ?? [],
- input: this.stringify(trace.body.input),
- output: this.stringify(trace.body.output), // convert even json to string
+ // We skip the processing here as stringifying is an expensive operation on large objects.
+ // Instead, we only take the last truthy value and apply it on the merge step.
+ // input: this.stringify(trace.body.input),
+ // output: this.stringify(trace.body.output), // convert even json to string
session_id: trace.body.sessionId,
created_at: Date.now(),
updated_at: Date.now(),
@@ -1032,8 +1073,10 @@ export class IngestionService {
? JSON.stringify(obs.body.modelParameters)
: undefined
: undefined,
- input: this.stringify(obs.body.input),
- output: this.stringify(obs.body.output),
+ // We skip the processing here as stringifying is an expensive operation on large objects.
+ // Instead, we only take the last truthy value and apply it on the merge step.
+ // input: this.stringify(obs.body.input),
+ // output: this.stringify(obs.body.output),
provided_usage_details,
provided_cost_details,
usage_details: provided_usage_details,
diff --git a/worker/src/services/IngestionService/utils.ts b/worker/src/services/IngestionService/utils.ts
index a703d54601..755817e46d 100644
--- a/worker/src/services/IngestionService/utils.ts
+++ b/worker/src/services/IngestionService/utils.ts
@@ -1,11 +1,8 @@
-import {
- JsonNested,
- convertRecordToJsonSchema,
- mergeJson,
-} from "@langfuse/shared";
-import { mergeWith } from "lodash";
-import { logger } from "@langfuse/shared/src/server";
+import { JsonNested } from "@langfuse/shared";
+import { mergeWith, merge } from "lodash";
+// Theoretically this returns Record<string, unknown>, but it would be hard to align the typing accordingly.
+// It's easier to pretend here and let JavaScript do its magic.
export const convertJsonSchemaToRecord = (
jsonSchema: JsonNested,
): Record<string, string> => {
@@ -23,25 +20,17 @@ export const convertJsonSchemaToRecord = (
return record;
}
- if (typeof jsonSchema === "object") {
- for (const key in jsonSchema) {
- const value = jsonSchema[key];
- record[key] = typeof value === "string" ? value : JSON.stringify(value);
- }
- }
- return record;
+ return jsonSchema as Record<string, string>;
};
-const mergeRecords = (
- record1?: Record<string, string>,
- record2?: Record<string, string>,
-): Record<string, string> | undefined => {
- const merged = mergeJson(
- record1 ? (convertRecordToJsonSchema(record1) ?? undefined) : undefined,
- record2 ? (convertRecordToJsonSchema(record2) ?? undefined) : undefined,
- );
-
- return merged ? convertJsonSchemaToRecord(merged) : undefined;
+export const convertRecordValuesToString = (
+ record: Record<string, unknown>,
+): Record<string, string> => {
+ for (const key in record) {
+ const value = record[key];
+ record[key] = typeof value === "string" ? value : JSON.stringify(value);
+ }
+ return record as Record<string, string>;
};
export function overwriteObject(
@@ -76,7 +65,7 @@ export function overwriteObject(
? b.metadata
: !b.metadata && a.metadata
? a.metadata
- : (mergeRecords(a.metadata, b.metadata) ?? {});
+ : (merge(a.metadata, b.metadata) ?? {});
if ("tags" in result) {
result.tags = Array.from(