🪢 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(prompt-experiments): set langfuse-native environment (#7573)
marliessophie0391b9a26333
diff --git a/packages/shared/src/server/index.ts b/packages/shared/src/server/index.tsindex edead2017b..e1f1e0b41c 100644--- a/packages/shared/src/server/index.ts+++ b/packages/shared/src/server/index.ts@@ -21,7 +21,6 @@ export * from "./clickhouse/schema";export * from "./repositories/definitions";export * from "../server/ingestion/types";export * from "./ingestion/processEventBatch";-export * from "../server/ingestion/types";export * from "../server/ingestion/validateAndInflateScore";export * from "./redis/redis";export * from "./redis/traceUpsert";diff --git a/packages/shared/src/server/ingestion/processEventBatch.ts b/packages/shared/src/server/ingestion/processEventBatch.tsindex 6a29ceb968..59484afeb0 100644--- a/packages/shared/src/server/ingestion/processEventBatch.ts+++ b/packages/shared/src/server/ingestion/processEventBatch.ts@@ -21,7 +21,11 @@ import { logger } from "../logger";import { QueueJobs } from "../queues";import { IngestionQueue } from "../redis/ingestionQueue";import { redis } from "../redis/redis";-import { eventTypes, ingestionEvent, IngestionEventType } from "./types";+import {+ eventTypes,+ createIngestionEventSchema,+ IngestionEventType,+} from "./types";import {StorageService,StorageServiceFactory,@@ -75,18 +79,28 @@ const getDelay = (delay: number | null) => {return Math.min(5000, env.LANGFUSE_INGESTION_QUEUE_DELAY_MS);};+/**+ * Options for event batch processing.+ * @property delay - Delay in ms to wait before processing events in the batch.+ * @property source - Source of the events for metrics tracking (e.g., "otel", "api").+ * @property isLangfuseInternal - Whether the events are being ingested by Langfuse internally (e.g. traces created for prompt experiments).+ */+type ProcessEventBatchOptions = {+ delay?: number | null;+ source?: "api" | "otel";+ isLangfuseInternal?: boolean;+};+/*** Processes a batch of events.* @param input - Batch of IngestionEventType. Will validate the types first thing and return errors if they are invalid.* @param authCheck - AuthHeaderValidVerificationResult- * @param delay - (Optional) Delay in ms to wait before processing events in the batch.- * @param source - (Optional) Source of the events for metrics tracking (e.g., "otel", "api").+ * @param options - (Optional) Options for the event batch processing.*/export const processEventBatch = async (input: unknown[],authCheck: AuthHeaderValidVerificationResult,- delay: number | null = null,- source: "api" | "otel" = "api",+ options: ProcessEventBatchOptions = {},): Promise<{successes: { id: string; status: number }[];errors: {@@ -96,6 +110,8 @@ export const processEventBatch = async (error?: string;}[];}> => {+ const { delay = null, source = "api", isLangfuseInternal = false } = options;+// add context of api call to the spanconst currentSpan = getCurrentSpan();recordIncrement("langfuse.ingestion.event", input.length, { source });@@ -121,9 +137,10 @@ export const processEventBatch = async (const validationErrors: { id: string; error: unknown }[] = [];const authenticationErrors: { id: string; error: unknown }[] = [];- const batch: z.infer<typeof ingestionEvent>[] = input+ const ingestionSchema = createIngestionEventSchema(isLangfuseInternal);+ const batch: z.infer<typeof ingestionSchema>[] = input.flatMap((event) => {- const parsed = ingestionEvent.safeParse(event);+ const parsed = ingestionSchema.safeParse(event);if (!parsed.success) {validationErrors.push({id:@@ -302,7 +319,7 @@ const isAuthorized = (/*** Sorts a batch of ingestion events. Orders by: updating events last, sorted by timestamp asc.*/-const sortBatch = (batch: Array<z.infer<typeof ingestionEvent>>) => {+const sortBatch = (batch: IngestionEventType[]) => {const updateEvents: (typeof eventTypes)[keyof typeof eventTypes][] = [eventTypes.GENERATION_UPDATE,eventTypes.SPAN_UPDATE,diff --git a/packages/shared/src/server/ingestion/types.ts b/packages/shared/src/server/ingestion/types.tsindex 3f058bc9fc..693ae51cc6 100644--- a/packages/shared/src/server/ingestion/types.ts+++ b/packages/shared/src/server/ingestion/types.ts@@ -193,178 +193,41 @@ export const UsageDetails = z]).nullish();-export const EnvironmentName = z+const INTERNAL_ENVIRONMENT_NAME_REGEX_ERROR_MESSAGE =+ "Only alphanumeric lower case characters, hyphens, and underscores are allowed";++const ENVIRONMENT_NAME_REGEX_ERROR_MESSAGE =+ INTERNAL_ENVIRONMENT_NAME_REGEX_ERROR_MESSAGE ++ " and it must not start with 'langfuse'";++const PublicEnvironmentName = z.string().max(40, "Maximum length is 40 characters")- .regex(- /^(?!langfuse)[a-z0-9-_]+$/,- "Only alphanumeric lower case characters, hyphens, and underscores are allowed, and it must not start with 'langfuse'",- )+ .regex(/^(?!langfuse)[a-z0-9-_]+$/, ENVIRONMENT_NAME_REGEX_ERROR_MESSAGE).default("default");-// Using z.any instead of jsonSchema for input/output as we saw huge CPU overhead for large numeric arrays.-// With this setup parsing should be more lightweight and doesn't block other requests.-// As we allow plain values, arrays, and objects the JSON parse via bodyParser should suffice.-export const TraceBody = z.object({- id: idSchema.nullish(),- timestamp: stringDateTime,- name: z.string().max(1000).nullish(),- externalId: z.string().nullish(),- input: z.any().nullish(),- output: z.any().nullish(),- sessionId: z.string().nullish(),- userId: z.string().nullish(),- environment: EnvironmentName,- metadata: jsonSchema.nullish(),- release: z.string().nullish(),- version: z.string().nullish(),- public: z.boolean().nullish(),- tags: z.array(z.string()).nullish(),-});--export const OptionalObservationBody = z.object({- traceId: idSchema.nullish(),- environment: EnvironmentName,- name: z.string().nullish(),- startTime: stringDateTime,- metadata: jsonSchema.nullish(),- input: z.any().nullish(),- output: z.any().nullish(),- level: ObservationLevel.nullish(),- statusMessage: z.string().nullish(),- parentObservationId: z.string().nullish(),- version: z.string().nullish(),-});--export const CreateEventEvent = OptionalObservationBody.extend({- id: idSchema,-});--export const UpdateEventEvent = OptionalObservationBody.extend({- id: idSchema,-});--export const CreateSpanBody = CreateEventEvent.extend({- endTime: stringDateTime,-});--export const UpdateSpanBody = UpdateEventEvent.extend({- endTime: stringDateTime,-});--export const CreateGenerationBody = CreateSpanBody.extend({- completionStartTime: stringDateTime,- model: z.string().nullish(),- modelParameters: z- .record(- z.string(),- z- .union([- z.string(),- z.number(),- z.boolean(),- z.array(z.string()),- z.record(z.string(), z.string()),- ])- .nullish(),- )- .nullish(),- usage: usage,- usageDetails: UsageDetails,- costDetails: CostDetails,- promptName: z.string().nullish(),- promptVersion: z.number().int().nullish(),-}).refine((value) => {- // ensure that either promptName and promptVersion are set, or none-- if (!value.promptName && !value.promptVersion) return true;- if (value.promptName && value.promptVersion) return true;- return false;-});--export const UpdateGenerationBody = UpdateSpanBody.extend({- completionStartTime: stringDateTime,- model: z.string().nullish(),- modelParameters: z- .record(- z.string(),- z- .union([- z.string(),- z.number(),- z.boolean(),- z.array(z.string()),- z.record(z.string(), z.string()),- ])- .nullish(),- )- .nullish(),- usage: usage,- usageDetails: UsageDetails,- costDetails: CostDetails,- promptName: z.string().nullish(),- promptVersion: z.number().int().nullish(),-}).refine((value) => {- // ensure that either promptName and promptVersion are set, or none-- if (!value.promptName && !value.promptVersion) return true;- if (value.promptName && value.promptVersion) return true;- return false;-});+const InternalEnvironmentName = z+ .string()+ .max(40, "Maximum length is 40 characters")+ .regex(/^[a-z0-9-_]+$/, INTERNAL_ENVIRONMENT_NAME_REGEX_ERROR_MESSAGE)+ .default("default");-const BaseScoreBody = z.object({- id: idSchema.nullish(),- name: NonEmptyString,- traceId: z.string().nullish(),- sessionId: z.string().nullish(),- datasetRunId: z.string().nullish(),- environment: EnvironmentName,- observationId: z.string().nullish(),- comment: z.string().nullish(),- metadata: jsonSchema.nullish(),- source: z- .enum(["API", "EVAL", "ANNOTATION"])- .default("API" as ScoreSourceType),-});+/** @deprecated Use PublicEnvironmentName or InternalEnvironmentName instead */+export const EnvironmentName = PublicEnvironmentName;-/**- * ScoreBody exactly mirrors `PostScoresBody` in the public API. Please refer there for source of truth.- */-export const ScoreBody = applyScoreValidation(- z.discriminatedUnion("dataType", [- BaseScoreBody.merge(- z.object({- value: z.number(),- dataType: z.literal("NUMERIC"),- configId: z.string().nullish(),- }),- ),- BaseScoreBody.merge(- z.object({- value: z.string(),- dataType: z.literal("CATEGORICAL"),- configId: z.string().nullish(),- }),- ),- BaseScoreBody.merge(- z.object({- value: z.number().refine((value) => value === 0 || value === 1, {- message:- "Value must be a number equal to either 0 or 1 for data type BOOLEAN",- }),- dataType: z.literal("BOOLEAN"),- configId: z.string().nullish(),- }),- ),- BaseScoreBody.merge(- z.object({- value: z.union([z.string(), z.number()]),- dataType: z.undefined(),- configId: z.string().nullish(),- }),- ),- ]),-);+export const eventTypes = {+ TRACE_CREATE: "trace-create",+ SCORE_CREATE: "score-create",+ EVENT_CREATE: "event-create",+ SPAN_CREATE: "span-create",+ SPAN_UPDATE: "span-update",+ GENERATION_CREATE: "generation-create",+ GENERATION_UPDATE: "generation-update",+ SDK_LOG: "sdk-log",+ // LEGACY, only required for backwards compatibility+ OBSERVATION_CREATE: "observation-create",+ OBSERVATION_UPDATE: "observation-update",+} as const;// LEGACY, only required for backwards compatibilityexport const LegacySpanPostSchema = z.object({@@ -475,83 +338,328 @@ export const SdkLogEvent = z.object({id: z.string().nullish(), // Not used, but makes downstream processing easier.});-export const eventTypes = {- TRACE_CREATE: "trace-create",- SCORE_CREATE: "score-create",- EVENT_CREATE: "event-create",- SPAN_CREATE: "span-create",- SPAN_UPDATE: "span-update",- GENERATION_CREATE: "generation-create",- GENERATION_UPDATE: "generation-update",- SDK_LOG: "sdk-log",- // LEGACY, only required for backwards compatibility- OBSERVATION_CREATE: "observation-create",- OBSERVATION_UPDATE: "observation-update",-} as const;+// Using z.any instead of jsonSchema for input/output as we saw huge CPU overhead for large numeric arrays.+// With this setup parsing should be more lightweight and doesn't block other requests.+// As we allow plain values, arrays, and objects the JSON parse via bodyParser should suffice.-const base = z.object({- id: idSchema,- timestamp: z.string().datetime({ offset: true }),- metadata: jsonSchema.nullish(),-});-export const traceEvent = base.extend({- type: z.literal(eventTypes.TRACE_CREATE),- body: TraceBody,-});-export type TraceEventType = z.infer<typeof traceEvent>;+// Complete schema factory - single source of truth for ALL schemas+const createAllIngestionSchemas = (+ environmentSchema: z.ZodDefault<z.ZodString>,+) => {+ // Base schemas with environment+ const TraceBody = z.object({+ id: idSchema.nullish(),+ timestamp: stringDateTime,+ name: z.string().max(1000).nullish(),+ externalId: z.string().nullish(),+ input: z.any().nullish(),+ output: z.any().nullish(),+ sessionId: z.string().nullish(),+ userId: z.string().nullish(),+ environment: environmentSchema,+ metadata: jsonSchema.nullish(),+ release: z.string().nullish(),+ version: z.string().nullish(),+ public: z.boolean().nullish(),+ tags: z.array(z.string()).nullish(),+ });-export const eventCreateEvent = base.extend({- type: z.literal(eventTypes.EVENT_CREATE),- body: CreateEventEvent,-});-export const spanCreateEvent = base.extend({- type: z.literal(eventTypes.SPAN_CREATE),- body: CreateSpanBody,-});-export const spanUpdateEvent = base.extend({- type: z.literal(eventTypes.SPAN_UPDATE),- body: UpdateSpanBody,-});-export const generationCreateEvent = base.extend({- type: z.literal(eventTypes.GENERATION_CREATE),- body: CreateGenerationBody,-});-export const generationUpdateEvent = base.extend({- type: z.literal(eventTypes.GENERATION_UPDATE),- body: UpdateGenerationBody,-});-export const scoreEvent = base.extend({- type: z.literal(eventTypes.SCORE_CREATE),- body: ScoreBody,-});-export type ScoreEventType = z.infer<typeof scoreEvent>;-export const sdkLogEvent = base.extend({- type: z.literal(eventTypes.SDK_LOG),- body: SdkLogEvent,-});-export const legacyObservationCreateEvent = base.extend({- type: z.literal(eventTypes.OBSERVATION_CREATE),- body: LegacyObservationBody,-});-export const legacyObservationUpdateEvent = base.extend({- type: z.literal(eventTypes.OBSERVATION_UPDATE),- body: LegacyObservationBody,-});+ const OptionalObservationBody = z.object({+ traceId: idSchema.nullish(),+ environment: environmentSchema,+ name: z.string().nullish(),+ startTime: stringDateTime,+ metadata: jsonSchema.nullish(),+ input: z.any().nullish(),+ output: z.any().nullish(),+ level: ObservationLevel.nullish(),+ statusMessage: z.string().nullish(),+ parentObservationId: z.string().nullish(),+ version: z.string().nullish(),+ });-export const ingestionEvent = z.discriminatedUnion("type", [- traceEvent,- scoreEvent,- eventCreateEvent,- spanCreateEvent,- spanUpdateEvent,- generationCreateEvent,- generationUpdateEvent,- sdkLogEvent,- // LEGACY, only required for backwards compatibility- legacyObservationCreateEvent,- legacyObservationUpdateEvent,-]);+ // Derivative schemas+ const CreateEventEvent = OptionalObservationBody.extend({+ id: idSchema,+ });++ const UpdateEventEvent = OptionalObservationBody.extend({+ id: idSchema,+ });++ const CreateSpanBody = CreateEventEvent.extend({+ endTime: stringDateTime,+ });++ const UpdateSpanBody = UpdateEventEvent.extend({+ endTime: stringDateTime,+ });++ const CreateGenerationBody = CreateSpanBody.extend({+ completionStartTime: stringDateTime,+ model: z.string().nullish(),+ modelParameters: z+ .record(+ z.string(),+ z+ .union([+ z.string(),+ z.number(),+ z.boolean(),+ z.array(z.string()),+ z.record(z.string(), z.string()),+ ])+ .nullish(),+ )+ .nullish(),+ usage: usage,+ usageDetails: UsageDetails,+ costDetails: CostDetails,+ promptName: z.string().nullish(),+ promptVersion: z.number().int().nullish(),+ }).refine((value) => {+ // ensure that either promptName and promptVersion are set, or none+ if (!value.promptName && !value.promptVersion) return true;+ if (value.promptName && value.promptVersion) return true;+ return false;+ });++ const UpdateGenerationBody = UpdateSpanBody.extend({+ completionStartTime: stringDateTime,+ model: z.string().nullish(),+ modelParameters: z+ .record(+ z.string(),+ z+ .union([+ z.string(),+ z.number(),+ z.boolean(),+ z.array(z.string()),+ z.record(z.string(), z.string()),+ ])+ .nullish(),+ )+ .nullish(),+ usage: usage,+ usageDetails: UsageDetails,+ costDetails: CostDetails,+ promptName: z.string().nullish(),+ promptVersion: z.number().int().nullish(),+ }).refine((value) => {+ // ensure that either promptName and promptVersion are set, or none+ if (!value.promptName && !value.promptVersion) return true;+ if (value.promptName && value.promptVersion) return true;+ return false;+ });++ const BaseScoreBody = z.object({+ id: idSchema.nullish(),+ name: NonEmptyString,+ traceId: z.string().nullish(),+ sessionId: z.string().nullish(),+ datasetRunId: z.string().nullish(),+ environment: environmentSchema,+ observationId: z.string().nullish(),+ comment: z.string().nullish(),+ metadata: jsonSchema.nullish(),+ source: z+ .enum(["API", "EVAL", "ANNOTATION"])+ .default("API" as ScoreSourceType),+ });++ const ScoreBody = applyScoreValidation(+ z.discriminatedUnion("dataType", [+ BaseScoreBody.merge(+ z.object({+ value: z.number(),+ dataType: z.literal("NUMERIC"),+ configId: z.string().nullish(),+ }),+ ),+ BaseScoreBody.merge(+ z.object({+ value: z.string(),+ dataType: z.literal("CATEGORICAL"),+ configId: z.string().nullish(),+ }),+ ),+ BaseScoreBody.merge(+ z.object({+ value: z.number().refine((value) => value === 0 || value === 1, {+ message:+ "Value must be a number equal to either 0 or 1 for data type BOOLEAN",+ }),+ dataType: z.literal("BOOLEAN"),+ configId: z.string().nullish(),+ }),+ ),+ BaseScoreBody.merge(+ z.object({+ value: z.union([z.string(), z.number()]),+ dataType: z.undefined(),+ configId: z.string().nullish(),+ }),+ ),+ ]),+ );++ // Event schemas+ const base = z.object({+ id: idSchema,+ timestamp: z.string().datetime({ offset: true }),+ metadata: jsonSchema.nullish(),+ });++ const traceEvent = base.extend({+ type: z.literal(eventTypes.TRACE_CREATE),+ body: TraceBody,+ });++ const eventCreateEvent = base.extend({+ type: z.literal(eventTypes.EVENT_CREATE),+ body: CreateEventEvent,+ });++ const spanCreateEvent = base.extend({+ type: z.literal(eventTypes.SPAN_CREATE),+ body: CreateSpanBody,+ });++ const spanUpdateEvent = base.extend({+ type: z.literal(eventTypes.SPAN_UPDATE),+ body: UpdateSpanBody,+ });++ const generationCreateEvent = base.extend({+ type: z.literal(eventTypes.GENERATION_CREATE),+ body: CreateGenerationBody,+ });++ const generationUpdateEvent = base.extend({+ type: z.literal(eventTypes.GENERATION_UPDATE),+ body: UpdateGenerationBody,+ });++ const scoreEvent = base.extend({+ type: z.literal(eventTypes.SCORE_CREATE),+ body: ScoreBody,+ });++ const sdkLogEvent = base.extend({+ type: z.literal(eventTypes.SDK_LOG),+ body: SdkLogEvent,+ });++ const legacyObservationCreateEvent = base.extend({+ type: z.literal(eventTypes.OBSERVATION_CREATE),+ body: LegacyObservationBody,+ });++ const legacyObservationUpdateEvent = base.extend({+ type: z.literal(eventTypes.OBSERVATION_UPDATE),+ body: LegacyObservationBody,+ });++ const ingestionEvent = z.discriminatedUnion("type", [+ traceEvent,+ scoreEvent,+ eventCreateEvent,+ spanCreateEvent,+ spanUpdateEvent,+ generationCreateEvent,+ generationUpdateEvent,+ sdkLogEvent,+ // LEGACY, only required for backwards compatibility+ legacyObservationCreateEvent,+ legacyObservationUpdateEvent,+ ]);++ return {+ // Body schemas+ TraceBody,+ OptionalObservationBody,+ CreateEventEvent,+ UpdateEventEvent,+ CreateSpanBody,+ UpdateSpanBody,+ CreateGenerationBody,+ UpdateGenerationBody,+ BaseScoreBody,+ ScoreBody,+ // Event schemas+ traceEvent,+ eventCreateEvent,+ spanCreateEvent,+ spanUpdateEvent,+ generationCreateEvent,+ generationUpdateEvent,+ scoreEvent,+ sdkLogEvent,+ legacyObservationCreateEvent,+ legacyObservationUpdateEvent,+ // Complete schema+ ingestionEvent,+ };+};++// Create both public and internal schema instances+const publicSchemas = createAllIngestionSchemas(PublicEnvironmentName);+const internalSchemas = createAllIngestionSchemas(InternalEnvironmentName);++// Export individual schemas for backwards compatibility+export const TraceBody = publicSchemas.TraceBody;+export const OptionalObservationBody = publicSchemas.OptionalObservationBody;+export const CreateEventEvent = publicSchemas.CreateEventEvent;+export const UpdateEventEvent = publicSchemas.UpdateEventEvent;+export const CreateSpanBody = publicSchemas.CreateSpanBody;+export const UpdateSpanBody = publicSchemas.UpdateSpanBody;+export const CreateGenerationBody = publicSchemas.CreateGenerationBody;+export const UpdateGenerationBody = publicSchemas.UpdateGenerationBody;+export const BaseScoreBody = publicSchemas.BaseScoreBody;++/**+ * ScoreBody exactly mirrors `PostScoresBody` in the public API. Please refer there for source of truth.+ */+export const ScoreBody = publicSchemas.ScoreBody;++// Export individual event schemas for backwards compatibility+export const traceEvent = publicSchemas.traceEvent;+export const eventCreateEvent = publicSchemas.eventCreateEvent;+export const spanCreateEvent = publicSchemas.spanCreateEvent;+export const spanUpdateEvent = publicSchemas.spanUpdateEvent;+export const generationCreateEvent = publicSchemas.generationCreateEvent;+export const generationUpdateEvent = publicSchemas.generationUpdateEvent;+export const scoreEvent = publicSchemas.scoreEvent;+export const sdkLogEvent = publicSchemas.sdkLogEvent;+export const legacyObservationCreateEvent =+ publicSchemas.legacyObservationCreateEvent;+export const legacyObservationUpdateEvent =+ publicSchemas.legacyObservationUpdateEvent;++/** @deprecated Use createIngestionEventSchema() instead */+export const ingestionEvent = publicSchemas.ingestionEvent;++/**+ * Type definitions for both schema variants (public and internal).+ * These types are equivalent to the return types of createIngestionEventSchema() and all exported schemas,+ * since the factory patterns only differ in environment validation rules, not in the actual TypeScript types.+ * The environment field remains `string` in all cases - only the validation logic differs.+ */export type IngestionEventType = z.infer<typeof ingestionEvent>;+export type TraceEventType = z.infer<typeof traceEvent>;+export type ScoreEventType = z.infer<typeof scoreEvent>;++/**+ * Creates an ingestion event schema with appropriate environment validation.+ * @param isLangfuseInternal - Whether the events are being ingested by Langfuse internally (e.g. traces created for prompt experiments).+ * @returns The ingestion event schema.+ */+export const createIngestionEventSchema = (isLangfuseInternal = false) => {+ return isLangfuseInternal+ ? internalSchemas.ingestionEvent+ : publicSchemas.ingestionEvent;+};export type ObservationEvent =| z.infer<typeof legacyObservationCreateEvent>diff --git a/packages/shared/src/server/llm/fetchLLMCompletion.ts b/packages/shared/src/server/llm/fetchLLMCompletion.tsindex 590176d41d..a18481f96a 100644--- a/packages/shared/src/server/llm/fetchLLMCompletion.ts+++ b/packages/shared/src/server/llm/fetchLLMCompletion.ts@@ -137,7 +137,7 @@ export async function fetchLLMCompletion(const handler = new CallbackHandler({_projectId: traceParams.projectId,_isLocalEventExportEnabled: true,- tags: traceParams.tags,+ environment: traceParams.environment,});finalCallbacks.push(handler);@@ -149,6 +149,7 @@ export async function fetchLLMCompletion(await processEventBatch(JSON.parse(JSON.stringify(events)), // stringify to emulate network event batch from network calltraceParams.authCheck,+ { isLangfuseInternal: true },);} catch (e) {logger.error("Failed to process traced events", { error: e });diff --git a/packages/shared/src/server/llm/types.ts b/packages/shared/src/server/llm/types.tsindex 8e716a32ee..1d924c7c8c 100644--- a/packages/shared/src/server/llm/types.ts+++ b/packages/shared/src/server/llm/types.ts@@ -419,11 +419,17 @@ export type LLMApiKey =? z.infer<typeof LLMApiKeySchema>: never;+// NOTE: This string is whitelisted in the TS SDK to allow ingestion of traces by Langfuse. Please mirror edits to this string in https://github.com/langfuse/langfuse-js/blob/main/langfuse-core/src/index.ts.+export const PROMPT_EXPERIMENT_ENVIRONMENT =+ "langfuse-prompt-experiment" as const;++type PromptExperimentEnvironment = typeof PROMPT_EXPERIMENT_ENVIRONMENT;+export type TraceParams = {traceName: string;traceId: string;projectId: string;- tags: string[];+ environment: PromptExperimentEnvironment;tokenCountDelegate: TokenCountDelegate;authCheck: AuthHeaderValidVerificationResult;};diff --git a/web/src/__tests__/server/api/otel/otelMapping.servertest.ts b/web/src/__tests__/server/api/otel/otelMapping.servertest.tsindex c657967b1f..2d358dbdca 100644--- a/web/src/__tests__/server/api/otel/otelMapping.servertest.ts+++ b/web/src/__tests__/server/api/otel/otelMapping.servertest.ts@@ -1,5 +1,5 @@import { OtelIngestionProcessor } from "@/src/features/otel/server/OtelIngestionProcessor";-import { ingestionEvent } from "@langfuse/shared/src/server";+import { createIngestionEventSchema } from "@langfuse/shared/src/server";// Test helper function to maintain backward compatibility with existing tests// This mimics the old convertOtelSpanToIngestionEvent function signature@@ -771,9 +771,8 @@ describe("OTel Resource Span Mapping", () => {// Then// Will throw an error if the parsing fails- const parsedEvents = langfuseEvents.map((event) =>- ingestionEvent.parse(event),- );+ const schema = createIngestionEventSchema();+ const parsedEvents = langfuseEvents.map((event) => schema.parse(event));expect(parsedEvents).toHaveLength(2);});@@ -890,9 +889,8 @@ describe("OTel Resource Span Mapping", () => {// Then// Will throw an error if the parsing fails- const parsedEvents = langfuseEvents.map((event) =>- ingestionEvent.parse(event),- );+ const schema = createIngestionEventSchema();+ const parsedEvents = langfuseEvents.map((event) => schema.parse(event));expect(parsedEvents).toHaveLength(2);});@@ -1011,9 +1009,8 @@ describe("OTel Resource Span Mapping", () => {// Then// Will throw an error if the parsing fails- const parsedEvents = langfuseEvents.map((event) =>- ingestionEvent.parse(event),- );+ const schema = createIngestionEventSchema();+ const parsedEvents = langfuseEvents.map((event) => schema.parse(event));expect(parsedEvents).toHaveLength(2);// Check that input contains both system and user messagesdiff --git a/web/src/pages/api/public/otel/v1/traces/index.ts b/web/src/pages/api/public/otel/v1/traces/index.tsindex 641ab074e8..7ea750e50a 100644--- a/web/src/pages/api/public/otel/v1/traces/index.ts+++ b/web/src/pages/api/public/otel/v1/traces/index.ts@@ -99,7 +99,7 @@ export default withMiddlewares({// We set a delay of 0 for OTel, as we never expect updates.// We also set the source to "otel" which helps us with metric tracking and skipping list calls for S3.- return processEventBatch(events, auth, 0, "otel");+ return processEventBatch(events, auth, { delay: 0, source: "otel" });},}),});diff --git a/worker/src/__tests__/experimentsService.test.ts b/worker/src/__tests__/experimentsService.test.tsindex def456c4b5..a1729669a8 100644--- a/worker/src/__tests__/experimentsService.test.ts+++ b/worker/src/__tests__/experimentsService.test.ts@@ -6,6 +6,7 @@ import { pruneDatabase } from "./utils";import { LLMAdapter } from "@langfuse/shared";import { encrypt } from "@langfuse/shared/encryption";import { callLLM } from "../features/utilities";+import { PROMPT_EXPERIMENT_ENVIRONMENT } from "@langfuse/shared/src/server";vi.mock("../features/utilities", () => ({callLLM: vi.fn().mockResolvedValue({ id: "test-id" }),@@ -592,7 +593,7 @@ describe("create experiment job calls with langfuse server side tracing", asyncexpect.any(String),expect.any(String),expect.objectContaining({- tags: ["langfuse-prompt-experiment"],+ environment: PROMPT_EXPERIMENT_ENVIRONMENT,traceName: expect.stringMatching(/^dataset-run-item-/),traceId: expect.any(String),projectId: mockEvent.projectId,diff --git a/worker/src/features/experiments/experimentService.ts b/worker/src/features/experiments/experimentService.tsindex c48717cf9a..f4686adbda 100644--- a/worker/src/features/experiments/experimentService.ts+++ b/worker/src/features/experiments/experimentService.ts@@ -10,6 +10,8 @@ import {ChatMessageType,type ChatMessage,PromptService,+ PROMPT_EXPERIMENT_ENVIRONMENT,+ TraceParams,compileChatMessages,extractPlaceholderNames,type MessagePlaceholderValues,@@ -350,8 +352,8 @@ export const createExperimentJob = async ({* LLM MODEL CALL *********************/- const traceParams = {- tags: ["langfuse-prompt-experiment"], // LFE-2917: filter out any trace in trace upsert queue that has this tag set+ const traceParams: Omit<TraceParams, "tokenCountDelegate"> = {+ environment: PROMPT_EXPERIMENT_ENVIRONMENT,traceName: `dataset-run-item-${runItem.id.slice(0, 5)}`,traceId: newTraceId,projectId: event.projectId,diff --git a/worker/src/services/IngestionService/tests/IngestionService.integration.test.ts b/worker/src/services/IngestionService/tests/IngestionService.integration.test.tsindex a41076895c..7f1c567af9 100644--- a/worker/src/services/IngestionService/tests/IngestionService.integration.test.ts+++ b/worker/src/services/IngestionService/tests/IngestionService.integration.test.ts@@ -14,7 +14,7 @@ import {TraceEventType,traceRecordReadSchema,TraceRecordReadType,- ingestionEvent,+ createIngestionEventSchema,} from "@langfuse/shared/src/server";import { pruneDatabase } from "../../../__tests__/utils";import waitForExpect from "wait-for-expect";@@ -25,11 +25,11 @@ import { Cluster } from "ioredis";const projectId = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";const environment = "default";-const IngestionEventBatchSchema = z.array(ingestionEvent);describe("Ingestion end-to-end tests", () => {let ingestionService: IngestionService;let clickhouseWriter: ClickhouseWriter;+ let IngestionEventBatchSchema: z.ZodType<any>;beforeEach(async () => {if (!redis) throw new Error("Redis not initialized");@@ -49,6 +49,8 @@ describe("Ingestion end-to-end tests", () => {clickhouseWriter,clickhouseClient(),);++ IngestionEventBatchSchema = z.array(createIngestionEventSchema());});afterEach(async () => {