🪢 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: forward /api/public/scores to /api/public/ingestion (#4064)
Steffen Schmitz9445c7ca78a7
diff --git a/web/src/pages/api/public/ingestion.ts b/web/src/pages/api/public/ingestion.tsindex 765c5c8581..995c4aeabe 100644--- a/web/src/pages/api/public/ingestion.ts+++ b/web/src/pages/api/public/ingestion.ts@@ -16,10 +16,10 @@ import {S3StorageService,instrumentAsync,getProcessorForEvent,+ getClickhouseEntityType,type AuthHeaderValidVerificationResult,type LegacyIngestionEventType,type IngestionEventType,- getClickhouseEntityType,} from "@langfuse/shared/src/server";import { telemetry } from "@/src/features/telemetry";import { jsonSchema } from "@langfuse/shared";@@ -79,17 +79,14 @@ const getS3StorageServiceClient = (bucketName: string): S3StorageService => {* - Add the event batch to the queue for async processing* - Fallback to sync processing on errors* 3. Sync Processing- * @param req- * @param res+ * The last two stages live in a processEventBatch function which is reused for the POST scores endpoint and for+ * legacy event types.*/export default async function handler(req: NextApiRequest,res: NextApiResponse,) {try {- /**************- * VALIDATION *- **************/await runMiddleware(req, res, cors);// add context of api call to the span@@ -145,16 +142,6 @@ export default async function handler(() => batchType.safeParse(req.body),);- recordIncrement(- "langfuse.ingestion.event",- parsedSchema.success ? parsedSchema.data.batch.length : 0,- );-- // add number of events to the span- parsedSchema.data- ? currentSpan?.setAttribute("event_count", parsedSchema.data.batch.length)- : undefined;-if (!parsedSchema.success) {logger.info("Invalid request data", parsedSchema.error);return res.status(400).json({@@ -163,239 +150,10 @@ export default async function handler(});}- const validationErrors: { id: string; error: unknown }[] = [];- const authenticationErrors: { id: string; error: unknown }[] = [];-- const batch: z.infer<typeof ingestionEvent>[] = parsedSchema.data.batch- .flatMap((event) => {- const parsed = instrumentSync(- { name: "ingestion-zod-parse-individual-event" },- (span) => {- const parsedBody = ingestionEvent.safeParse(event);- if (parsedBody.data?.id !== undefined) {- span.setAttribute("object.id", parsedBody.data.id);- }- return parsedBody;- },- );- if (!parsed.success) {- validationErrors.push({- id:- typeof event === "object" && event && "id" in event- ? typeof event.id === "string"- ? event.id- : "unknown"- : "unknown",- error: new InvalidRequestError(parsed.error.message),- });- return [];- }- if (!isAuthorized(parsed.data, authCheck)) {- authenticationErrors.push({- id: parsed.data.id,- error: new UnauthorizedError("Access Scope Denied"),- });- return [];- }- return [parsed.data];- })- .flatMap((event) => {- if (event.type === eventTypes.SDK_LOG) {- // Log SDK_LOG events, but remove them from further processing- logger.info("SDK Log Event", { event });- return [];- }- return [event];- });-await telemetry();- const sortedBatch = sortBatch(batch);-- // We group events by eventBodyId which allows us to store and process them- // as one which reduces infra interactions per event. Only used in the S3 case.- const sortedBatchByEventBodyId = sortedBatch.reduce(- (- acc: Record<- string,- {- data: IngestionEventType[];- key: string;- eventBodyId: string;- type: (typeof eventTypes)[keyof typeof eventTypes];- }- >,- event,- ) => {- if (!event.body?.id) {- return acc;- }- const key = `${getClickhouseEntityType(event.type)}-${event.body.id}`;- if (!acc[key]) {- acc[key] = {- data: [],- key: event.id,- type: event.type,- eventBodyId: event.body.id,- };- }- acc[key].data.push(event);- return acc;- },- {},- );-- /********************- * ASYNC PROCESSING *- ********************/- let s3UploadErrored = false;- if (env.LANGFUSE_S3_EVENT_UPLOAD_ENABLED === "true") {- await instrumentAsync({ name: "s3-upload-events" }, async () => {- 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,- );- // S3 Event Upload is currently blocking, but non-failing.- // If a promise rejects, we log it below, but do not throw an error.- // In this case, we upload the full batch into the Redis queue.- const results = await Promise.allSettled(- Object.keys(sortedBatchByEventBodyId).map(async (id) => {- // We upload the event in an array to the S3 bucket grouped by the eventBodyId.- // That way we batch updates from the same invocation into a single file and reduce- // write operations on S3.- const { data, key, type, eventBodyId } =- sortedBatchByEventBodyId[id];- return s3Client.uploadJson(- `${env.LANGFUSE_S3_EVENT_UPLOAD_PREFIX}${authCheck.scope.projectId}/${getClickhouseEntityType(type)}/${eventBodyId}/${key}.json`,- data,- );- }),- );- results.forEach((result) => {- if (result.status === "rejected") {- s3UploadErrored = true;- logger.error("Failed to upload event to S3", {- error: result.reason,- });- }- });- });- }-- // Send each event individually to IngestionQueue for new processing- if (- env.LANGFUSE_ASYNC_INGESTION_PROCESSING === "true" &&- env.LANGFUSE_S3_EVENT_UPLOAD_ENABLED === "true" &&- env.LANGFUSE_ASYNC_CLICKHOUSE_INGESTION_PROCESSING === "true" &&- redis &&- !s3UploadErrored- ) {- const queue = IngestionQueue.getInstance();- const results = await Promise.allSettled(- Object.keys(sortedBatchByEventBodyId).map(async (id) =>- queue- ? queue.add(- QueueJobs.IngestionJob,- {- id: randomUUID(),- timestamp: new Date(),- name: QueueJobs.IngestionJob as const,- payload: {- data: {- type: sortedBatchByEventBodyId[id].type,- eventBodyId: sortedBatchByEventBodyId[id].eventBodyId,- },- authCheck,- },- },- {- delay: env.LANGFUSE_INGESTION_QUEUE_DELAY_SECONDS,- },- )- : Promise.reject("Failed to instantiate queue"),- ),- );- results.forEach((result) => {- if (result.status === "rejected") {- logger.error("Failed to add event to IngestionQueue", {- error: result.reason,- });- }- });- }-- // As part of the legacy processing we sent the entire batch to the worker.- if (env.LANGFUSE_ASYNC_INGESTION_PROCESSING === "true" && redis) {- const queue = LegacyIngestionQueue.getInstance();-- if (queue) {- let addToQueueFailed = false;-- const queuePayload: LegacyIngestionEventType =- env.LANGFUSE_S3_EVENT_UPLOAD_ENABLED === "true" && !s3UploadErrored- ? {- data: Object.keys(sortedBatchByEventBodyId).map((id) => {- const { key, type, eventBodyId } =- sortedBatchByEventBodyId[id];- return {- type,- eventBodyId,- eventId: key,- };- }),- authCheck,- useS3EventStore: true,- }- : { data: sortedBatch, authCheck, useS3EventStore: false };-- try {- await queue.add(QueueJobs.LegacyIngestionJob, {- payload: queuePayload,- id: randomUUID(),- timestamp: new Date(),- name: QueueJobs.LegacyIngestionJob as const,- });- } catch (e: unknown) {- logger.warn(- "Failed to add batch to queue, falling back to sync processing",- e,- );- addToQueueFailed = true;- }-- if (!addToQueueFailed) {- return handleBatchResult(- // we are not sending additional server errors to the client in case of early return- [...validationErrors, ...authenticationErrors],- sortedBatch.map((event) => ({ id: event.id, result: event })),- res,- );- }- } else {- logger.error(- "Ingestion queue not initialized, falling back to sync processing",- );- }- }-- /*******************- * SYNC PROCESSING *- *******************/- const result = await handleBatch(sortedBatch, authCheck, tokenCount);-- await addTracesToTraceUpsertQueue(- result.results,- authCheck.scope.projectId,- );-- // in case we did not return early, we return the result here- handleBatchResult(- [...validationErrors, ...authenticationErrors, ...result.errors],- result.results,- res,- );+ const result = await processEventBatch(parsedSchema.data.batch, authCheck);+ return res.status(207).json(result);} catch (error: unknown) {if (!(error instanceof UnauthorizedError)) {logger.error("error_handling_ingestion_event", error);@@ -414,6 +172,7 @@ export default async function handler(error: "Internal Server Error",});}+if (error instanceof z.ZodError) {logger.error(`Zod exception`, error.errors);return res.status(400).json({@@ -431,6 +190,252 @@ export default async function handler(}}+export const processEventBatch = async (+ input: unknown[],+ authCheck: AuthHeaderValidVerificationResult,+): Promise<{+ successes: { id: string; status: number }[];+ errors: {+ id: string;+ status: number;+ message?: string;+ error?: string;+ }[];+}> => {+ // add context of api call to the span+ const currentSpan = getCurrentSpan();+ recordIncrement("langfuse.ingestion.event", input.length);+ currentSpan?.setAttribute("event_count", input.length);++ /**************+ * VALIDATION *+ **************/+ const validationErrors: { id: string; error: unknown }[] = [];+ const authenticationErrors: { id: string; error: unknown }[] = [];++ const batch: z.infer<typeof ingestionEvent>[] = input+ .flatMap((event) => {+ const parsed = instrumentSync(+ { name: "ingestion-zod-parse-individual-event" },+ (span) => {+ const parsedBody = ingestionEvent.safeParse(event);+ if (parsedBody.data?.id !== undefined) {+ span.setAttribute("object.id", parsedBody.data.id);+ }+ return parsedBody;+ },+ );+ if (!parsed.success) {+ validationErrors.push({+ id:+ typeof event === "object" && event && "id" in event+ ? typeof event.id === "string"+ ? event.id+ : "unknown"+ : "unknown",+ error: new InvalidRequestError(parsed.error.message),+ });+ return [];+ }+ if (!isAuthorized(parsed.data, authCheck)) {+ authenticationErrors.push({+ id: parsed.data.id,+ error: new UnauthorizedError("Access Scope Denied"),+ });+ return [];+ }+ return [parsed.data];+ })+ .flatMap((event) => {+ if (event.type === eventTypes.SDK_LOG) {+ // Log SDK_LOG events, but remove them from further processing+ logger.info("SDK Log Event", { event });+ return [];+ }+ return [event];+ });++ const sortedBatch = sortBatch(batch);++ // We group events by eventBodyId which allows us to store and process them+ // as one which reduces infra interactions per event. Only used in the S3 case.+ const sortedBatchByEventBodyId = sortedBatch.reduce(+ (+ acc: Record<+ string,+ {+ data: IngestionEventType[];+ key: string;+ eventBodyId: string;+ type: (typeof eventTypes)[keyof typeof eventTypes];+ }+ >,+ event,+ ) => {+ if (!event.body?.id) {+ return acc;+ }+ const key = `${getClickhouseEntityType(event.type)}-${event.body.id}`;+ if (!acc[key]) {+ acc[key] = {+ data: [],+ key: event.id,+ type: event.type,+ eventBodyId: event.body.id,+ };+ }+ acc[key].data.push(event);+ return acc;+ },+ {},+ );++ /********************+ * ASYNC PROCESSING *+ ********************/+ let s3UploadErrored = false;+ if (env.LANGFUSE_S3_EVENT_UPLOAD_ENABLED === "true") {+ await instrumentAsync({ name: "s3-upload-events" }, async () => {+ 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,+ );+ // S3 Event Upload is currently blocking, but non-failing.+ // If a promise rejects, we log it below, but do not throw an error.+ // In this case, we upload the full batch into the Redis queue.+ const results = await Promise.allSettled(+ Object.keys(sortedBatchByEventBodyId).map(async (id) => {+ // We upload the event in an array to the S3 bucket grouped by the eventBodyId.+ // That way we batch updates from the same invocation into a single file and reduce+ // write operations on S3.+ const { data, key, type, eventBodyId } = sortedBatchByEventBodyId[id];+ return s3Client.uploadJson(+ `${env.LANGFUSE_S3_EVENT_UPLOAD_PREFIX}${authCheck.scope.projectId}/${getClickhouseEntityType(type)}/${eventBodyId}/${key}.json`,+ data,+ );+ }),+ );+ results.forEach((result) => {+ if (result.status === "rejected") {+ s3UploadErrored = true;+ logger.error("Failed to upload event to S3", {+ error: result.reason,+ });+ }+ });+ });+ }++ // Send each event individually to IngestionQueue for new processing+ if (+ env.LANGFUSE_ASYNC_INGESTION_PROCESSING === "true" &&+ env.LANGFUSE_S3_EVENT_UPLOAD_ENABLED === "true" &&+ env.LANGFUSE_ASYNC_CLICKHOUSE_INGESTION_PROCESSING === "true" &&+ redis &&+ !s3UploadErrored+ ) {+ const queue = IngestionQueue.getInstance();+ const results = await Promise.allSettled(+ Object.keys(sortedBatchByEventBodyId).map(async (id) =>+ queue+ ? queue.add(+ QueueJobs.IngestionJob,+ {+ id: randomUUID(),+ timestamp: new Date(),+ name: QueueJobs.IngestionJob as const,+ payload: {+ data: {+ type: sortedBatchByEventBodyId[id].type,+ eventBodyId: sortedBatchByEventBodyId[id].eventBodyId,+ },+ authCheck,+ },+ },+ {+ delay: env.LANGFUSE_INGESTION_QUEUE_DELAY_SECONDS,+ },+ )+ : Promise.reject("Failed to instantiate queue"),+ ),+ );+ results.forEach((result) => {+ if (result.status === "rejected") {+ logger.error("Failed to add event to IngestionQueue", {+ error: result.reason,+ });+ }+ });+ }++ // As part of the legacy processing we sent the entire batch to the worker.+ if (env.LANGFUSE_ASYNC_INGESTION_PROCESSING === "true" && redis) {+ const queue = LegacyIngestionQueue.getInstance();++ if (queue) {+ let addToQueueFailed = false;++ const queuePayload: LegacyIngestionEventType =+ env.LANGFUSE_S3_EVENT_UPLOAD_ENABLED === "true" && !s3UploadErrored+ ? {+ data: Object.keys(sortedBatchByEventBodyId).map((id) => {+ const { key, type, eventBodyId } = sortedBatchByEventBodyId[id];+ return {+ type,+ eventBodyId,+ eventId: key,+ };+ }),+ authCheck,+ useS3EventStore: true,+ }+ : { data: sortedBatch, authCheck, useS3EventStore: false };++ try {+ await queue.add(QueueJobs.LegacyIngestionJob, {+ payload: queuePayload,+ id: randomUUID(),+ timestamp: new Date(),+ name: QueueJobs.LegacyIngestionJob as const,+ });+ } catch (e: unknown) {+ logger.warn(+ "Failed to add batch to queue, falling back to sync processing",+ e,+ );+ addToQueueFailed = true;+ }++ if (!addToQueueFailed) {+ return aggregateBatchResult(+ // we are not sending additional server errors to the client in case of early return+ [...validationErrors, ...authenticationErrors],+ sortedBatch.map((event) => ({ id: event.id, result: event })),+ );+ }+ } else {+ logger.error(+ "Ingestion queue not initialized, falling back to sync processing",+ );+ }+ }++ /*******************+ * SYNC PROCESSING *+ *******************/+ const result = await handleBatch(sortedBatch, authCheck, tokenCount);++ await addTracesToTraceUpsertQueue(result.results, authCheck.scope.projectId);++ // in case we did not return early, we return the result here+ return aggregateBatchResult(+ [...validationErrors, ...authenticationErrors, ...result.errors],+ result.results,+ );+};+const isAuthorized = (event: IngestionEventType,authScope: AuthHeaderValidVerificationResult,@@ -483,13 +488,9 @@ export const getLangfuseNotFoundError = (error instanceof LangfuseNotFoundError,);-export const hasBadRequestError = (errors: Array<unknown>) =>- errors.some((error) => error instanceof InvalidRequestError);--export const handleBatchResult = (+export const aggregateBatchResult = (errors: Array<{ id: string; error: unknown }>,results: Array<{ id: string; result: unknown }>,- res: NextApiResponse,) => {const returnedErrors: {id: string;@@ -546,37 +547,7 @@ export const handleBatchResult = (});});- return res.status(207).send({ errors: returnedErrors, successes });-};--/**- * Handle single event which is usually send via /ingestion endpoint. Returns errors and results via `res` directly.- *- * Use `parseSingleTypedIngestionApiResponse` for a typed version of this function that throws `BaseError`.- */-export const handleSingleIngestionObject = (- errors: Array<{ id: string; error: unknown }>,- results: Array<{ id: string; result: unknown }>,- res: NextApiResponse,-) => {- try {- // use method untyped for backwards compatibility- const parsedResult = parseSingleTypedIngestionApiResponse(errors, results);-- return res.status(200).json(parsedResult);- } catch (error) {- if (error instanceof BaseError) {- return res.status(error.httpCode).json({- message: error.message,- error: error.name,- });- }- return res.status(500).json({- message: "Internal Server Error",- error:- error instanceof Error ? error.message : "An unknown error occurred",- });- }+ return { successes, errors: returnedErrors };};/**@@ -588,7 +559,6 @@ export const handleSingleIngestionObject = (* @returns - Parsed result* @throws - Throws an error of type `BaseError` if there are errors in the arguments*/-export const parseSingleTypedIngestionApiResponse = <T extends z.ZodTypeAny>(errors: Array<{ id: string; error: unknown }>,results: Array<{ id: string; result: unknown }>,diff --git a/web/src/pages/api/public/scores/index.ts b/web/src/pages/api/public/scores/index.tsindex 81a8b84c64..486bdb0366 100644--- a/web/src/pages/api/public/scores/index.ts+++ b/web/src/pages/api/public/scores/index.ts@@ -2,7 +2,6 @@ import { v4 } from "uuid";import { createAuthedAPIRoute } from "@/src/features/public-api/server/createAuthedAPIRoute";import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";-import { parseSingleTypedIngestionApiResponse } from "@/src/pages/api/public/ingestion";import {GetScoresQuery,GetScoresResponse,@@ -11,36 +10,37 @@ import {PostScoresResponse,} from "@langfuse/shared";import { prisma, Prisma } from "@langfuse/shared/src/db";-import {- eventTypes,- handleBatch,- ingestionBatchEvent,-} from "@langfuse/shared/src/server";-import { tokenCount } from "@/src/features/ingest/usage";+import { eventTypes, logger } from "@langfuse/shared/src/server";+import { processEventBatch } from "@/src/pages/api/public/ingestion";export default withMiddlewares({POST: createAuthedAPIRoute({name: "Create Score",bodySchema: PostScoresBody,responseSchema: PostScoresResponse,- fn: async ({ body, auth }) => {+ fn: async ({ body, auth, res }) => {const event = {id: v4(),type: eventTypes.SCORE_CREATE,timestamp: new Date().toISOString(),body,};- const result = await handleBatch(- ingestionBatchEvent.parse([event]),- auth,- tokenCount,- );- const response = parseSingleTypedIngestionApiResponse(- result.errors,- result.results,- PostScoresResponse,- );- return response;+ if (!event.body.id) {+ event.body.id = v4();+ }+ const result = await processEventBatch([event], auth);+ if (result.errors.length > 0) {+ const error = result.errors[0];+ res+ .status(error.status)+ .json({ message: error.error ?? error.message });+ return { id: "" }; // dummy return+ }+ if (result.successes.length !== 1) {+ logger.error("Failed to create score", { result });+ throw new Error("Failed to create score");+ }+ return result.successes[0];},}),GET: createAuthedAPIRoute({