Skip to content

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

chore: inject eval and annotation scores into clickhouse (#4081)

Steffen Schmitzeaa885f5f522
diff --git a/.env.dev.example b/.env.dev.example
index 486a28aa69..e8c58d7a1b 100644
--- a/.env.dev.example
+++ b/.env.dev.example
@@ -44,7 +44,7 @@ S3_FORCE_PATH_STYLE=true
# S3 Event Bucket Upload
## Set to true to test uploading all events to S3
-LANGFUSE_S3_EVENT_UPLOAD_ENABLED=false
+LANGFUSE_S3_EVENT_UPLOAD_ENABLED=true
LANGFUSE_S3_EVENT_UPLOAD_BUCKET=langfuse
LANGFUSE_S3_EVENT_UPLOAD_ACCESS_KEY_ID=minio
LANGFUSE_S3_EVENT_UPLOAD_SECRET_ACCESS_KEY=miniosecret
diff --git a/packages/shared/src/db.ts b/packages/shared/src/db.ts
index 8346f5203c..2c186ff479 100644
--- a/packages/shared/src/db.ts
+++ b/packages/shared/src/db.ts
@@ -76,7 +76,7 @@ export class KyselySingleton {
createQueryCompiler: () => new PostgresQueryCompiler(),
},
}),
- })
+ }),
);
return KyselySingleton.instance;
@@ -103,7 +103,7 @@ if (process.env.NODE_ENV === "development") {
createQueryCompiler: () => new PostgresQueryCompiler(),
},
}),
- })
+ }),
);
}
diff --git a/packages/shared/src/env.ts b/packages/shared/src/env.ts
index 52cefa6adc..9315718e3a 100644
--- a/packages/shared/src/env.ts
+++ b/packages/shared/src/env.ts
@@ -38,6 +38,16 @@ const EnvSchema = z.object({
ENABLE_AWS_CLOUDWATCH_METRIC_PUBLISHING: z
.enum(["true", "false"])
.default("false"),
+ LANGFUSE_S3_EVENT_UPLOAD_ENABLED: z.enum(["true", "false"]).default("false"),
+ LANGFUSE_S3_EVENT_UPLOAD_BUCKET: z.string().optional(),
+ LANGFUSE_S3_EVENT_UPLOAD_PREFIX: z.string().default(""),
+ LANGFUSE_S3_EVENT_UPLOAD_REGION: z.string().optional(),
+ LANGFUSE_S3_EVENT_UPLOAD_ENDPOINT: z.string().optional(),
+ LANGFUSE_S3_EVENT_UPLOAD_ACCESS_KEY_ID: z.string().optional(),
+ LANGFUSE_S3_EVENT_UPLOAD_SECRET_ACCESS_KEY: z.string().optional(),
+ LANGFUSE_S3_EVENT_UPLOAD_FORCE_PATH_STYLE: z
+ .enum(["true", "false"])
+ .default("false"),
});
export const env = EnvSchema.parse(removeEmptyEnvVariables(process.env));
diff --git a/packages/shared/src/server/clickhouse/schema-utils.ts b/packages/shared/src/server/clickhouse/schemaUtils.ts
similarity index 100%
rename from packages/shared/src/server/clickhouse/schema-utils.ts
rename to packages/shared/src/server/clickhouse/schemaUtils.ts
diff --git a/packages/shared/src/server/index.ts b/packages/shared/src/server/index.ts
index 69f65af45f..032a6a763e 100644
--- a/packages/shared/src/server/index.ts
+++ b/packages/shared/src/server/index.ts
@@ -10,7 +10,7 @@ export * from "./llm/types";
export * from "./utils/DatabaseReadStream";
export * from "./utils/transforms";
export * from "./clickhouse/client";
-export * from "./clickhouse/schema-utils";
+export * from "./clickhouse/schemaUtils";
export * from "./clickhouse/schema";
export * from "./repositories/definitions";
export * from "../server/ingestion/types";
diff --git a/packages/shared/src/server/ingestion/types.ts b/packages/shared/src/server/ingestion/types.ts
index ceb6ed1501..bb61bbb03b 100644
--- a/packages/shared/src/server/ingestion/types.ts
+++ b/packages/shared/src/server/ingestion/types.ts
@@ -3,7 +3,7 @@ import { z } from "zod";
import { NonEmptyString, jsonSchema } from "../../utils/zod";
import { ModelUsageUnit } from "../../constants";
-import { ObservationLevel } from "@prisma/client";
+import { ObservationLevel, ScoreSource } from "@prisma/client";
export const Usage = z.object({
input: z.number().int().nullish(),
@@ -163,6 +163,7 @@ const BaseScoreBody = z.object({
traceId: z.string(),
observationId: z.string().nullish(),
comment: z.string().nullish(),
+ source: z.nativeEnum(ScoreSource).default(ScoreSource.API),
});
/**
diff --git a/packages/shared/src/server/ingestion/validateAndInflateScore.ts b/packages/shared/src/server/ingestion/validateAndInflateScore.ts
index 86667f8c6d..90e9ba303c 100644
--- a/packages/shared/src/server/ingestion/validateAndInflateScore.ts
+++ b/packages/shared/src/server/ingestion/validateAndInflateScore.ts
@@ -76,7 +76,7 @@ function inflateScoreBody(
const { body, projectId, scoreId, config } = params;
const relevantDataType = config?.dataType ?? body.dataType;
- const scoreProps = { ...body, id: scoreId, projectId, source: "API" };
+ const scoreProps = { ...body, id: scoreId, projectId };
if (typeof body.value === "number") {
if (relevantDataType && relevantDataType === ScoreDataType.BOOLEAN) {
diff --git a/packages/shared/src/server/queries/clickhouse-filter/factory.ts b/packages/shared/src/server/queries/clickhouse-filter/factory.ts
index ca9ee9364d..159d92c851 100644
--- a/packages/shared/src/server/queries/clickhouse-filter/factory.ts
+++ b/packages/shared/src/server/queries/clickhouse-filter/factory.ts
@@ -1,7 +1,7 @@
import z from "zod";
import { singleFilter } from "../../../interfaces/filters";
import { FilterCondition } from "../../../types";
-import { isValidTableName } from "../../clickhouse/schema-utils";
+import { isValidTableName } from "../../clickhouse/schemaUtils";
import { logger } from "../../logger";
import { UiColumnMapping } from "../../../tableDefinitions";
import {
diff --git a/packages/shared/src/server/repositories/clickhouse.ts b/packages/shared/src/server/repositories/clickhouse.ts
index d446d22a62..eb52531208 100644
--- a/packages/shared/src/server/repositories/clickhouse.ts
+++ b/packages/shared/src/server/repositories/clickhouse.ts
@@ -1,34 +1,109 @@
-import { JsonNested } from "../../utils/zod";
import { env } from "../../env";
-import { clickhouseClient } from "../clickhouse/client";
+import {
+ clickhouseClient,
+ convertDateToClickhouseDateTime,
+} from "../clickhouse/client";
import { logger } from "../logger";
-import { getCurrentSpan, instrumentAsync } from "../instrumentation";
+import { instrumentAsync } from "../instrumentation";
+import { S3StorageService } from "../services/S3StorageService";
+import { randomUUID } from "crypto";
+import { getClickhouseEntityType } from "../clickhouse/schemaUtils";
-export const convertRecordToJsonSchema = (
- record: Record<string, string>,
-): JsonNested | undefined => {
- const jsonSchema: JsonNested = {};
+let s3StorageServiceClient: S3StorageService;
- // if record is empty, return undefined
- if (Object.keys(record).length === 0) {
- return undefined;
+const getS3StorageServiceClient = (bucketName: string): S3StorageService => {
+ if (!s3StorageServiceClient) {
+ s3StorageServiceClient = new S3StorageService({
+ bucketName,
+ accessKeyId: env.LANGFUSE_S3_EVENT_UPLOAD_ACCESS_KEY_ID,
+ secretAccessKey: env.LANGFUSE_S3_EVENT_UPLOAD_SECRET_ACCESS_KEY,
+ endpoint: env.LANGFUSE_S3_EVENT_UPLOAD_ENDPOINT,
+ region: env.LANGFUSE_S3_EVENT_UPLOAD_REGION,
+ forcePathStyle: env.LANGFUSE_S3_EVENT_UPLOAD_FORCE_PATH_STYLE === "true",
+ });
}
+ return s3StorageServiceClient;
+};
+
+export async function upsertClickhouse<
+ T extends Record<string, unknown>,
+>(opts: {
+ table: "scores"; // TODO: Modify eventType logic to support more tables going forward
+ records: T[];
+ eventBodyMapper: (body: T) => Record<string, unknown>;
+}): Promise<void> {
+ return await instrumentAsync({ name: "clickhouse-upsert" }, async (span) => {
+ // https://opentelemetry.io/docs/specs/semconv/database/database-spans/
+ span.setAttribute("ch.query.table", opts.table);
+
+ // drop trailing s and pretend it's always a create.
+ // Only applicable to scores (and eventually traces).
+ const eventType = `${opts.table.slice(0, -1)}-create`;
- for (const key in record) {
- try {
- jsonSchema[key] = JSON.parse(record[key]);
- } catch (e) {
- jsonSchema[key] = record[key];
+ // If event upload is enabled, we store all rows in S3 to have a backup
+ if (env.LANGFUSE_S3_EVENT_UPLOAD_ENABLED === "true") {
+ if (env.LANGFUSE_S3_EVENT_UPLOAD_BUCKET === undefined) {
+ throw new Error("S3 event store is enabled but no bucket is set");
+ }
+ const s3Client = getS3StorageServiceClient(
+ env.LANGFUSE_S3_EVENT_UPLOAD_BUCKET,
+ );
+ await Promise.all(
+ opts.records.map((record) => {
+ s3Client.uploadJson(
+ `${env.LANGFUSE_S3_EVENT_UPLOAD_PREFIX}${record.project_id}/${getClickhouseEntityType(eventType)}/${record.id}/${randomUUID()}.json`,
+ [
+ {
+ id: randomUUID(),
+ timestamp: new Date().toISOString(),
+ type: eventType,
+ body: opts.eventBodyMapper(record),
+ },
+ ],
+ );
+ }),
+ );
}
- }
- return jsonSchema;
-};
+ const res = await clickhouseClient.insert({
+ table: opts.table,
+ values: opts.records.map((record) => ({
+ ...record,
+ event_ts: convertDateToClickhouseDateTime(new Date()),
+ })),
+ format: "JSONEachRow",
+ });
+ // same logic as for prisma. we want to see queries in development
+ if (env.NODE_ENV === "development") {
+ logger.info(`clickhouse:insert ${res.query_id} ${opts.table}`);
+ }
+
+ span.setAttribute("ch.queryId", res.query_id);
+
+ // add summary headers to the span. Helps to tune performance
+ const summaryHeader = res.response_headers["x-clickhouse-summary"];
+ if (summaryHeader) {
+ try {
+ const summary = Array.isArray(summaryHeader)
+ ? JSON.parse(summaryHeader[0])
+ : JSON.parse(summaryHeader);
+ for (const key in summary) {
+ span.setAttribute(`ch.${key}`, summary[key]);
+ }
+ } catch (error) {
+ logger.debug(
+ `Failed to parse clickhouse summary header ${summaryHeader}`,
+ error,
+ );
+ }
+ }
+ });
+}
export async function queryClickhouse<T>(opts: {
query: string;
params?: Record<string, unknown> | undefined;
-}) {
+}): Promise<T[]> {
return await instrumentAsync({ name: "clickhouse-query" }, async (span) => {
// https://opentelemetry.io/docs/specs/semconv/database/database-spans/
span.setAttribute("ch.query.text", opts.query);
@@ -67,6 +142,45 @@ export async function queryClickhouse<T>(opts: {
});
}
+export async function commandClickhouse<T>(opts: {
+ query: string;
+ params?: Record<string, unknown> | undefined;
+}): Promise<void> {
+ return await instrumentAsync({ name: "clickhouse-command" }, async (span) => {
+ // https://opentelemetry.io/docs/specs/semconv/database/database-spans/
+ span.setAttribute("ch.query.text", opts.query);
+
+ const res = await clickhouseClient.command({
+ query: opts.query,
+ query_params: opts.params,
+ });
+ // same logic as for prisma. we want to see queries in development
+ if (env.NODE_ENV === "development") {
+ logger.info(`clickhouse:query ${res.query_id} ${opts.query}`);
+ }
+
+ span.setAttribute("ch.queryId", res.query_id);
+
+ // add summary headers to the span. Helps to tune performance
+ const summaryHeader = res.response_headers["x-clickhouse-summary"];
+ if (summaryHeader) {
+ try {
+ const summary = Array.isArray(summaryHeader)
+ ? JSON.parse(summaryHeader[0])
+ : JSON.parse(summaryHeader);
+ for (const key in summary) {
+ span.setAttribute(`ch.${key}`, summary[key]);
+ }
+ } catch (error) {
+ logger.debug(
+ `Failed to parse clickhouse summary header ${summaryHeader}`,
+ error,
+ );
+ }
+ }
+ });
+}
+
export function parseClickhouseUTCDateTimeFormat(dateStr: string): Date {
return new Date(`${dateStr.replace(" ", "T")}Z`);
}
diff --git a/packages/shared/src/server/repositories/scores.ts b/packages/shared/src/server/repositories/scores.ts
index 0f9ad33af3..5c045301fd 100644
--- a/packages/shared/src/server/repositories/scores.ts
+++ b/packages/shared/src/server/repositories/scores.ts
@@ -1,7 +1,9 @@
import { Score, ScoreDataType, ScoreSource } from "@prisma/client";
import {
+ commandClickhouse,
parseClickhouseUTCDateTimeFormat,
queryClickhouse,
+ upsertClickhouse,
} from "./clickhouse";
import { FilterList } from "../queries/clickhouse-filter/clickhouse-filter";
import { FilterState } from "../../types";
@@ -56,6 +58,86 @@ const convertToScore = (row: FetchScoresReturnType) => {
};
};
+export const searchExistingAnnotationScore = async (
+ projectId: string,
+ traceId: string,
+ observationId: string | null,
+ name: string | undefined,
+ configId: string | undefined,
+) => {
+ if (!name && !configId) {
+ throw new Error("Either name or configId (or both) must be provided.");
+ }
+ const query = `
+ SELECT *
+ FROM scores s FINAL
+ WHERE s.project_id = {projectId: String}
+ AND s.source = 'ANNOTATION'
+ AND s.trace_id = {traceId: String}
+ ${observationId ? `AND s.observation_id = {observationId: String}` : "AND isNull(s.observation_id)"}
+ AND (
+ FALSE
+ ${name ? `OR s.name = {name: String}` : ""}
+ ${configId ? `OR s.config_id = {configId: String}` : ""}
+ )
+ ORDER BY s.event_ts DESC
+ LIMIT 1
+ `;
+
+ const rows = await queryClickhouse<FetchScoresReturnType>({
+ query,
+ params: {
+ projectId,
+ name,
+ configId,
+ traceId,
+ observationId,
+ },
+ });
+ return rows.map(convertToScore).shift();
+};
+
+export const getScoreById = async (
+ projectId: string,
+ scoreId: string,
+ source: ScoreSource,
+) => {
+ const query = `
+ SELECT *
+ FROM scores s FINAL
+ WHERE s.project_id = {projectId: String}
+ AND s.id = {scoreId: String}
+ AND s.source = {source: String}
+ ORDER BY s.event_ts DESC
+ LIMIT 1
+ `;
+
+ const rows = await queryClickhouse<FetchScoresReturnType>({
+ query,
+ params: {
+ projectId,
+ scoreId,
+ source,
+ },
+ });
+ return rows.map(convertToScore).shift();
+};
+
+/**
+ * Accepts a score in a Clickhouse-ready format.
+ * id, project_id, name, and timestamp must always be provided.
+ */
+export const upsertScore = async (score: Partial<FetchScoresReturnType>) => {
+ if (!["id", "project_id", "name", "timestamp"].every((key) => key in score)) {
+ throw new Error("Identifier fields must be provided to upsert Score.");
+ }
+ await upsertClickhouse({
+ table: "scores",
+ records: [score as FetchScoresReturnType],
+ eventBodyMapper: convertToScore,
+ });
+};
+
export const getScoresForTraces = async (
projectId: string,
traceIds: string[],
@@ -376,3 +458,18 @@ export const getScoreNames = async (
count: Number(row.count),
}));
};
+
+export const deleteScore = async (projectId: string, scoreId: string) => {
+ const query = `
+ DELETE FROM scores
+ WHERE project_id = {projectId: String}
+ AND id = {scoreId: String};
+ `;
+ await commandClickhouse({
+ query: query,
+ params: {
+ projectId,
+ scoreId,
+ },
+ });
+};
diff --git a/packages/shared/src/server/repositories/traces.ts b/packages/shared/src/server/repositories/traces.ts
index a50c6cc1df..6a9d00baa5 100644
--- a/packages/shared/src/server/repositories/traces.ts
+++ b/packages/shared/src/server/repositories/traces.ts
@@ -240,6 +240,18 @@ const getTracesTableGeneric = async <T>(props: FetchTracesTableProps) => {
});
};
+export const getTraceById = async (
+ traceId: string,
+ projectId: string,
+ timestamp?: Date,
+): Promise<Trace | undefined> => {
+ try {
+ return getTraceByIdOrThrow(traceId, projectId, timestamp);
+ } catch (e) {
+ return undefined;
+ }
+};
+
export const getTracesByIds = async (
traceIds: string[],
projectId: string,
diff --git a/web/src/pages/api/public/scores/[scoreId].ts b/web/src/pages/api/public/scores/[scoreId].ts
index bfba238a7d..644aa7c9bb 100644
--- a/web/src/pages/api/public/scores/[scoreId].ts
+++ b/web/src/pages/api/public/scores/[scoreId].ts
@@ -1,3 +1,4 @@
+import { env } from "@/src/env.mjs";
import { createAuthedAPIRoute } from "@/src/features/public-api/server/createAuthedAPIRoute";
import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";
import {
@@ -9,7 +10,7 @@ import {
LangfuseNotFoundError,
} from "@langfuse/shared";
import { prisma } from "@langfuse/shared/src/db";
-import { traceException } from "@langfuse/shared/src/server";
+import { deleteScore, traceException } from "@langfuse/shared/src/server";
export default withMiddlewares({
GET: createAuthedAPIRoute({
@@ -63,6 +64,10 @@ export default withMiddlewares({
);
}
+ if (env.CLICKHOUSE_URL) {
+ await deleteScore(auth.scope.projectId, scoreId);
+ }
+
await prisma.score.delete({
where: {
id: scoreId,
diff --git a/web/src/server/api/routers/scores.ts b/web/src/server/api/routers/scores.ts
index f32a9d7472..be603fc673 100644
--- a/web/src/server/api/routers/scores.ts
+++ b/web/src/server/api/routers/scores.ts
@@ -23,6 +23,7 @@ import {
timeFilter,
UpdateAnnotationScoreData,
validateDbScore,
+ ScoreSource,
} from "@langfuse/shared";
import { Prisma, type Score } from "@langfuse/shared/src/db";
import {
@@ -35,9 +36,17 @@ import {
tableColumnsToSqlFilterAndPrefix,
getScoreNames,
getTracesGroupedByTags,
+ deleteScore,
+ upsertScore,
+ logger,
+ getTraceById,
+ getScoreById,
+ convertDateToClickhouseDateTime,
+ searchExistingAnnotationScore,
} from "@langfuse/shared/src/server";
import { isClickhouseEligible } from "@/src/server/utils/checkClickhouseAccess";
import { TRPCError } from "@trpc/server";
+import { env } from "@/src/env.mjs";
const ScoreFilterOptions = z.object({
projectId: z.string(), // Required for protectedProjectProcedure
@@ -318,33 +327,15 @@ export const scoresRouter = createTRPCRouter({
traceId: input.traceId,
observationId: input.observationId ?? null,
source: "ANNOTATION",
+ // configId functions as unique constraint for scores with source ANNOTATION
configId: input.configId,
},
});
if (existingScore) {
- const updatedScore = await ctx.prisma.score.update({
- where: {
- id: existingScore.id,
- projectId: input.projectId,
- },
- data: {
- value: input.value,
- stringValue: input.stringValue,
- comment: input.comment,
- authorUserId: ctx.session.user.id,
- queueId: input.queueId,
- },
- });
- await auditLog({
- session: ctx.session,
- resourceType: "score",
- resourceId: updatedScore.id,
- action: "update",
- before: existingScore,
- after: updatedScore,
- });
- return validateDbScore(updatedScore);
+ throw new Error(
+ `Score for name ${input.name} already exists for trace ${input.traceId} in project ${input.projectId}`,
+ );
}
const score = await ctx.prisma.score.create({
@@ -371,6 +362,55 @@ export const scoresRouter = createTRPCRouter({
action: "create",
after: score,
});
+
+ if (env.CLICKHOUSE_URL) {
+ const clickhouseTrace = await getTraceById(
+ input.traceId,
+ input.projectId,
+ );
+
+ if (!clickhouseTrace) {
+ // Fail silently while Postgres is in lead and return early.
+ logger.error(
+ `No trace with id ${input.traceId} in project ${input.projectId} in Clickhouse`,
+ );
+ return validateDbScore(score);
+ }
+
+ const clickhouseScore = await searchExistingAnnotationScore(
+ input.projectId,
+ input.traceId,
+ input.observationId ?? null,
+ input.name,
+ input.configId,
+ );
+
+ if (clickhouseScore) {
+ // Fail silently while Postgres is in lead and return early.
+ logger.error(
+ `Score for name ${input.name} already exists for trace ${input.traceId} in project ${input.projectId}`,
+ );
+ return validateDbScore(score);
+ }
+
+ 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,
+ });
+ }
+
return validateDbScore(score);
}),
updateAnnotationScore: protectedProjectProcedure
@@ -381,6 +421,41 @@ export const scoresRouter = createTRPCRouter({
projectId: input.projectId,
scope: "scores:CUD",
});
+
+ if (env.CLICKHOUSE_URL) {
+ // Fetch the current score from Clickhouse
+ const clickhouseScore = await getScoreById(
+ input.projectId,
+ input.id,
+ ScoreSource.ANNOTATION,
+ );
+ if (!clickhouseScore) {
+ // Continue processing the update in Postgres
+ logger.warn(
+ `No annotation score with id ${input.id} in project ${input.projectId} in Clickhouse`,
+ );
+ } else {
+ await upsertScore({
+ id: input.id,
+ project_id: input.projectId,
+ timestamp: convertDateToClickhouseDateTime(
+ clickhouseScore.timestamp,
+ ),
+ value: input.value !== null ? input.value : undefined,
+ string_value: input.stringValue,
+ comment: input.comment,
+ author_user_id: ctx.session.user.id,
+ queue_id: input.queueId,
+ source: ScoreSource.ANNOTATION,
+ name: clickhouseScore.name,
+ data_type: clickhouseScore.dataType,
+ config_id: clickhouseScore.configId,
+ trace_id: clickhouseScore.traceId,
+ observation_id: clickhouseScore.observationId,
+ });
+ }
+ }
+
const score = await ctx.prisma.score.findFirst({
where: {
id: input.id,
@@ -444,6 +519,12 @@ export const scoresRouter = createTRPCRouter({
before: score,
});
+ if (env.CLICKHOUSE_URL) {
+ // Delete the score from Clickhouse
+ await deleteScore(input.projectId, score.id);
+ }
+
+ // Delete the score from Postgres
return await ctx.prisma.score.delete({
where: {
id: score.id,
diff --git a/worker/src/__tests__/eval-service.test.ts b/worker/src/__tests__/evalService.test.ts
similarity index 86%
rename from worker/src/__tests__/eval-service.test.ts
rename to worker/src/__tests__/evalService.test.ts
index 350ce80a1e..f96d89e6ea 100644
--- a/worker/src/__tests__/eval-service.test.ts
+++ b/worker/src/__tests__/evalService.test.ts
@@ -1,4 +1,4 @@
-import { expect, test, describe, vi, afterAll, beforeAll } from "vitest";
+import { expect, test, describe, afterAll, beforeAll, vi } from "vitest";
import {
createEvalJobs,
evaluate,
@@ -17,22 +17,8 @@ import {
import { encrypt } from "@langfuse/shared/encryption";
import { OpenAIServer } from "./network";
import { afterEach } from "node:test";
-import { logger } from "@langfuse/shared/src/server";
-
-vi.mock("../redis/consumer", () => ({
- evalQueue: {
- add: vi.fn().mockImplementation((jobName, jobData) => {
- logger.info(
- `Mock evalQueue.add called with jobName: ${jobName} and jobData:`,
- jobData,
- );
- // Simulate the job being processed immediately by calling the job's processing function
- // Note: You would replace `processJobFunction` with the actual function that processes the job
- // For example, if `createEvalJobs` is the function that should be called, you would use it here
- // processJobFunction({ data: jobData.payload });
- }),
- },
-}));
+import { QueueName } from "@langfuse/shared/src/server";
+import { Worker, Job } from "bullmq";
let OPENAI_API_KEY = process.env.OPENAI_API_KEY;
const hasActiveKey = Boolean(OPENAI_API_KEY);
@@ -695,6 +681,141 @@ describe("execute evals", () => {
expect(jobs.length).toBe(0);
}, 10_000);
+
+ test("evals a valid event and inserts score to ingestion pipeline", async () => {
+ await pruneDatabase();
+ openAIServer.respondWithDefault();
+ const traceId = randomUUID();
+
+ await kyselyPrisma.$kysely
+ .insertInto("traces")
+ .values({
+ id: traceId,
+ project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ user_id: "a",
+ input: { input: "This is a great prompt" },
+ output: { output: "This is a great response" },
+ })
+ .execute();
+
+ const templateId = randomUUID();
+ await kyselyPrisma.$kysely
+ .insertInto("eval_templates")
+ .values({
+ id: templateId,
+ project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ name: "test-template",
+ version: 1,
+ prompt: "Please evaluate toxicity {{input}} {{output}}",
+ model: "gpt-3.5-turbo",
+ provider: "openai",
+ model_params: {},
+ output_schema: {
+ reasoning: "Please explain your reasoning",
+ score: "Please provide a score between 0 and 1",
+ },
+ })
+ .executeTakeFirst();
+
+ const jobConfiguration = await prisma.jobConfiguration.create({
+ data: {
+ id: randomUUID(),
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ filter: [
+ {
+ type: "string",
+ value: "a",
+ column: "User ID",
+ operator: "contains",
+ },
+ ],
+ jobType: "EVAL",
+ delay: 0,
+ sampling: new Decimal("1"),
+ targetObject: "traces",
+ scoreName: "score",
+ variableMapping: JSON.parse("[]"),
+ evalTemplateId: templateId,
+ },
+ });
+
+ const jobExecutionId = randomUUID();
+
+ await kyselyPrisma.$kysely
+ .insertInto("job_executions")
+ .values({
+ id: jobExecutionId,
+ project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ job_configuration_id: jobConfiguration.id,
+ status: sql`'PENDING'::"JobExecutionStatus"`,
+ start_time: new Date(),
+ job_input_trace_id: traceId,
+ })
+ .execute();
+
+ await kyselyPrisma.$kysely
+ .insertInto("llm_api_keys")
+ .values({
+ id: randomUUID(),
+ project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ secret_key: encrypt(String(OPENAI_API_KEY)),
+ provider: "openai",
+ adapter: LLMAdapter.OpenAI,
+ custom_models: [],
+ display_secret_key: "123456",
+ })
+ .execute();
+
+ const payload = {
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ jobExecutionId: jobExecutionId,
+ delay: 1000,
+ };
+
+ await evaluate({ event: payload });
+
+ const jobs = await kyselyPrisma.$kysely
+ .selectFrom("job_executions")
+ .selectAll()
+ .where("project_id", "=", "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a")
+ .execute();
+
+ expect(jobs.length).toBe(1);
+ expect(jobs[0].project_id).toBe("7a88fb47-b4e2-43b8-a06c-a5ce950dc53a");
+ expect(jobs[0].job_input_trace_id).toBe(traceId);
+ expect(jobs[0].status.toString()).toBe("COMPLETED");
+ expect(jobs[0].start_time).not.toBeNull();
+ expect(jobs[0].end_time).not.toBeNull();
+
+ const scores = await kyselyPrisma.$kysely
+ .selectFrom("scores")
+ .selectAll()
+ .where("trace_id", "=", traceId)
+ .execute();
+
+ expect(scores.length).toBe(1);
+ expect(scores[0].trace_id).toBe(traceId);
+ expect(scores[0].comment).not.toBeNull();
+ expect(scores[0].project_id).toBe("7a88fb47-b4e2-43b8-a06c-a5ce950dc53a");
+
+ await new Promise<void>((resolve, reject) => {
+ new Worker(
+ QueueName.IngestionQueue,
+ async (job: Job) => {
+ try {
+ expect(job.name).toBe("ingestion-job");
+ expect(job.data.payload.data.type).toBe("score-create");
+ resolve();
+ } catch (e) {
+ reject(e);
+ }
+ },
+ {
+ connection: redis,
+ },
+ );
+ });
+ }, 10_000);
});
describe("test variable extraction", () => {
diff --git a/worker/src/__tests__/evnets-api.test.ts b/worker/src/__tests__/eventsApi.test.ts
similarity index 100%
rename from worker/src/__tests__/evnets-api.test.ts
rename to worker/src/__tests__/eventsApi.test.ts
diff --git a/worker/src/__tests__/network.ts b/worker/src/__tests__/network.ts
index 61bb7ffc4e..1232c9264c 100644
--- a/worker/src/__tests__/network.ts
+++ b/worker/src/__tests__/network.ts
@@ -51,12 +51,21 @@ function JsonCompletionHandler(data: object) {
return CompletionHandler(HttpResponse.json(data));
}
+function MinioCompletionHandler() {
+ return http.all("http://localhost:9090*", async (request) => {
+ if ((request.params[0] as string).startsWith("/langfuse/events/")) {
+ return new HttpResponse("Success");
+ }
+ throw new Error("Unexpected path");
+ });
+}
+
function ErrorCompletionHandler(status: number, statusText: string) {
return CompletionHandler(
new HttpResponse(null, {
status,
statusText,
- })
+ }),
);
}
@@ -78,7 +87,7 @@ export class OpenAIServer {
this.hasActiveKey = hasActiveKey;
this.internalServer = setupServer(
- ...(useDefaultResponse ? [JsonCompletionHandler(DEFAULT_RESPONSE)] : [])
+ ...(useDefaultResponse ? [JsonCompletionHandler(DEFAULT_RESPONSE)] : []),
);
if (hasActiveKey) {
this.internalServer.events.on("response:bypass", async ({ response }) => {
@@ -100,7 +109,10 @@ export class OpenAIServer {
}
respondWithData(data: object) {
- this.internalServer.use(JsonCompletionHandler(data));
+ this.internalServer.use(
+ JsonCompletionHandler(data),
+ MinioCompletionHandler(),
+ );
}
respondWithDefault() {
diff --git a/worker/src/__tests__/redis-consumer.test.ts b/worker/src/__tests__/redisConsumer.test.ts
similarity index 100%
rename from worker/src/__tests__/redis-consumer.test.ts
rename to worker/src/__tests__/redisConsumer.test.ts
diff --git a/worker/src/features/evaluation/evalService.ts b/worker/src/features/evaluation/evalService.ts
index 11e575c818..1c8d9efbae 100644
--- a/worker/src/features/evaluation/evalService.ts
+++ b/worker/src/features/evaluation/evalService.ts
@@ -2,12 +2,18 @@ import { randomUUID } from "crypto";
import Handlebars from "handlebars";
import { sql } from "kysely";
import { z } from "zod";
+import { ScoreSource } from "@prisma/client";
import {
QueueJobs,
QueueName,
EvalExecutionEvent,
TraceUpsertEventSchema,
tableColumnsToSqlFilterAndPrefix,
+ traceException,
+ S3StorageService,
+ eventTypes,
+ redis,
+ IngestionQueue,
} from "@langfuse/shared/src/server";
import {
ApiError,
@@ -29,6 +35,23 @@ import { kyselyPrisma, prisma } from "@langfuse/shared/src/db";
import { fetchLLMCompletion, logger } from "@langfuse/shared/src/server";
import { EvalExecutionQueue } from "../../queues/evalQueue";
import { backOff } from "exponential-backoff";
+import { env } from "../../env";
+
+let s3StorageServiceClient: S3StorageService;
+
+const getS3StorageServiceClient = (bucketName: string): S3StorageService => {
+ if (!s3StorageServiceClient) {
+ s3StorageServiceClient = new S3StorageService({
+ bucketName,
+ accessKeyId: env.LANGFUSE_S3_EVENT_UPLOAD_ACCESS_KEY_ID,
+ secretAccessKey: env.LANGFUSE_S3_EVENT_UPLOAD_SECRET_ACCESS_KEY,
+ endpoint: env.LANGFUSE_S3_EVENT_UPLOAD_ENDPOINT,
+ region: env.LANGFUSE_S3_EVENT_UPLOAD_REGION,
+ forcePathStyle: env.LANGFUSE_S3_EVENT_UPLOAD_FORCE_PATH_STYLE === "true",
+ });
+ }
+ return s3StorageServiceClient;
+};
// this function is used to determine which eval jobs to create for a given trace
// there might be multiple eval jobs to create for a single trace
@@ -319,18 +342,77 @@ export const evaluate = async ({
// persist the score and update the job status
const scoreId = randomUUID();
+ const baseScore = {
+ id: scoreId,
+ traceId: job.job_input_trace_id,
+ name: config.score_name,
+ value: parsedLLMOutput.score,
+ comment: parsedLLMOutput.reasoning,
+ source: ScoreSource.EVAL,
+ };
+
await prisma.score.create({
data: {
- id: scoreId,
- traceId: job.job_input_trace_id,
- name: config.score_name,
- value: parsedLLMOutput.score,
- comment: parsedLLMOutput.reasoning,
- source: "EVAL",
+ ...baseScore,
projectId: event.projectId,
},
});
+ // Write score to S3 and ingest into queue for Clickhouse processing
+ try {
+ if (env.LANGFUSE_S3_EVENT_UPLOAD_ENABLED === "true" && env.CLICKHOUSE_URL) {
+ if (env.LANGFUSE_S3_EVENT_UPLOAD_BUCKET === undefined) {
+ throw new Error("S3 event store is enabled but no bucket is set");
+ }
+ const s3Client = getS3StorageServiceClient(
+ env.LANGFUSE_S3_EVENT_UPLOAD_BUCKET,
+ );
+ await s3Client.uploadJson(
+ `${env.LANGFUSE_S3_EVENT_UPLOAD_PREFIX}${event.projectId}/score/${scoreId}/${randomUUID()}.json`,
+ [
+ {
+ id: randomUUID(),
+ timestamp: new Date().toISOString(),
+ type: eventTypes.SCORE_CREATE,
+ body: {
+ ...baseScore,
+ dataType: "NUMERIC",
+ },
+ },
+ ],
+ );
+
+ if (redis) {
+ const queue = IngestionQueue.getInstance();
+ if (!queue) {
+ throw new Error("Ingestion queue not available");
+ }
+ await queue.add(QueueJobs.IngestionJob, {
+ id: randomUUID(),
+ timestamp: new Date(),
+ name: QueueJobs.IngestionJob as const,
+ payload: {
+ data: {
+ type: eventTypes.SCORE_CREATE,
+ eventBodyId: scoreId,
+ },
+ authCheck: {
+ validKey: true,
+ scope: {
+ projectId: event.projectId,
+ accessLevel: "scores",
+ },
+ },
+ },
+ });
+ }
+ }
+ } catch (e) {
+ logger.error(`Failed to add score into IngestionQueue: ${e}`, e);
+ traceException(e);
+ throw new Error(`Failed to write score ${scoreId} into IngestionQueue`);
+ }
+
logger.info(
`Evaluating job ${event.jobExecutionId} persisted score ${scoreId} for trace ${job.job_input_trace_id}`,
);
diff --git a/worker/src/services/IngestionService/tests/IngestionService.integration.test.ts b/worker/src/services/IngestionService/tests/IngestionService.integration.test.ts
index 8650014c00..6a2026e4f8 100644
--- a/worker/src/services/IngestionService/tests/IngestionService.integration.test.ts
+++ b/worker/src/services/IngestionService/tests/IngestionService.integration.test.ts
@@ -281,6 +281,7 @@ describe("Ingestion end-to-end tests", () => {
dataType: "NUMERIC",
name: "score-name",
value: 100.5,
+ source: ScoreSource.EVAL,
traceId: traceId,
},
},
@@ -371,6 +372,7 @@ describe("Ingestion end-to-end tests", () => {
expect(score.name).toBe("score-name");
expect(score.value).toBe(100.5);
expect(score.observation_id).toBeNull();
+ expect(score.source).toBe(ScoreSource.EVAL);
expect(score.project_id).toBe("7a88fb47-b4e2-43b8-a06c-a5ce950dc53a");
});
});
@@ -754,6 +756,7 @@ describe("Ingestion end-to-end tests", () => {
dataType: "NUMERIC",
name: "score-name",
traceId: traceId,
+ source: ScoreSource.API,
value: 100.5,
observationId: generationId,
},