Skip to content

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

feat: process environment in ingestion pipeline (#5671)

Steffen Schmitz0b7dd5a1a776
diff --git a/packages/shared/src/features/annotation/types.ts b/packages/shared/src/features/annotation/types.ts
index 4733798005..9ddce14a7e 100644
--- a/packages/shared/src/features/annotation/types.ts
+++ b/packages/shared/src/features/annotation/types.ts
@@ -28,6 +28,7 @@ const BooleanData = z.object({
const CreateAnnotationScoreBase = z.object({
name: z.string(),
projectId: z.string(),
+ environment: z.string().nullish(),
traceId: z.string(),
configId: z.string().optional(),
observationId: z.string().optional(),
diff --git a/packages/shared/src/features/scores/scoreTypes.ts b/packages/shared/src/features/scores/scoreTypes.ts
index 81a9e50d08..126f1b1f5e 100644
--- a/packages/shared/src/features/scores/scoreTypes.ts
+++ b/packages/shared/src/features/scores/scoreTypes.ts
@@ -45,6 +45,7 @@ const ScoreBase = z.object({
id: z.string(),
timestamp: z.coerce.date(),
projectId: z.string(),
+ environment: z.string(),
name: z.string(),
source: z.enum(ScoreSource),
authorUserId: z.string().nullish(),
diff --git a/packages/shared/src/server/ingestion/types.ts b/packages/shared/src/server/ingestion/types.ts
index c0f86972fc..fcbd22d5df 100644
--- a/packages/shared/src/server/ingestion/types.ts
+++ b/packages/shared/src/server/ingestion/types.ts
@@ -118,6 +118,15 @@ export const UsageOrCostDetails = z
.union([OpenAIUsageSchema, RawUsageOrCostDetails])
.nullish();
+export const EnvironmentName = 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'",
+ )
+ .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.
@@ -130,6 +139,7 @@ export const TraceBody = z.object({
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(),
@@ -139,6 +149,7 @@ export const TraceBody = z.object({
export const OptionalObservationBody = z.object({
traceId: z.string().nullish(),
+ environment: EnvironmentName,
name: z.string().nullish(),
startTime: stringDateTime,
metadata: jsonSchema.nullish(),
@@ -230,6 +241,7 @@ const BaseScoreBody = z.object({
id: z.string().nullish(),
name: NonEmptyString,
traceId: z.string(),
+ environment: EnvironmentName,
observationId: z.string().nullish(),
comment: z.string().nullish(),
source: z
@@ -383,18 +395,6 @@ export const SdkLogEvent = z.object({
id: z.string().nullish(), // Not used, but makes downstream processing easier.
});
-// definitions for the ingestion API
-
-export const observationTypes = [
- "observation-create",
- "observation-update",
- "generation-create",
- "generation-update",
- "span-create",
- "span-update",
- "event-create",
-];
-
export const eventTypes = {
TRACE_CREATE: "trace-create",
SCORE_CREATE: "score-create",
@@ -474,27 +474,12 @@ export const ingestionEvent = z.discriminatedUnion("type", [
export type IngestionEventType = z.infer<typeof ingestionEvent>;
export const ingestionBatchEvent = z.array(ingestionEvent);
-export type IngestionBatchEventType = z.infer<typeof ingestionBatchEvent>;
-
-export const ingestionEventWithProjectId = ingestionEvent.and(
- z.object({ projectId: z.string() }),
-);
-export type IngestionEventWithProjectIdType = z.infer<
- typeof ingestionEventWithProjectId
->;
export const ingestionApiSchema = z.object({
batch: ingestionBatchEvent,
metadata: jsonSchema.nullish(),
});
-export const ingestionApiSchemaWithProjectId = ingestionApiSchema.extend({
- projectId: z.string(),
-});
-export type IngestionApiSchemaWithProjectId = z.infer<
- typeof ingestionApiSchemaWithProjectId
->;
-
export type ObservationEvent =
| z.infer<typeof legacyObservationCreateEvent>
| z.infer<typeof legacyObservationUpdateEvent>
diff --git a/packages/shared/src/server/repositories/definitions.ts b/packages/shared/src/server/repositories/definitions.ts
index e059e8e360..56c6d6d7d7 100644
--- a/packages/shared/src/server/repositories/definitions.ts
+++ b/packages/shared/src/server/repositories/definitions.ts
@@ -36,6 +36,7 @@ export const observationRecordBaseSchema = z.object({
project_id: z.string(),
type: z.string(),
parent_observation_id: z.string().nullish(),
+ environment: z.string(),
name: z.string().nullish(),
metadata: z.record(z.string()),
level: z.string().nullish(),
@@ -52,9 +53,6 @@ export const observationRecordBaseSchema = z.object({
prompt_version: z.number().nullish(),
is_deleted: z.number(),
});
-export type ObservationRecordBaseType = z.infer<
- typeof observationRecordBaseSchema
->;
export const observationRecordReadSchema = observationRecordBaseSchema.extend({
created_at: clickhouseStringDateSchema,
@@ -98,6 +96,7 @@ export const traceRecordBaseSchema = z.object({
release: z.string().nullish(),
version: z.string().nullish(),
project_id: z.string(),
+ environment: z.string(),
public: z.boolean(),
bookmarked: z.boolean(),
tags: z.array(z.string()),
@@ -106,7 +105,6 @@ export const traceRecordBaseSchema = z.object({
session_id: z.string().nullish(),
is_deleted: z.number(),
});
-export type TraceRecordBaseType = z.infer<typeof traceRecordBaseSchema>;
export const traceRecordReadSchema = traceRecordBaseSchema.extend({
timestamp: clickhouseStringDateSchema,
@@ -129,6 +127,7 @@ export const scoreRecordBaseSchema = z.object({
project_id: z.string(),
trace_id: z.string(),
observation_id: z.string().nullish(),
+ environment: z.string(),
name: z.string(),
value: z.number().nullish(),
source: z.string(),
@@ -140,7 +139,6 @@ export const scoreRecordBaseSchema = z.object({
queue_id: z.string().nullish(),
is_deleted: z.number(),
});
-export type ScoreRecordBaseType = z.infer<typeof scoreRecordBaseSchema>;
export const scoreRecordReadSchema = scoreRecordBaseSchema.extend({
created_at: clickhouseStringDateSchema,
@@ -246,6 +244,7 @@ export const convertPostgresTraceToInsert = (
: Array.isArray(trace.metadata)
? { metadata: trace.metadata }
: trace.metadata,
+ environment: trace.environment,
release: trace.release,
version: trace.version,
project_id: trace.project_id,
@@ -282,6 +281,7 @@ export const convertPostgresObservationToInsert = (
project_id: observation.project_id,
type: observation.type,
parent_observation_id: observation.parent_observation_id,
+ environment: observation.environment,
start_time: observation.start_time?.getTime(),
end_time: observation.end_time?.getTime(),
name: observation.name,
@@ -345,6 +345,7 @@ export const convertPostgresScoreToInsert = (
project_id: score.project_id,
trace_id: score.trace_id,
observation_id: score.observation_id,
+ environment: score.environment,
name: score.name,
value: score.value,
source: score.source,
diff --git a/packages/shared/src/server/repositories/observations.ts b/packages/shared/src/server/repositories/observations.ts
index 4eed945a2a..d688529ecc 100644
--- a/packages/shared/src/server/repositories/observations.ts
+++ b/packages/shared/src/server/repositories/observations.ts
@@ -114,6 +114,7 @@ export const getObservationsViewForTrace = async (
project_id,
type,
parent_observation_id,
+ environment,
start_time,
end_time,
name,
@@ -342,6 +343,7 @@ const getObservationByIdInternal = async (
id,
trace_id,
project_id,
+ environment,
type,
parent_observation_id,
start_time,
diff --git a/packages/shared/src/server/repositories/observations_converters.ts b/packages/shared/src/server/repositories/observations_converters.ts
index 9577c0df3c..409515624a 100644
--- a/packages/shared/src/server/repositories/observations_converters.ts
+++ b/packages/shared/src/server/repositories/observations_converters.ts
@@ -55,6 +55,7 @@ export const convertObservation = (
traceId: record.trace_id ?? null,
projectId: record.project_id,
type: record.type as ObservationType,
+ environment: record.environment,
parentObservationId: record.parent_observation_id ?? null,
startTime: parseClickhouseUTCDateTimeFormat(record.start_time),
endTime: record.end_time
diff --git a/packages/shared/src/server/repositories/scores.ts b/packages/shared/src/server/repositories/scores.ts
index 05012cbca9..6381221875 100644
--- a/packages/shared/src/server/repositories/scores.ts
+++ b/packages/shared/src/server/repositories/scores.ts
@@ -372,6 +372,7 @@ export const getScoresUiTable = async (props: {
const rows = await getScoresUiGeneric<{
id: string;
project_id: string;
+ environment: string;
name: string;
value: number;
string_value: string | null;
@@ -396,6 +397,7 @@ export const getScoresUiTable = async (props: {
select: `
s.id,
s.project_id,
+ s.environment,
s.name,
s.value,
s.string_value,
@@ -424,6 +426,7 @@ export const getScoresUiTable = async (props: {
return rows.map((row) => ({
projectId: row.project_id,
+ environment: row.environment,
authorUserId: row.author_user_id,
traceId: row.trace_id,
observationId: row.observation_id,
diff --git a/packages/shared/src/server/repositories/scores_converters.ts b/packages/shared/src/server/repositories/scores_converters.ts
index b52a586735..be6bfb82e8 100644
--- a/packages/shared/src/server/repositories/scores_converters.ts
+++ b/packages/shared/src/server/repositories/scores_converters.ts
@@ -17,6 +17,7 @@ export const convertToScore = (row: ScoreRecordReadType): Score => {
id: row.id,
timestamp: new Date(row.timestamp),
projectId: row.project_id,
+ environment: row.environment,
traceId: row.trace_id,
observationId: row.observation_id ?? null,
name: row.name,
diff --git a/packages/shared/src/server/repositories/traces_converters.ts b/packages/shared/src/server/repositories/traces_converters.ts
index 2185906aaf..7a4c604016 100644
--- a/packages/shared/src/server/repositories/traces_converters.ts
+++ b/packages/shared/src/server/repositories/traces_converters.ts
@@ -14,6 +14,7 @@ export const convertTraceDomainToClickhouse = (
name: trace.name,
user_id: trace.userId,
metadata: trace.metadata as Record<string, string>,
+ environment: trace.environment,
release: trace.release,
version: trace.version,
project_id: trace.projectId,
@@ -38,6 +39,7 @@ export const convertClickhouseToDomain = (
projectId: record.project_id,
name: record.name ?? null,
timestamp: parseClickhouseUTCDateTimeFormat(record.timestamp),
+ environment: record.environment,
tags: record.tags,
bookmarked: record.bookmarked,
release: record.release ?? null,
diff --git a/packages/shared/src/server/repositories/types.ts b/packages/shared/src/server/repositories/types.ts
index 548836f6d6..ed64681c6e 100644
--- a/packages/shared/src/server/repositories/types.ts
+++ b/packages/shared/src/server/repositories/types.ts
@@ -31,6 +31,7 @@ export type Observation = {
id: string;
traceId: string | null;
projectId: string;
+ environment: string;
type: ObservationType;
startTime: Date;
endTime: Date | null;
@@ -69,6 +70,7 @@ export type ObservationView = {
type: ObservationType;
startTime: Date;
endTime: Date | null;
+ environment: string;
name: string | null;
metadata: Prisma.JsonValue | null;
parentObservationId: string | null;
@@ -104,6 +106,7 @@ export type Score = {
id: string;
timestamp: Date;
projectId: string;
+ environment: string;
name: string;
value: number | null;
source: ScoreSourceType;
@@ -124,6 +127,7 @@ export type Trace = {
timestamp: Date;
name: string | null;
userId: string | null;
+ environment: string;
metadata: Prisma.JsonValue | null;
release: string | null;
version: string | null;
diff --git a/packages/shared/src/server/test-utils/tracing-factory.ts b/packages/shared/src/server/test-utils/tracing-factory.ts
index d1674d6e00..94feea060c 100644
--- a/packages/shared/src/server/test-utils/tracing-factory.ts
+++ b/packages/shared/src/server/test-utils/tracing-factory.ts
@@ -11,6 +11,7 @@ export const createTrace = (trace: Partial<TraceRecordInsertType>) => {
project_id: v4(),
session_id: v4(),
timestamp: Date.now(),
+ environment: "default",
metadata: {
source: "API",
server: "Node",
@@ -38,6 +39,7 @@ export const createObservation = (
trace_id: v4(),
project_id: v4(),
type: "GENERATION",
+ environment: "default",
metadata: {
source: "API",
server: "Node",
@@ -76,6 +78,7 @@ export const createScore = (score: Partial<ScoreRecordInsertType>) => {
project_id: v4(),
trace_id: v4(),
observation_id: v4(),
+ environment: "default",
name: "test-score" + v4(),
timestamp: Date.now(),
value: 100.5,
diff --git a/web/src/__tests__/async/ingestion-api.servertest.ts b/web/src/__tests__/async/ingestion-api.servertest.ts
index 99411770ff..50d72bf683 100644
--- a/web/src/__tests__/async/ingestion-api.servertest.ts
+++ b/web/src/__tests__/async/ingestion-api.servertest.ts
@@ -54,6 +54,21 @@ describe("/api/public/ingestion API Endpoint", () => {
},
},
],
+ [
+ "non-default-environment",
+ {
+ id: randomUUID(),
+ type: "trace-create",
+ timestamp: new Date().toISOString(),
+ body: {
+ id: randomUUID(),
+ timestamp: new Date().toISOString(),
+ metadata: { hello: "world" },
+ input: ["hello", { world: "world" }, [1, 2, 3]],
+ environment: "production",
+ },
+ },
+ ],
])(
"should create traces via the ingestion API (%s)",
async (_name: string, entity: any) => {
@@ -71,6 +86,9 @@ describe("/api/public/ingestion API Endpoint", () => {
expect(trace!.metadata).toEqual(entity.body?.metadata ?? {});
expect(trace!.input).toEqual(entity.body?.input ?? null);
expect(trace!.output).toEqual(entity.body?.output ?? null);
+ expect(trace!.environment).toEqual(
+ entity.body?.environment ?? "default",
+ );
});
},
);
@@ -124,6 +142,23 @@ describe("/api/public/ingestion API Endpoint", () => {
},
},
],
+ [
+ "span-non-default-environment",
+ "SPAN",
+ {
+ id: randomUUID(),
+ type: "span-create",
+ timestamp: new Date().toISOString(),
+ body: {
+ id: randomUUID(),
+ traceId: randomUUID(),
+ startTime: new Date().toISOString(),
+ input: ["hello", { world: "world" }, [1, 2, 3]],
+ output: ["hello", { world: [2, 3, "test"] }, [1, 2, 3]],
+ environment: "production",
+ },
+ },
+ ],
])(
"should create observations via the ingestion API (%s)",
async (_name: string, type: string, entity: any) => {
@@ -146,6 +181,9 @@ describe("/api/public/ingestion API Endpoint", () => {
expect(observation!.input).toEqual(entity.body?.input ?? null);
expect(observation!.output).toEqual(entity.body?.output ?? null);
expect(observation!.type).toBe(type);
+ expect(observation!.environment).toEqual(
+ entity.body?.environment ?? "default",
+ );
});
},
);
@@ -166,6 +204,22 @@ describe("/api/public/ingestion API Endpoint", () => {
},
},
],
+ [
+ "non-default-environment",
+ {
+ id: randomUUID(),
+ type: "score-create",
+ timestamp: new Date().toISOString(),
+ body: {
+ id: randomUUID(),
+ name: "score-name",
+ traceId: randomUUID(),
+ value: 100.5,
+ observationId: randomUUID(),
+ environment: "production",
+ },
+ },
+ ],
])(
"should create scores via the ingestion API (%s)",
async (_name: string, entity: any) => {
@@ -181,6 +235,9 @@ describe("/api/public/ingestion API Endpoint", () => {
expect(score!.id).toBe(entity.body.id);
expect(score!.projectId).toBe(projectId);
expect(score!.value).toEqual(100.5);
+ expect(score!.environment).toEqual(
+ entity.body?.environment ?? "default",
+ );
});
},
);
@@ -218,6 +275,36 @@ describe("/api/public/ingestion API Endpoint", () => {
expect(response.body.errors[0].message).toBe("Invalid request data");
});
+ it.each([
+ "langfuse-test",
+ ".invalidcharacter!",
+ "incrediblylongstringwithmorethan40characters",
+ ])(
+ "should fail for invalid environments (%s)",
+ async (environment: string) => {
+ const entity = {
+ id: randomUUID(),
+ type: "score-create",
+ timestamp: new Date().toISOString(),
+ body: {
+ id: randomUUID(),
+ name: "score-name",
+ traceId: randomUUID(),
+ value: 100.5,
+ observationId: randomUUID(),
+ environment,
+ },
+ };
+
+ const response = await makeAPICall("POST", "/api/public/ingestion", {
+ batch: [entity],
+ });
+
+ expect(response.status).toBe(207);
+ expect(response.body.errors[0].status).toBe(400);
+ },
+ );
+
// Disabled until eventLog becomes the default behaviour.
it("should create a log entry for the S3 file", async () => {
const traceId = v4();
diff --git a/web/src/features/otel/server/index.ts b/web/src/features/otel/server/index.ts
index 1b53ecd837..7964525bcc 100644
--- a/web/src/features/otel/server/index.ts
+++ b/web/src/features/otel/server/index.ts
@@ -328,6 +328,9 @@ export const convertOtelSpanToIngestionEvent = (
attributes?.["langfuse.public"] === "true",
tags: attributes?.["langfuse.tags"] ?? [],
+ // TODO: Overwrite to OTel based mapping via LFE-4081
+ environment: "default",
+
// Input and Output
...extractInputAndOutput(span?.events ?? [], attributes),
};
@@ -354,6 +357,9 @@ export const convertOtelSpanToIngestionEvent = (
startTime: convertNanoTimestampToISO(span.startTimeUnixNano),
endTime: convertNanoTimestampToISO(span.endTimeUnixNano),
+ // TODO: Overwrite to OTel based mapping via LFE-4081
+ environment: "default",
+
// Additional fields
metadata: {
attributes,
diff --git a/web/src/features/public-api/server/observations.ts b/web/src/features/public-api/server/observations.ts
index ef1b3bb7b9..21d5777ec7 100644
--- a/web/src/features/public-api/server/observations.ts
+++ b/web/src/features/public-api/server/observations.ts
@@ -55,6 +55,7 @@ export const generateObservationsForPublicApi = async (props: QueryType) => {
project_id,
type,
parent_observation_id,
+ environment,
start_time,
end_time,
name,
diff --git a/web/src/features/public-api/server/scores.ts b/web/src/features/public-api/server/scores.ts
index be2db8d900..3dd9b4c731 100644
--- a/web/src/features/public-api/server/scores.ts
+++ b/web/src/features/public-api/server/scores.ts
@@ -41,6 +41,7 @@ export const generateScoresForPublicApi = async (props: ScoreQueryType) => {
s.id as id,
s.project_id as project_id,
s.timestamp as timestamp,
+ s.environment as environment,
s.name as name,
s.value as value,
s.string_value as string_value,
diff --git a/web/src/features/public-api/server/traces.ts b/web/src/features/public-api/server/traces.ts
index 86924a6c6b..ec72dc0f1b 100644
--- a/web/src/features/public-api/server/traces.ts
+++ b/web/src/features/public-api/server/traces.ts
@@ -93,6 +93,7 @@ export const generateTracesForPublicApi = async (
t.project_id as project_id,
t.timestamp as timestamp,
t.name as name,
+ t.environment as environment,
t.input as input,
t.output as output,
t.session_id as session_id,
diff --git a/web/src/features/public-api/types/observations.ts b/web/src/features/public-api/types/observations.ts
index b5988b8ee9..ba6ed86e84 100644
--- a/web/src/features/public-api/types/observations.ts
+++ b/web/src/features/public-api/types/observations.ts
@@ -21,6 +21,7 @@ export const APIObservation = z
parentObservationId: z.string().nullable(),
name: z.string().nullable(),
type: ObservationType,
+ environment: z.string(),
startTime: z.coerce.date(),
endTime: z.coerce.date().nullable(),
version: z.string().nullable(),
diff --git a/web/src/features/public-api/types/traces.ts b/web/src/features/public-api/types/traces.ts
index a40ac771c8..0fd709ff19 100644
--- a/web/src/features/public-api/types/traces.ts
+++ b/web/src/features/public-api/types/traces.ts
@@ -23,6 +23,7 @@ export const APITrace = z
release: z.string().nullable(),
version: z.string().nullable(),
projectId: z.string(),
+ environment: z.string(),
public: z.boolean(),
bookmarked: z.boolean(),
tags: z.array(z.string()),
diff --git a/web/src/server/api/routers/scores.ts b/web/src/server/api/routers/scores.ts
index 8ad36ed0ac..9832cd3ff4 100644
--- a/web/src/server/api/routers/scores.ts
+++ b/web/src/server/api/routers/scores.ts
@@ -39,7 +39,6 @@ import {
convertDateToClickhouseDateTime,
searchExistingAnnotationScore,
} from "@langfuse/shared/src/server";
-import { env } from "@/src/env.mjs";
import { v4 } from "uuid";
const ScoreFilterOptions = z.object({
@@ -166,9 +165,41 @@ export const scoresRouter = createTRPCRouter({
scope: "scores:CUD",
});
+ const clickhouseTrace = await getTraceById(
+ input.traceId,
+ input.projectId,
+ );
+
+ if (!clickhouseTrace) {
+ logger.error(
+ `No trace with id ${input.traceId} in project ${input.projectId} in Clickhouse`,
+ );
+ throw new LangfuseNotFoundError(
+ `No trace with id ${input.traceId} in project ${input.projectId} in Clickhouse`,
+ );
+ }
+
+ const clickhouseScore = await searchExistingAnnotationScore(
+ input.projectId,
+ input.traceId,
+ input.observationId ?? null,
+ input.name,
+ input.configId,
+ );
+
+ if (clickhouseScore) {
+ logger.error(
+ `Score for name ${input.name} already exists for trace ${input.traceId} in project ${input.projectId}`,
+ );
+ throw new InvalidRequestError(
+ `Score for name ${input.name} already exists for trace ${input.traceId} in project ${input.projectId}`,
+ );
+ }
+
const score = {
id: v4(),
projectId: input.projectId,
+ environment: input.environment ?? "default",
traceId: input.traceId,
observationId: input.observationId ?? null,
value: input.value ?? null,
@@ -185,57 +216,23 @@ export const scoresRouter = createTRPCRouter({
timestamp: new Date(),
};
- const hasClickhouseConfigured = env.CLICKHOUSE_URL;
-
- if (hasClickhouseConfigured) {
- const clickhouseTrace = await getTraceById(
- input.traceId,
- input.projectId,
- );
-
- if (!clickhouseTrace) {
- logger.error(
- `No trace with id ${input.traceId} in project ${input.projectId} in Clickhouse`,
- );
- throw new LangfuseNotFoundError(
- `No trace with id ${input.traceId} in project ${input.projectId} in Clickhouse`,
- );
- }
-
- const clickhouseScore = await searchExistingAnnotationScore(
- input.projectId,
- input.traceId,
- input.observationId ?? null,
- input.name,
- input.configId,
- );
-
- if (clickhouseScore) {
- logger.error(
- `Score for name ${input.name} already exists for trace ${input.traceId} in project ${input.projectId}`,
- );
- throw new InvalidRequestError(
- `Score for name ${input.name} already exists for trace ${input.traceId} in project ${input.projectId}`,
- );
- }
-
- await upsertScore({
- id: score.id, // Reuse ID that was generated by Prisma
- timestamp: convertDateToClickhouseDateTime(new Date()),
- project_id: input.projectId,
- trace_id: input.traceId,
- observation_id: input.observationId,
- name: input.name,
- value: input.value !== null ? input.value : undefined,
- source: ScoreSource.ANNOTATION,
- comment: input.comment,
- author_user_id: ctx.session.user.id,
- config_id: input.configId,
- data_type: input.dataType,
- string_value: input.stringValue,
- queue_id: input.queueId,
- });
- }
+ await upsertScore({
+ id: score.id, // Reuse ID that was generated by Prisma
+ timestamp: convertDateToClickhouseDateTime(new Date()),
+ project_id: input.projectId,
+ environment: input.environment ?? "default",
+ trace_id: input.traceId,
+ observation_id: input.observationId,
+ name: input.name,
+ value: input.value !== null ? input.value : undefined,
+ source: ScoreSource.ANNOTATION,
+ comment: input.comment,
+ author_user_id: ctx.session.user.id,
+ config_id: input.configId,
+ data_type: input.dataType,
+ string_value: input.stringValue,
+ queue_id: input.queueId,
+ });
await auditLog({
session: ctx.session,
diff --git a/worker/src/services/IngestionService/index.ts b/worker/src/services/IngestionService/index.ts
index b6d3e6bc71..074f11e5f7 100644
--- a/worker/src/services/IngestionService/index.ts
+++ b/worker/src/services/IngestionService/index.ts
@@ -171,6 +171,7 @@ export class IngestionService {
return {
id: entityId,
project_id: projectId,
+ environment: validatedScore.environment,
timestamp: this.getMillisecondTimestamp(scoreEvent.timestamp),
name: validatedScore.name,
value: validatedScore.value,
@@ -411,6 +412,7 @@ export class IngestionService {
id: finalObservationRecord.id,
timestamp: finalObservationRecord.start_time,
project_id: projectId,
+ environment: finalObservationRecord.environment,
created_at: Date.now(),
updated_at: Date.now(),
metadata: {},
@@ -945,6 +947,7 @@ export class IngestionService {
release: trace.body.release,
version: trace.body.version,
project_id: projectId,
+ environment: trace.body.environment,
public: trace.body.public ?? false,
bookmarked: false,
tags: trace.body.tags ?? [],
@@ -1058,6 +1061,8 @@ export class IngestionService {
trace_id: obs.body.traceId ?? v4(),
type: observationType,
name: obs.body.name,
+ environment:
+ "environment" in obs.body ? obs.body.environment : "default",
start_time: this.getMillisecondTimestamp(
obs.body.startTime ?? obs.timestamp,
),
diff --git a/worker/src/services/IngestionService/tests/IngestionService.integration.test.ts b/worker/src/services/IngestionService/tests/IngestionService.integration.test.ts
index 0acbbf2e28..e263727e25 100644
--- a/worker/src/services/IngestionService/tests/IngestionService.integration.test.ts
+++ b/worker/src/services/IngestionService/tests/IngestionService.integration.test.ts
@@ -23,6 +23,7 @@ import { IngestionService } from "../../IngestionService";
import { ModelUsageUnit, ScoreSource } from "@langfuse/shared";
const projectId = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";
+const environment = "default";
const IngestionEventBatchSchema = z.array(ingestionEvent);
describe("Ingestion end-to-end tests", () => {
@@ -66,6 +67,7 @@ describe("Ingestion end-to-end tests", () => {
body: {
name: traceName,
timestamp,
+ environment,
},
},
];
@@ -368,6 +370,7 @@ describe("Ingestion end-to-end tests", () => {
release: "1.0.0",
version: "2.0.0",
tags: ["tag-1", "tag-2"],
+ environment,
},
},
];
@@ -388,6 +391,7 @@ describe("Ingestion end-to-end tests", () => {
input: { key: "value" },
metadata: { key: "value" },
version: "2.0.0",
+ environment,
},
},
{
@@ -400,6 +404,7 @@ describe("Ingestion end-to-end tests", () => {
usage: testConfig.usage,
usageDetails: testConfig.usageDetails,
costDetails: testConfig.costDetails,
+ environment,
},
},
]);
@@ -419,6 +424,7 @@ describe("Ingestion end-to-end tests", () => {
input: { input: "value" },
metadata: { meta: "value" },
version: "2.0.0",
+ environment,
},
},
];
@@ -435,6 +441,7 @@ describe("Ingestion end-to-end tests", () => {
value: 100.5,
source: ScoreSource.EVAL,
traceId: traceId,
+ environment,
},
},
];
@@ -755,6 +762,7 @@ describe("Ingestion end-to-end tests", () => {
id: traceId,
name: "trace-name",
timestamp: new Date().toISOString(),
+ environment,
},
},
];
@@ -775,6 +783,7 @@ describe("Ingestion end-to-end tests", () => {
},
input: "This is a great prompt",
output: "This is a great gpt output",
+ environment,
},
},
];
@@ -836,6 +845,7 @@ describe("Ingestion end-to-end tests", () => {
body: {
id: traceId,
timestamp: new Date().toISOString(),
+ environment,
},
},
];
@@ -849,6 +859,7 @@ describe("Ingestion end-to-end tests", () => {
id: spanId,
traceId: traceId,
startTime: new Date().toISOString(),
+ environment,
},
},
{
@@ -860,6 +871,7 @@ describe("Ingestion end-to-end tests", () => {
traceId: traceId,
name: "span-name",
startTime: new Date().toISOString(),
+ environment,
},
},
];
@@ -874,6 +886,7 @@ describe("Ingestion end-to-end tests", () => {
traceId: traceId,
startTime: new Date().toISOString(),
parentObservationId: spanId,
+ environment: environment,
modelParameters: { someKey: ["user-1", "user-2"] },
},
},
@@ -885,6 +898,7 @@ describe("Ingestion end-to-end tests", () => {
id: generationId,
name: "generation-name",
startTime: new Date().toISOString(),
+ environment,
},
},
];
@@ -900,6 +914,7 @@ describe("Ingestion end-to-end tests", () => {
name: "event-name",
startTime: new Date().toISOString(),
parentObservationId: generationId,
+ environment,
},
},
];
@@ -917,6 +932,7 @@ describe("Ingestion end-to-end tests", () => {
source: ScoreSource.API,
value: 100.5,
observationId: generationId,
+ environment,
},
},
];
@@ -1014,6 +1030,7 @@ describe("Ingestion end-to-end tests", () => {
release: "1.0.0",
version: "2.0.0",
tags: ["tag-1", "tag-2", "tag-2"],
+ environment,
},
},
];
@@ -1038,6 +1055,7 @@ describe("Ingestion end-to-end tests", () => {
name: "trace-name",
userId: "user-2",
tags: ["tag-1", "tag-4", "tag-3"],
+ environment,
},
},
];
@@ -1084,6 +1102,7 @@ describe("Ingestion end-to-end tests", () => {
timestamp: latestEvent.toISOString(),
name: "trace-name",
userId: "user-1",
+ environment,
},
},
{
@@ -1095,6 +1114,7 @@ describe("Ingestion end-to-end tests", () => {
timestamp: new Date(oldEvent).toISOString(),
name: "trace-name",
userId: "user-2",
+ environment,
},
},
];
@@ -1177,6 +1197,7 @@ describe("Ingestion end-to-end tests", () => {
max_tokens: 1000,
},
usage: null,
+ environment,
},
},
{
@@ -1195,6 +1216,7 @@ describe("Ingestion end-to-end tests", () => {
total: -3,
unit: "TOKENS",
},
+ environment,
},
},
];
@@ -1291,6 +1313,7 @@ describe("Ingestion end-to-end tests", () => {
max_tokens: 1000,
},
usage: null,
+ environment,
},
},
{
@@ -1309,6 +1332,7 @@ describe("Ingestion end-to-end tests", () => {
total: 1313,
unit: "TOKENS",
},
+ environment,
},
},
];
@@ -1364,6 +1388,7 @@ describe("Ingestion end-to-end tests", () => {
startTime: new Date().toISOString(),
output: "to overwrite",
usage: undefined,
+ environment,
},
},
];
@@ -1386,6 +1411,7 @@ describe("Ingestion end-to-end tests", () => {
traceId: traceId,
output: "overwritten",
usage: undefined,
+ environment,
},
},
];
@@ -1421,6 +1447,7 @@ describe("Ingestion end-to-end tests", () => {
type: "GENERATION",
startTime: new Date().toISOString(),
output: { key: "this is a great gpt output" },
+ environment,
},
},
{
@@ -1435,6 +1462,7 @@ describe("Ingestion end-to-end tests", () => {
input: { key: "value" },
output: "should be overwritten",
model: "gpt-3.5",
+ environment,
},
},
];
@@ -1480,6 +1508,7 @@ describe("Ingestion end-to-end tests", () => {
timestamp,
name: "trace-name",
userId: "user-1",
+ environment,
},
},
];
@@ -1496,6 +1525,7 @@ describe("Ingestion end-to-end tests", () => {
startTime: new Date().toISOString(),
name: "LiteLLM.run",
// usage: null,
+ environment,
},
},
];
@@ -1544,6 +1574,7 @@ describe("Ingestion end-to-end tests", () => {
outputCost: 0.0007695,
totalCost: 0.001412,
},
+ environment,
},
},
];
@@ -1608,6 +1639,7 @@ describe("Ingestion end-to-end tests", () => {
name: "trace-name",
timestamp: new Date().toISOString(),
userId: "user-1",
+ environment,
},
},
];
@@ -1625,6 +1657,7 @@ describe("Ingestion end-to-end tests", () => {
name: "generation-name",
input: { key: "value" },
model: "gpt-3.5",
+ environment,
},
},
{
@@ -1635,6 +1668,7 @@ describe("Ingestion end-to-end tests", () => {
id: generationId,
type: "GENERATION",
output: { key: "this is a great gpt output" },
+ environment,
},
},
];
@@ -1710,6 +1744,7 @@ describe("Ingestion end-to-end tests", () => {
name: "trace-name",
timestamp: new Date().toISOString(),
userId: "user-1",
+ environment,
},
},
];
@@ -1723,6 +1758,7 @@ describe("Ingestion end-to-end tests", () => {
id: generationId,
type: "GENERATION",
output: { key: "this is a great gpt output" },
+ environment,
},
},
{
@@ -1737,6 +1773,7 @@ describe("Ingestion end-to-end tests", () => {
name: "generation-name",
input: { key: "value" },
model: "gpt-3.5",
+ environment,
},
},
];
@@ -1795,6 +1832,7 @@ describe("Ingestion end-to-end tests", () => {
metadata: { key: "value" },
release: "1.0.0",
version: "2.0.0",
+ environment,
},
},
{
@@ -1808,6 +1846,7 @@ describe("Ingestion end-to-end tests", () => {
// Do not set user_id here to validate behaviour for missing fields
release: null,
version: undefined,
+ environment,
},
},
];
@@ -1899,6 +1938,7 @@ describe("Ingestion end-to-end tests", () => {
timestamp: new Date().toISOString(),
userId: "user-1",
metadata: inputs[0],
+ environment,
},
},
{
@@ -1910,6 +1950,7 @@ describe("Ingestion end-to-end tests", () => {
name: "trace-name",
timestamp: new Date().toISOString(),
metadata: inputs[1],
+ environment,
},
},
];
@@ -1926,6 +1967,7 @@ describe("Ingestion end-to-end tests", () => {
type: "GENERATION",
name: "generation-name",
metadata: inputs[0],
+ environment,
},
},
{
@@ -1938,6 +1980,7 @@ describe("Ingestion end-to-end tests", () => {
startTime: new Date().toISOString(),
type: "GENERATION",
metadata: inputs[1],
+ environment,
},
},
];