🪢 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: move legacy api endpoints to async ingestion (#4109)
Steffen Schmitz07344e89b19f
diff --git a/web/src/features/public-api/types/events.ts b/web/src/features/public-api/types/events.tsindex 3b6d6411ae..7f808111aa 100644--- a/web/src/features/public-api/types/events.ts+++ b/web/src/features/public-api/types/events.ts@@ -1,34 +1,5 @@import { z } from "zod";-import {- CreateEventEvent,- eventTypes,- type ingestionApiSchema,-} from "@langfuse/shared/src/server";-import { v4 as uuidv4 } from "uuid";--/**- * Transforms- */--export const transformEventToIngestionBatch = (- event: z.infer<typeof CreateEventEvent>,-): z.infer<typeof ingestionApiSchema>["batch"] => {- return [- {- id: uuidv4(),- type: eventTypes.OBSERVATION_CREATE,- timestamp: new Date().toISOString(),- body: {- ...event,- type: "EVENT",- },- },- ];-};--/**- * Endpoints- */+import { CreateEventEvent } from "@langfuse/shared/src/server";// POST /eventsexport const PostEventsV1Body = CreateEventEvent;diff --git a/web/src/features/public-api/types/generations.ts b/web/src/features/public-api/types/generations.tsindex e0cce84b69..590f6bbf26 100644--- a/web/src/features/public-api/types/generations.ts+++ b/web/src/features/public-api/types/generations.ts@@ -4,64 +4,7 @@ import { z } from "zod";import {LegacyGenerationsCreateSchema,LegacyGenerationPatchSchema,- eventTypes,- type ingestionApiSchema,} from "@langfuse/shared/src/server";-import { v4 as uuidv4 } from "uuid";--/**- * Transforms- */--export const transformGenerationPostToIngestionBatch = ({- prompt,- completion,- ...generation-}: z.infer<typeof LegacyGenerationsCreateSchema>): z.infer<- typeof ingestionApiSchema->["batch"] => {- return [- {- id: uuidv4(),- type: eventTypes.OBSERVATION_CREATE,- timestamp: new Date().toISOString(),- body: {- ...generation,- type: "GENERATION",- input: prompt,- output: completion,- },- },- ];-};--export const transformGenerationPatchToIngestionBatch = ({- generationId,- prompt,- completion,- ...generation-}: z.infer<typeof LegacyGenerationPatchSchema>): z.infer<- typeof ingestionApiSchema->["batch"] => {- return [- {- id: uuidv4(),- type: eventTypes.OBSERVATION_UPDATE,- timestamp: new Date().toISOString(),- body: {- ...generation,- id: generationId,- type: "GENERATION",- input: prompt,- output: completion,- },- },- ];-};--/**- * Endpoints- */// POST /generationsexport const PostGenerationsV1Body = LegacyGenerationsCreateSchema;diff --git a/web/src/features/public-api/types/spans.ts b/web/src/features/public-api/types/spans.tsindex 9cef52e7ed..7a6a8ed977 100644--- a/web/src/features/public-api/types/spans.ts+++ b/web/src/features/public-api/types/spans.ts@@ -2,58 +2,7 @@ import { z } from "zod";import {LegacySpanPatchSchema,LegacySpanPostSchema,- eventTypes,- type ingestionApiSchema,} from "@langfuse/shared/src/server";-import { v4 } from "uuid";--/**- * Objects- */--/**- * Transforms- */--export const transformLegacySpanPostToIngestionBatch = (- span: z.infer<typeof LegacySpanPostSchema>,-): z.infer<typeof ingestionApiSchema>["batch"] => {- return [- {- id: v4(),- type: eventTypes.OBSERVATION_CREATE,- timestamp: new Date().toISOString(),- body: {- ...span,- type: "SPAN",- },- },- ];-};--export const transformLegacySpanPatchToIngestionBatch = ({- spanId,- ...span-}: z.infer<typeof LegacySpanPatchSchema>): z.infer<- typeof ingestionApiSchema->["batch"] => {- return [- {- id: v4(),- type: eventTypes.OBSERVATION_UPDATE,- timestamp: new Date().toISOString(),- body: {- ...span,- id: spanId,- type: "SPAN",- },- },- ];-};--/**- * Endpoints- */// POST /spansexport const PostSpansV1Body = LegacySpanPostSchema;diff --git a/web/src/pages/api/public/events.ts b/web/src/pages/api/public/events.tsindex e526d66aa2..926bae79df 100644--- a/web/src/pages/api/public/events.ts+++ b/web/src/pages/api/public/events.ts@@ -1,28 +1,44 @@import {PostEventsV1Body,PostEventsV1Response,- transformEventToIngestionBatch,} from "@/src/features/public-api/types/events";import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";import { createAuthedAPIRoute } from "@/src/features/public-api/server/createAuthedAPIRoute";-import { parseSingleTypedIngestionApiResponse } from "@/src/pages/api/public/ingestion";-import { handleBatch } from "@langfuse/shared/src/server";-import { tokenCount } from "@/src/features/ingest/usage";+import { processEventBatch } from "@/src/pages/api/public/ingestion";+import { eventTypes, logger } from "@langfuse/shared/src/server";+import { v4 } from "uuid";export default withMiddlewares({POST: createAuthedAPIRoute({name: "Create Event",bodySchema: PostEventsV1Body,responseSchema: PostEventsV1Response,- fn: async ({ body, auth }) => {- const ingestionBatch = transformEventToIngestionBatch(body);- const result = await handleBatch(ingestionBatch, auth, tokenCount);- const response = parseSingleTypedIngestionApiResponse(- result.errors,- result.results,- PostEventsV1Response,- );- return response;+ fn: async ({ body, auth, res }) => {+ const event = {+ id: v4(),+ type: eventTypes.OBSERVATION_CREATE,+ timestamp: new Date().toISOString(),+ body: {+ ...body,+ type: "EVENT",+ },+ };+ 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 event", { result });+ throw new Error("Failed to create event");+ }+ return { id: event.body.id };},}),});diff --git a/web/src/pages/api/public/generations.ts b/web/src/pages/api/public/generations.tsindex fdbbb03048..dcf554d52f 100644--- a/web/src/pages/api/public/generations.ts+++ b/web/src/pages/api/public/generations.ts@@ -3,14 +3,12 @@ import {PostGenerationsV1Response,PatchGenerationsV1Body,PatchGenerationsV1Response,- transformGenerationPostToIngestionBatch,- transformGenerationPatchToIngestionBatch,} from "@/src/features/public-api/types/generations";import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";import { createAuthedAPIRoute } from "@/src/features/public-api/server/createAuthedAPIRoute";-import { parseSingleTypedIngestionApiResponse } from "@/src/pages/api/public/ingestion";-import { handleBatch } from "@langfuse/shared/src/server";-import { tokenCount } from "@/src/features/ingest/usage";+import { processEventBatch } from "@/src/pages/api/public/ingestion";+import { eventTypes, logger } from "@langfuse/shared/src/server";+import { v4 } from "uuid";export default withMiddlewares({POST: createAuthedAPIRoute({@@ -18,15 +16,35 @@ export default withMiddlewares({bodySchema: PostGenerationsV1Body,responseSchema: PostGenerationsV1Response,rateLimitResource: "legacy-ingestion",- fn: async ({ body, auth }) => {- const ingestionBatch = transformGenerationPostToIngestionBatch(body);- const result = await handleBatch(ingestionBatch, auth, tokenCount);- const response = parseSingleTypedIngestionApiResponse(- result.errors,- result.results,- PostGenerationsV1Response,- );- return response;+ fn: async ({ body, auth, res }) => {+ const { prompt, completion, ...rest } = body;+ const event = {+ id: v4(),+ type: eventTypes.OBSERVATION_CREATE,+ timestamp: new Date().toISOString(),+ body: {+ ...rest,+ type: "GENERATION",+ input: prompt,+ output: completion,+ },+ };+ 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 generation", { result });+ throw new Error("Failed to create generation");+ }+ return { id: event.body.id };},}),PATCH: createAuthedAPIRoute({@@ -34,15 +52,33 @@ export default withMiddlewares({bodySchema: PatchGenerationsV1Body,responseSchema: PatchGenerationsV1Response,rateLimitResource: "legacy-ingestion",- fn: async ({ body, auth }) => {- const ingestionBatch = transformGenerationPatchToIngestionBatch(body);- const result = await handleBatch(ingestionBatch, auth, tokenCount);- const response = parseSingleTypedIngestionApiResponse(- result.errors,- result.results,- PatchGenerationsV1Response,- );- return response;+ fn: async ({ body, auth, res }) => {+ const { generationId, prompt, completion, ...rest } = body;+ const event = {+ id: v4(),+ type: eventTypes.OBSERVATION_UPDATE,+ timestamp: new Date().toISOString(),+ body: {+ ...rest,+ id: generationId,+ type: "GENERATION",+ input: prompt,+ output: completion,+ },+ };+ 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 update generation", { result });+ throw new Error("Failed to update generation");+ }+ return { id: event.body.id };},}),});diff --git a/web/src/pages/api/public/ingestion.ts b/web/src/pages/api/public/ingestion.tsindex 995c4aeabe..2d45fb5a21 100644--- a/web/src/pages/api/public/ingestion.ts+++ b/web/src/pages/api/public/ingestion.ts@@ -1,7 +1,7 @@import { cors, runMiddleware } from "@/src/features/public-api/server/cors";import { type NextApiRequest, type NextApiResponse } from "next";import { z } from "zod";-import { LangfuseNotFoundError, InternalServerError } from "@langfuse/shared";+import { LangfuseNotFoundError } from "@langfuse/shared";import {eventTypes,ingestionEvent,@@ -472,22 +472,6 @@ const sortBatch = (batch: Array<z.infer<typeof ingestionEvent>>) => {return [...others, ...updates];};-export const getBadRequestError = (- errors: Array<unknown>,-): InvalidRequestError[] =>- errors.filter(- (error): error is InvalidRequestError =>- error instanceof InvalidRequestError,- );--export const getLangfuseNotFoundError = (- errors: Array<unknown>,-): LangfuseNotFoundError[] =>- errors.filter(- (error): error is LangfuseNotFoundError =>- error instanceof LangfuseNotFoundError,- );-export const aggregateBatchResult = (errors: Array<{ id: string; error: unknown }>,results: Array<{ id: string; result: unknown }>,@@ -549,47 +533,3 @@ export const aggregateBatchResult = (return { successes, errors: returnedErrors };};--/**- * Parses the response from the ingestion batch API event processor and throws an error of `BaserError` if the response is not as expected.- *- * @param errors - Array of errors from `handleBatch()`- * @param results - Array of results from `handleBatch()`- * @param object - Zod object to parse the result, if not provided, the result is returned as is without parsing- * @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 }>,- object?: T,-): T extends z.ZodTypeAny ? z.infer<T> : unknown => {- const unknownErrors = errors.map((error) => error.error);- const badRequestErrors = getBadRequestError(unknownErrors);- if (badRequestErrors.length > 0) {- throw new InvalidRequestError(badRequestErrors[0].message);- }- const langfuseNotFoundError = getLangfuseNotFoundError(unknownErrors);- if (langfuseNotFoundError.length > 0) {- throw langfuseNotFoundError[0];- }- if (errors.length > 0) {- throw new InternalServerError("Internal Server Error");- }-- if (results.length === 0) {- throw new InternalServerError("No results returned");- }-- if (object === undefined) {- return results[0].result as T extends z.ZodTypeAny ? z.infer<T> : unknown;- }-- const parsedObj = object.safeParse(results[0].result);- if (!parsedObj.success) {- console.error("Error parsing response", parsedObj.error);- traceException(parsedObj.error);- }- // should not fail in prod but just log an exception, see above- return results[0].result as z.infer<T>;-};diff --git a/web/src/pages/api/public/scores/index.ts b/web/src/pages/api/public/scores/index.tsindex 486bdb0366..6693197a72 100644--- a/web/src/pages/api/public/scores/index.ts+++ b/web/src/pages/api/public/scores/index.ts@@ -40,7 +40,7 @@ export default withMiddlewares({logger.error("Failed to create score", { result });throw new Error("Failed to create score");}- return result.successes[0];+ return { id: event.body.id };},}),GET: createAuthedAPIRoute({diff --git a/web/src/pages/api/public/spans.ts b/web/src/pages/api/public/spans.tsindex a455abbd1f..8473e39d46 100644--- a/web/src/pages/api/public/spans.ts+++ b/web/src/pages/api/public/spans.ts@@ -3,44 +3,74 @@ import {PatchSpansV1Response,PostSpansV1Body,PostSpansV1Response,- transformLegacySpanPatchToIngestionBatch,- transformLegacySpanPostToIngestionBatch,} from "@/src/features/public-api/types/spans";import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";import { createAuthedAPIRoute } from "@/src/features/public-api/server/createAuthedAPIRoute";-import { parseSingleTypedIngestionApiResponse } from "@/src/pages/api/public/ingestion";-import { handleBatch } from "@langfuse/shared/src/server";-import { tokenCount } from "@/src/features/ingest/usage";+import { processEventBatch } from "@/src/pages/api/public/ingestion";+import { eventTypes, logger } from "@langfuse/shared/src/server";+import { v4 } from "uuid";export default withMiddlewares({POST: createAuthedAPIRoute({name: "Create Span (Legacy)",bodySchema: PostSpansV1Body,responseSchema: PostSpansV1Response,- fn: async ({ body, auth }) => {- const ingestionBatch = transformLegacySpanPostToIngestionBatch(body);- const result = await handleBatch(ingestionBatch, auth, tokenCount);- const response = parseSingleTypedIngestionApiResponse(- result.errors,- result.results,- PostSpansV1Response,- );- return response;+ fn: async ({ body, auth, res }) => {+ const event = {+ id: v4(),+ type: eventTypes.OBSERVATION_CREATE,+ timestamp: new Date().toISOString(),+ body: {+ ...body,+ type: "SPAN",+ },+ };+ 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 span", { result });+ throw new Error("Failed to create span");+ }+ return { id: event.body.id };},}),PATCH: createAuthedAPIRoute({name: "Update Span (Legacy)",bodySchema: PatchSpansV1Body,responseSchema: PatchSpansV1Response,- fn: async ({ body, auth }) => {- const ingestionBatch = transformLegacySpanPatchToIngestionBatch(body);- const result = await handleBatch(ingestionBatch, auth, tokenCount);- const response = parseSingleTypedIngestionApiResponse(- result.errors,- result.results,- PatchSpansV1Response,- );- return response;+ fn: async ({ body, auth, res }) => {+ const event = {+ id: v4(),+ type: eventTypes.OBSERVATION_UPDATE,+ timestamp: new Date().toISOString(),+ body: {+ ...body,+ id: body.spanId,+ type: "SPAN",+ },+ };+ 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 update span", { result });+ throw new Error("Failed to update span");+ }+ return { id: event.body.id };},}),});diff --git a/web/src/pages/api/public/traces/index.ts b/web/src/pages/api/public/traces/index.tsindex 0186b6dc61..1d3a5b9181 100644--- a/web/src/pages/api/public/traces/index.ts+++ b/web/src/pages/api/public/traces/index.ts@@ -8,18 +8,17 @@ import {import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";import { createAuthedAPIRoute } from "@/src/features/public-api/server/createAuthedAPIRoute";import { Prisma } from "@langfuse/shared/src/db";-import { parseSingleTypedIngestionApiResponse } from "@/src/pages/api/public/ingestion";+import { processEventBatch } from "@/src/pages/api/public/ingestion";import { type Trace } from "@langfuse/shared";import {eventTypes,- handleBatch,+ logger,orderByToPrismaSql,} from "@langfuse/shared/src/server";import { v4 } from "uuid";import { telemetry } from "@/src/features/telemetry";import { tracesTableCols } from "@langfuse/shared";-import { tokenCount } from "@/src/features/ingest/usage";export default withMiddlewares({POST: createAuthedAPIRoute({@@ -27,23 +26,30 @@ export default withMiddlewares({bodySchema: PostTracesV1Body,responseSchema: PostTracesV1Response, // Adjust this if you have a specific response schemarateLimitResource: "legacy-ingestion",- fn: async ({ body, auth }) => {+ fn: async ({ body, auth, res }) => {await telemetry();-const event = {id: v4(),type: eventTypes.TRACE_CREATE,timestamp: new Date().toISOString(),body: body,};-- const result = await handleBatch([event], auth, tokenCount);- const response = parseSingleTypedIngestionApiResponse(- result.errors,- result.results,- PostTracesV1Response,- );- 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 trace", { result });+ throw new Error("Failed to create trace");+ }+ return { id: event.body.id };},}),@@ -61,9 +67,10 @@ export default withMiddlewares({: Prisma.empty;const tagsCondition = query.tags? Prisma.sql`AND ARRAY[${Prisma.join(- (Array.isArray(query.tags) ? query.tags : query.tags.split(',')).map(- (v) => Prisma.sql`${v}`,- ),+ (Array.isArray(query.tags)+ ? query.tags+ : query.tags.split(",")+ ).map((v) => Prisma.sql`${v}`),", ",)}] <@ t."tags"`: Prisma.empty;@@ -169,7 +176,9 @@ export default withMiddlewares({},tags: query.tags? {- hasEvery: Array.isArray(query.tags) ? query.tags : query.tags.split(','),+ hasEvery: Array.isArray(query.tags)+ ? query.tags+ : query.tags.split(","),}: undefined,},