Skip to content

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

feat(core): add server side tracing of LLM invocations (#4317)

Hassieb Pakzada4c040b314f5
diff --git a/.env.dev.example b/.env.dev.example
index 6a3238ca34..bbd886ca57 100644
--- a/.env.dev.example
+++ b/.env.dev.example
@@ -80,8 +80,8 @@ ENCRYPTION_KEY=0000000000000000000000000000000000000000000000000000000000000000
# speeds up local development by not executing init scripts on server startup
NEXT_PUBLIC_LANGFUSE_RUN_NEXT_INIT="false"
-
LANGFUSE_READ_FROM_POSTGRES_ONLY=false
LANGFUSE_RETURN_FROM_CLICKHOUSE=true
LANGFUSE_READ_DASHBOARDS_FROM_CLICKHOUSE=true
LANGFUSE_READ_FROM_CLICKHOUSE_ONLY=true
+
diff --git a/packages/shared/package.json b/packages/shared/package.json
index ccda4115be..16d36f85ea 100644
--- a/packages/shared/package.json
+++ b/packages/shared/package.json
@@ -60,10 +60,10 @@
"@aws-sdk/lib-storage": "^3.675.0",
"@aws-sdk/s3-request-presigner": "^3.679.0",
"@clickhouse/client": "^1.4.0",
- "@langchain/anthropic": "^0.3.1",
- "@langchain/aws": "^0.1.0",
- "@langchain/core": "^0.3.9",
- "@langchain/openai": "^0.3.0",
+ "@langchain/anthropic": "^0.3.8",
+ "@langchain/aws": "^0.1.2",
+ "@langchain/core": "^0.3.18",
+ "@langchain/openai": "^0.3.14",
"@opentelemetry/api": ">=1.0.0 <1.10.0",
"@prisma/client": "^5.22.0",
"@react-email/components": "^0.0.19",
@@ -77,7 +77,8 @@
"exponential-backoff": "^3.1.1",
"ioredis": "^5.4.1",
"kysely": "^0.27.4",
- "langchain": "^0.3.2",
+ "langchain": "^0.3.6",
+ "langfuse-langchain": "3.30.1",
"lodash": "^4.17.21",
"next-auth": "^4.24.7",
"nodemailer": "^6.9.15",
diff --git a/packages/shared/src/env.ts b/packages/shared/src/env.ts
index b6d10298a7..490e3ce7c4 100644
--- a/packages/shared/src/env.ts
+++ b/packages/shared/src/env.ts
@@ -22,7 +22,7 @@ const EnvSchema = z.object({
.string()
.length(
64,
- "ENCRYPTION_KEY must be 256 bits, 64 string characters in hex format, generate via: openssl rand -hex 32"
+ "ENCRYPTION_KEY must be 256 bits, 64 string characters in hex format, generate via: openssl rand -hex 32",
)
.optional(),
LANGFUSE_CACHE_PROMPT_ENABLED: z.enum(["true", "false"]).default("false"),
@@ -30,6 +30,16 @@ const EnvSchema = z.object({
CLICKHOUSE_URL: z.string().url().optional(),
CLICKHOUSE_USER: z.string().optional(),
CLICKHOUSE_PASSWORD: z.string().optional(),
+ LANGFUSE_ASYNC_CLICKHOUSE_INGESTION_PROCESSING: z
+ .enum(["true", "false"])
+ .default("false"),
+ LANGFUSE_ASYNC_INGESTION_PROCESSING: z
+ .enum(["true", "false"])
+ .default("false"),
+ LANGFUSE_INGESTION_QUEUE_DELAY_MS: z.coerce
+ .number()
+ .nonnegative()
+ .default(15_000),
SALT: z.string().optional(), // used by components imported by web package
LANGFUSE_LOG_LEVEL: z
.enum(["trace", "debug", "info", "warn", "error", "fatal"])
diff --git a/packages/shared/src/server/index.ts b/packages/shared/src/server/index.ts
index 55aa6d4075..209eb6baee 100644
--- a/packages/shared/src/server/index.ts
+++ b/packages/shared/src/server/index.ts
@@ -15,6 +15,7 @@ export * from "./clickhouse/schema";
export * from "./repositories/definitions";
export * from "../server/ingestion/types";
export * from "./ingestion/modelMatch";
+export * from "./ingestion/processEventBatch";
export * from "../server/ingestion/types";
export * from "../server/ingestion/validateAndInflateScore";
export * from "./redis/redis";
diff --git a/packages/shared/src/server/ingestion/processEventBatch.ts b/packages/shared/src/server/ingestion/processEventBatch.ts
new file mode 100644
index 0000000000..1c6e0fadd6
--- /dev/null
+++ b/packages/shared/src/server/ingestion/processEventBatch.ts
@@ -0,0 +1,395 @@
+import { randomUUID } from "crypto";
+import { z } from "zod";
+
+import { type Model } from "../../db";
+import { env } from "../../env";
+import {
+ InvalidRequestError,
+ LangfuseNotFoundError,
+ UnauthorizedError,
+} from "../../errors";
+import { AuthHeaderValidVerificationResult } from "../auth/types";
+import { getClickhouseEntityType } from "../clickhouse/schemaUtils";
+import {
+ getCurrentSpan,
+ instrumentAsync,
+ instrumentSync,
+ recordIncrement,
+ traceException,
+} from "../instrumentation";
+import { logger } from "../logger";
+import { LegacyIngestionEventType, QueueJobs } from "../queues";
+import { IngestionQueue } from "../redis/ingestionQueue";
+import { LegacyIngestionQueue } from "../redis/legacyIngestion";
+import { redis } from "../redis/redis";
+import { S3StorageService } from "../services/S3StorageService";
+import { addTracesToTraceUpsertQueue, handleBatch } from "./legacy";
+import { getProcessorForEvent } from "./legacy/EventProcessor";
+import { eventTypes, ingestionEvent, IngestionEventType } from "./types";
+
+export type TokenCountDelegate = (p: {
+ model: Model;
+ text: unknown;
+}) => number | undefined;
+
+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;
+};
+
+export const processEventBatch = async (
+ input: unknown[],
+ authCheck: AuthHeaderValidVerificationResult,
+ tokenCountDelegate: TokenCountDelegate,
+): 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, tokenCountDelegate)) {
+ 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_MS,
+ },
+ )
+ : 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, tokenCountDelegate);
+
+ 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,
+ tokenCountDelegate: TokenCountDelegate,
+): boolean => {
+ try {
+ getProcessorForEvent(event, tokenCountDelegate).auth(authScope.scope);
+ return true;
+ } catch (error) {
+ return false;
+ }
+};
+
+/**
+ * Sorts a batch of ingestion events. Orders by: updating events last, sorted by timestamp asc.
+ */
+const sortBatch = (batch: Array<z.infer<typeof ingestionEvent>>) => {
+ const updateEvents: (typeof eventTypes)[keyof typeof eventTypes][] = [
+ eventTypes.GENERATION_UPDATE,
+ eventTypes.SPAN_UPDATE,
+ eventTypes.OBSERVATION_UPDATE, // legacy event type
+ ];
+ const updates = batch
+ .filter((event) => updateEvents.includes(event.type))
+ .sort((a, b) => {
+ return new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime();
+ });
+ const others = batch
+ .filter((event) => !updateEvents.includes(event.type))
+ .sort((a, b) => {
+ return new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime();
+ });
+
+ // Return the array with non-update events first, followed by update events
+ return [...others, ...updates];
+};
+
+export const aggregateBatchResult = (
+ errors: Array<{ id: string; error: unknown }>,
+ results: Array<{ id: string; result: unknown }>,
+) => {
+ const returnedErrors: {
+ id: string;
+ status: number;
+ message?: string;
+ error?: string;
+ }[] = [];
+
+ const successes: {
+ id: string;
+ status: number;
+ }[] = [];
+
+ errors.forEach((error) => {
+ if (error.error instanceof InvalidRequestError) {
+ returnedErrors.push({
+ id: error.id,
+ status: 400,
+ message: "Invalid request data",
+ error: error.error.message,
+ });
+ } else if (error.error instanceof UnauthorizedError) {
+ returnedErrors.push({
+ id: error.id,
+ status: 401,
+ message: "Authentication error",
+ error: error.error.message,
+ });
+ } else if (error.error instanceof LangfuseNotFoundError) {
+ returnedErrors.push({
+ id: error.id,
+ status: 404,
+ message: "Resource not found",
+ error: error.error.message,
+ });
+ } else {
+ returnedErrors.push({
+ id: error.id,
+ status: 500,
+ error: "Internal Server Error",
+ });
+ }
+ });
+
+ if (returnedErrors.length > 0) {
+ traceException(errors);
+ logger.error("Error processing events", returnedErrors);
+ }
+
+ results.forEach((result) => {
+ successes.push({
+ id: result.id,
+ status: 201,
+ });
+ });
+
+ return { successes, errors: returnedErrors };
+};
diff --git a/packages/shared/src/server/llm/fetchLLMCompletion.ts b/packages/shared/src/server/llm/fetchLLMCompletion.ts
index bccd52ff04..803b4a6d3a 100644
--- a/packages/shared/src/server/llm/fetchLLMCompletion.ts
+++ b/packages/shared/src/server/llm/fetchLLMCompletion.ts
@@ -1,5 +1,7 @@
import type { ZodSchema } from "zod";
+import { CallbackHandler } from "langfuse-langchain";
+
import { ChatAnthropic } from "@langchain/anthropic";
import { ChatBedrockConverse } from "@langchain/aws";
import {
@@ -17,11 +19,27 @@ import {
BedrockConfigSchema,
BedrockCredentialSchema,
} from "../../interfaces/customLLMProviderConfigSchemas";
-
+import { AuthHeaderValidVerificationResult } from "../auth/types";
+import {
+ processEventBatch,
+ type TokenCountDelegate,
+} from "../ingestion/processEventBatch";
+import { logger } from "../logger";
import { ChatMessage, ChatMessageRole, LLMAdapter, ModelParams } from "./types";
import type { BaseCallbackHandler } from "@langchain/core/callbacks/base";
+type ProcessTracedEvents = () => Promise<void>;
+
+type TraceParams = {
+ traceName: string;
+ traceId: string;
+ projectId: string;
+ tags: string[];
+ tokenCountDelegate: TokenCountDelegate;
+ authCheck: AuthHeaderValidVerificationResult;
+};
+
type LLMCompletionParams = {
messages: ChatMessage[];
modelParams: ModelParams;
@@ -31,6 +49,7 @@ type LLMCompletionParams = {
apiKey: string;
maxRetries?: number;
config?: Record<string, string> | null;
+ traceParams?: TraceParams;
};
type FetchLLMCompletionParams = LLMCompletionParams & {
@@ -40,25 +59,34 @@ type FetchLLMCompletionParams = LLMCompletionParams & {
export async function fetchLLMCompletion(
params: LLMCompletionParams & {
streaming: true;
- }
-): Promise<IterableReadableStream<Uint8Array>>;
+ },
+): Promise<{
+ completion: IterableReadableStream<Uint8Array>;
+ processTracedEvents: ProcessTracedEvents;
+}>;
export async function fetchLLMCompletion(
params: LLMCompletionParams & {
streaming: false;
- }
-): Promise<string>;
+ },
+): Promise<{ completion: string; processTracedEvents: ProcessTracedEvents }>;
export async function fetchLLMCompletion(
params: LLMCompletionParams & {
streaming: false;
structuredOutputSchema: ZodSchema;
- }
-): Promise<unknown>;
+ },
+): Promise<{
+ completion: unknown;
+ processTracedEvents: ProcessTracedEvents;
+}>;
export async function fetchLLMCompletion(
- params: FetchLLMCompletionParams
-): Promise<string | IterableReadableStream<Uint8Array> | unknown> {
+ params: FetchLLMCompletionParams,
+): Promise<{
+ completion: string | IterableReadableStream<Uint8Array> | unknown;
+ processTracedEvents: ProcessTracedEvents;
+}> {
// the apiKey must never be printed to the console
const {
messages,
@@ -69,8 +97,38 @@ export async function fetchLLMCompletion(
baseURL,
maxRetries,
config,
+ traceParams,
} = params;
+ let finalCallbacks: BaseCallbackHandler[] | undefined = callbacks ?? [];
+ let processTracedEvents: ProcessTracedEvents = () => Promise.resolve();
+
+ if (traceParams) {
+ const handler = new CallbackHandler({
+ _projectId: traceParams.projectId,
+ tags: traceParams.tags,
+ });
+
+ finalCallbacks.push(handler);
+
+ processTracedEvents = async () => {
+ try {
+ const events = await handler.langfuse._exportLocalEvents(
+ traceParams.projectId,
+ );
+ await processEventBatch(
+ JSON.parse(JSON.stringify(events)), // stringify to emulate network event batch from network call
+ traceParams.authCheck,
+ traceParams.tokenCountDelegate,
+ );
+ } catch (e) {
+ logger.error("Failed to process traced events", { error: e });
+ }
+ };
+ }
+
+ finalCallbacks = finalCallbacks.length > 0 ? finalCallbacks : undefined;
+
const finalMessages = messages.map((message) => {
if (message.role === ChatMessageRole.User)
return new HumanMessage(message.content);
@@ -89,7 +147,7 @@ export async function fetchLLMCompletion(
temperature: modelParams.temperature,
maxTokens: modelParams.max_tokens,
topP: modelParams.top_p,
- callbacks,
+ callbacks: finalCallbacks,
clientOptions: { maxRetries },
});
} else if (modelParams.adapter === LLMAdapter.OpenAI) {
@@ -100,7 +158,7 @@ export async function fetchLLMCompletion(
maxTokens: modelParams.max_tokens,
topP: modelParams.top_p,
streamUsage: false, // https://github.com/langchain-ai/langchainjs/issues/6533
- callbacks,
+ callbacks: finalCallbacks,
maxRetries,
configuration: {
baseURL,
@@ -115,7 +173,7 @@ export async function fetchLLMCompletion(
temperature: modelParams.temperature,
maxTokens: modelParams.max_tokens,
topP: modelParams.top_p,
- callbacks,
+ callbacks: finalCallbacks,
maxRetries,
});
} else if (modelParams.adapter === LLMAdapter.Bedrock) {
@@ -129,7 +187,7 @@ export async function fetchLLMCompletion(
temperature: modelParams.temperature,
maxTokens: modelParams.max_tokens,
topP: modelParams.top_p,
- callbacks,
+ callbacks: finalCallbacks,
maxRetries,
});
} else {
@@ -139,9 +197,16 @@ export async function fetchLLMCompletion(
}
if (params.structuredOutputSchema) {
- return await (chatModel as ChatOpenAI) // Typecast necessary due to https://github.com/langchain-ai/langchainjs/issues/6795
- .withStructuredOutput(params.structuredOutputSchema)
- .invoke(finalMessages);
+ return {
+ completion: await (chatModel as ChatOpenAI) // Typecast necessary due to https://github.com/langchain-ai/langchainjs/issues/6795
+ .withStructuredOutput(params.structuredOutputSchema)
+ .invoke(finalMessages, {
+ callbacks: finalCallbacks,
+ runId: traceParams?.traceId,
+ runName: traceParams?.traceName,
+ }),
+ processTracedEvents,
+ };
}
/*
@@ -157,27 +222,40 @@ export async function fetchLLMCompletion(
Reference: https://platform.openai.com/docs/guides/reasoning/beta-limitations
*/
if (modelParams.model.startsWith("o1-")) {
- return await new ChatOpenAI({
- openAIApiKey: apiKey,
- modelName: modelParams.model,
- temperature: 1,
- maxTokens: undefined,
- topP: undefined,
- callbacks,
- maxRetries,
- configuration: {
- baseURL,
- },
- })
- .pipe(new StringOutputParser())
- .invoke(
- finalMessages.filter((message) => message._getType() !== "system")
- );
+ return {
+ completion: await new ChatOpenAI({
+ openAIApiKey: apiKey,
+ modelName: modelParams.model,
+ temperature: 1,
+ maxTokens: undefined,
+ topP: undefined,
+ callbacks,
+ maxRetries,
+ configuration: {
+ baseURL,
+ },
+ })
+ .pipe(new StringOutputParser())
+ .invoke(
+ finalMessages.filter((message) => message._getType() !== "system"),
+ ),
+ processTracedEvents,
+ };
}
if (streaming) {
- return chatModel.pipe(new BytesOutputParser()).stream(finalMessages);
+ return {
+ completion: await chatModel
+ .pipe(new BytesOutputParser())
+ .stream(finalMessages),
+ processTracedEvents,
+ };
}
- return await chatModel.pipe(new StringOutputParser()).invoke(finalMessages);
+ return {
+ completion: await chatModel
+ .pipe(new StringOutputParser())
+ .invoke(finalMessages),
+ processTracedEvents,
+ };
}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index ba19a24cc3..5f22a83f81 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -141,17 +141,17 @@ importers:
specifier: ^1.4.0
version: 1.4.0
'@langchain/anthropic':
- specifier: ^0.3.1
+ specifier: ^0.3.8
'@langchain/aws':
- specifier: ^0.1.0
+ specifier: ^0.1.2
'@langchain/core':
- specifier: ^0.3.9
+ specifier: ^0.3.18
'@langchain/openai':
- specifier: ^0.3.0
+ specifier: ^0.3.14
'@opentelemetry/api':
specifier: '>=1.0.0 <1.10.0'
version: 1.9.0
@@ -195,8 +195,11 @@ importers:
specifier: ^0.27.4
version: 0.27.4
langchain:
- specifier: ^0.3.2
+ specifier: ^0.3.6
+ langfuse-langchain:
+ specifier: 3.30.1
lodash:
specifier: ^4.17.21
version: 4.17.21
@@ -337,14 +340,14 @@ importers:
specifier: ^3.3.4
'@langchain/anthropic':
- specifier: ^0.3.1
+ specifier: ^0.3.8
'@langchain/core':
- specifier: ^0.3.9
+ specifier: ^0.3.18
'@langchain/openai':
- specifier: ^0.3.0
+ specifier: ^0.3.14
'@langfuse/ee':
specifier: workspace:*
version: link:../ee
@@ -521,7 +524,7 @@ importers:
ai:
specifier: ^3.4.9
bcryptjs:
specifier: ^2.4.3
version: 2.4.3
@@ -571,8 +574,8 @@ importers:
specifier: ^0.27.4
version: 0.27.4
langchain:
- specifier: ^0.3.2
+ specifier: ^0.3.6
lodash:
specifier: ^4.17.21
version: 4.17.21
@@ -2307,24 +2310,24 @@ packages:
peerDependencies:
jsep: ^0.4.0||^1.0.0
- '@langchain/[email protected]':
- resolution: {integrity: sha512-mE2zfv2IeogDgP53IYlfqZuXbmACkQDtBkg1Nriasrzvr1g+1Q85pfyUCnxc05p4S2IplbJhvoBtgdQUTGenqw==}
+ '@langchain/[email protected]':
+ resolution: {integrity: sha512-7qeRDhNnCf1peAbjY825R2HNszobJeGvqi2cfPl+YsduDIYEGUzfoGRRarPI5joIGX5YshCsch6NFtap2bLfmw==}
engines: {node: '>=18'}
peerDependencies:
'@langchain/core': '>=0.2.21 <0.4.0'
- '@langchain/[email protected]':
- resolution: {integrity: sha512-EIrDmR7wvo9PdcITjBJ0PnNSblgOLOxmBwX0uhfdxFA4AYmp1i4peaFcLqCrziMqR1w4Ndr2+soPFkghuKRX2Q==}
+ '@langchain/[email protected]':
+ resolution: {integrity: sha512-1cQvv8XSbaZXceAbYexSm/8WLqfEJ4VF6qbf/XLwkpUKMFGqpSBA00+Bn5p8K/Ms+PyMguZrxVNqd6daqxhDBQ==}
engines: {node: '>=18'}
peerDependencies:
'@langchain/core': '>=0.2.21 <0.4.0'
- '@langchain/[email protected]':
- resolution: {integrity: sha512-Rttr9FuFwU+CWIoEyuLqQUPYg+3pKL1YpDgo3nvoDVhinoHqwGQ7aNGzZ/Sf+qASMi76sPSLm+75pHMJwwOiWg==}
+ '@langchain/[email protected]':
+ resolution: {integrity: sha512-IEZCrFs1Xd0J2FTH1D3Lnm3/Yk2r8LSpwDeLYwcCom3rNAK5k4mKQ2rwIpNq3YuqBdrTNMKRO+PopjkP1SB17A==}
engines: {node: '>=18'}
- '@langchain/[email protected]':
- resolution: {integrity: sha512-yXrz5Qn3t9nq3NQAH2l4zZOI4ev2CFdLC5kvmi5SdW4bggRuM40SXTUAY3VRld4I5eocYfk82VbrlA+6dvN5EA==}
+ '@langchain/[email protected]':
+ resolution: {integrity: sha512-lNWjUo1tbvsss45IF7UQtMu1NJ6oUKvhgPYWXnX9f/d6OmuLu7D99HQ3Y88vLcUo9XjjOy417olYHignMduMjA==}
engines: {node: '>=18'}
peerDependencies:
'@langchain/core': '>=0.2.26 <0.4.0'
@@ -8047,9 +8050,6 @@ packages:
resolution: {integrity: sha512-cEiJEAEoIbWfCZYKWhVwFuvPX1gETRYPw6LlaTKoxD3s2AkXzkCjnp6h0V77ozyqj0jakteJ4YqDJT830+lVGw==}
engines: {node: '>=14'}
- resolution: {integrity: sha512-Pk3l3WOgM9joguZY2k52+jH82RtABRgB5RdGFZNUGbOKGMVlNmafcPA3b0ITcCZPu1L9UclP1tne6aw7ZI4Myg==}
-
resolution: {integrity: sha512-65ruOWWXDEZHHbAo7EjOcNxOGasQKbL4Fq3jEr2xsCqSsoOo6VVSqzWQb6PRIqypFSDcma4jO90YP0w5X8qVXQ==}
@@ -8205,8 +8205,8 @@ packages:
resolution: {integrity: sha512-dyNKv2KRvYOQPLCAOCjjQuCk4YFd33BvGdf/o5bC7FiW+BB6snA81Zt+2wT9QDFzKqxKa5rrOmvlK/anehCcgA==}
engines: {node: '>=14.0.0'}
- resolution: {integrity: sha512-kd2kz1cS/PIVrLEDFlrZsAasQfPLbY1UqCZbRKa3/QcpB33/n6xPDvXSMfBuKhvNj0bjW6MXDR9HZTduXjJBgg==}
+ resolution: {integrity: sha512-erZOIKXzwCOrQHqY9AyjkQmaX62zUap1Sigw1KrwMUOnVoLKkVNRmAyxFlNZDZ9jLs/58MaQcaT9ReJtbj3x6w==}
engines: {node: '>=18'}
peerDependencies:
'@langchain/anthropic': '*'
@@ -8251,12 +8251,26 @@ packages:
typeorm:
optional: true
+ resolution: {integrity: sha512-tdHPqAKGtn4mhZXQ5RBGQHDccwG0xGlhQ4v3Shyzp09SXARNJ74lgnpp51bv1vHyTiKZvBGUcOoOOkItzj82cw==}
+ engines: {node: '>=18'}
+
+ resolution: {integrity: sha512-Edqfgtj3jOLbr+1nIzDPDs67//zkYGe/TVGvdFeCHw48AgjTXKB2eBWeQiYegaRZ/0lJm9/zmsk/9jzUZuJV5g==}
+ engines: {node: '>=18'}
+ peerDependencies:
+ langchain: '>=0.0.157 <0.4.0'
+
+ resolution: {integrity: sha512-nTJVuT/4Wrzg4OEtTxfywhO8taSdIaJ7Hn4yUu8SqDyxoLSrxEW0sM14EVaGAVfVhUThlKxcXmevmw1+BqnjWw==}
+ engines: {node: '>=18'}
+
resolution: {integrity: sha512-+Ez9EoiByeoTu/2BXmEaZ06iPNXM6thWJp02KfBO/raSMyCJ4jw7AkWWa+zBCTm0+Tw1Fj9FOxdqSskyN5nAwg==}
engines: {node: '>=16.0.0'}
- resolution: {integrity: sha512-dW+z6s538zBswFFP2w/xzvVef7y2+yNt6GkmRCeLtwfpbMaM4di7JboK3vmnZ+0/LjNb2ukiMmgsTNKu/Y43cg==}
+ resolution: {integrity: sha512-dA+l7ZEh1Q9Q9FcE39PUSSEMfsFo73R2V81fRo5KSlGNcypOEhoQvv6lbjyZP7MHmt3/9pPcfpuRd5Y4RbFYqQ==}
peerDependencies:
openai: '*'
peerDependenciesMeta:
@@ -9058,8 +9072,8 @@ packages:
resolution: {integrity: sha512-MVHddDVweXZF3awtlAS+6pgKLlm/JgxZ90+/NBurBoQctVOOB/zDdVjcyPzQ+0laDGbsWgrRkflI65sQeOgT9Q==}
engines: {node: '>=8'}
- resolution: {integrity: sha512-Aa6i4oBR1tV8E2d2p3MvXg57X98i8gZtHq4bQNX274qLKZVX7PXXq5P1FMonTXOrX3zwvkqN1iNccn3XK3CwVg==}
+ resolution: {integrity: sha512-hFqG9BWCs7L7ifrhJXw7mJXmUBr7d9N6If3J9563o0jfwVA4wFANFDDaOIWFdgDdwgCXg5emf0Q+LoLCGszQYA==}
hasBin: true
peerDependencies:
zod: ^3.23.8
@@ -11611,7 +11625,7 @@ snapshots:
'@aws-sdk/client-sso-oidc': 3.675.0(@aws-sdk/[email protected])
'@aws-sdk/client-sts': 3.675.0
'@aws-sdk/core': 3.667.0
- '@aws-sdk/credential-provider-node': 3.675.0(@aws-sdk/[email protected](@aws-sdk/[email protected]))(@aws-sdk/[email protected])
+ '@aws-sdk/credential-provider-node': 3.675.0(@aws-sdk/[email protected](@aws-sdk/[email protected]))(@aws-sdk/[email protected])
'@aws-sdk/middleware-host-header': 3.667.0
'@aws-sdk/middleware-logger': 3.667.0
'@aws-sdk/middleware-recursion-detection': 3.667.0
@@ -11707,7 +11721,7 @@ snapshots:
'@aws-sdk/client-sso-oidc': 3.675.0(@aws-sdk/[email protected])
'@aws-sdk/client-sts': 3.675.0
'@aws-sdk/core': 3.667.0
- '@aws-sdk/credential-provider-node': 3.675.0(@aws-sdk/[email protected](@aws-sdk/[email protected]))(@aws-sdk/[email protected])
+ '@aws-sdk/credential-provider-node': 3.675.0(@aws-sdk/[email protected](@aws-sdk/[email protected]))(@aws-sdk/[email protected])
'@aws-sdk/middleware-bucket-endpoint': 3.667.0
'@aws-sdk/middleware-expect-continue': 3.667.0
'@aws-sdk/middleware-flexible-checksums': 3.669.0
@@ -12096,14 +12110,14 @@ snapshots:
- '@aws-sdk/client-sso-oidc'
- aws-crt
dependencies:
'@aws-sdk/client-sts': 3.668.0
'@aws-sdk/core': 3.667.0
'@aws-sdk/credential-provider-env': 3.667.0
'@aws-sdk/credential-provider-http': 3.667.0
'@aws-sdk/credential-provider-process': 3.667.0
- '@aws-sdk/credential-provider-sso': 3.668.0(@aws-sdk/[email protected](@aws-sdk/[email protected]))
+ '@aws-sdk/credential-provider-sso': 3.675.0(@aws-sdk/[email protected](@aws-sdk/[email protected]))
'@aws-sdk/credential-provider-web-identity': 3.667.0(@aws-sdk/[email protected])
'@aws-sdk/types': 3.667.0
'@smithy/credential-provider-imds': 3.2.4
@@ -12115,14 +12129,14 @@ snapshots:
- '@aws-sdk/client-sso-oidc'
- aws-crt
dependencies:
'@aws-sdk/client-sts': 3.675.0
'@aws-sdk/core': 3.667.0
'@aws-sdk/credential-provider-env': 3.667.0
'@aws-sdk/credential-provider-http': 3.667.0
'@aws-sdk/credential-provider-process': 3.667.0
- '@aws-sdk/credential-provider-sso': 3.668.0(@aws-sdk/[email protected](@aws-sdk/[email protected]))
+ '@aws-sdk/credential-provider-sso': 3.675.0(@aws-sdk/[email protected](@aws-sdk/[email protected]))
'@aws-sdk/credential-provider-web-identity': 3.667.0(@aws-sdk/[email protected])
'@aws-sdk/types': 3.667.0
'@smithy/credential-provider-imds': 3.2.4
@@ -12133,16 +12147,15 @@ snapshots:
transitivePeerDependencies:
- '@aws-sdk/client-sso-oidc'
- aws-crt
- optional: true
+ '@aws-sdk/[email protected](@aws-sdk/[email protected])':
dependencies:
'@aws-sdk/client-sts': 3.675.0
'@aws-sdk/core': 3.667.0
'@aws-sdk/credential-provider-env': 3.667.0
'@aws-sdk/credential-provider-http': 3.667.0
'@aws-sdk/credential-provider-process': 3.667.0
- '@aws-sdk/credential-provider-sso': 3.675.0(@aws-sdk/[email protected](@aws-sdk/[email protected]))
+ '@aws-sdk/credential-provider-sso': 3.675.0(@aws-sdk/[email protected](@aws-sdk/[email protected]))
'@aws-sdk/credential-provider-web-identity': 3.667.0(@aws-sdk/[email protected])
'@aws-sdk/types': 3.667.0
'@smithy/credential-provider-imds': 3.2.4
@@ -12153,6 +12166,7 @@ snapshots:
transitivePeerDependencies:
- '@aws-sdk/client-sso-oidc'
- aws-crt
+ optional: true
dependencies:
@@ -12173,13 +12187,13 @@ snapshots:
- '@aws-sdk/client-sts'
- aws-crt
dependencies:
'@aws-sdk/credential-provider-env': 3.667.0
'@aws-sdk/credential-provider-http': 3.667.0
- '@aws-sdk/credential-provider-ini': 3.668.0(@aws-sdk/[email protected](@aws-sdk/[email protected]))(@aws-sdk/[email protected])
+ '@aws-sdk/credential-provider-ini': 3.675.0(@aws-sdk/[email protected](@aws-sdk/[email protected]))(@aws-sdk/[email protected])
'@aws-sdk/credential-provider-process': 3.667.0
- '@aws-sdk/credential-provider-sso': 3.668.0(@aws-sdk/[email protected](@aws-sdk/[email protected]))
+ '@aws-sdk/credential-provider-sso': 3.675.0(@aws-sdk/[email protected](@aws-sdk/[email protected]))
'@aws-sdk/credential-provider-web-identity': 3.667.0(@aws-sdk/[email protected])
'@aws-sdk/types': 3.667.0
'@smithy/credential-provider-imds': 3.2.4
@@ -12192,27 +12206,7 @@ snapshots:
- '@aws-sdk/client-sts'
- aws-crt
- dependencies:
- '@aws-sdk/credential-provider-env': 3.667.0
- '@aws-sdk/credential-provider-http': 3.667.0
- '@aws-sdk/credential-provider-ini': 3.668.0(@aws-sdk/[email protected](@aws-sdk/[email protected]))(@aws-sdk/[email protected])
- '@aws-sdk/credential-provider-process': 3.667.0
- '@aws-sdk/credential-provider-sso': 3.668.0(@aws-sdk/[email protected](@aws-sdk/[email protected]))
- '@aws-sdk/credential-provider-web-identity': 3.667.0(@aws-sdk/[email protected])
- '@aws-sdk/types': 3.667.0
- '@smithy/credential-provider-imds': 3.2.4
- '@smithy/property-provider': 3.1.7
- '@smithy/shared-ini-file-loader': 3.1.8
- '@smithy/types': 3.5.0
- tslib: 2.6.3
- transitivePeerDependencies:
- - '@aws-sdk/client-sso-oidc'
- - '@aws-sdk/client-sts'
- - aws-crt
- optional: true
-
dependencies:
'@aws-sdk/credential-provider-env': 3.667.0
'@aws-sdk/credential-provider-http': 3.667.0
@@ -12231,13 +12225,13 @@ snapshots:
- '@aws-sdk/client-sts'
- aws-crt
+ '@aws-sdk/[email protected](@aws-sdk/[email protected])':
dependencies:
'@aws-sdk/credential-provider-env': 3.667.0
'@aws-sdk/credential-provider-http': 3.667.0
- '@aws-sdk/credential-provider-ini': 3.675.0(@aws-sdk/[email protected](@aws-sdk/[email protected]))(@aws-sdk/[email protected])
+ '@aws-sdk/credential-provider-ini': 3.675.0(@aws-sdk/[email protected])
'@aws-sdk/credential-provider-process': 3.667.0
- '@aws-sdk/credential-provider-sso': 3.675.0(@aws-sdk/[email protected](@aws-sdk/[email protected]))
+ '@aws-sdk/credential-provider-sso': 3.675.0(@aws-sdk/[email protected](@aws-sdk/[email protected]))
'@aws-sdk/credential-provider-web-identity': 3.667.0(@aws-sdk/[email protected])
'@aws-sdk/types': 3.667.0
'@smithy/credential-provider-imds': 3.2.4
@@ -12249,6 +12243,7 @@ snapshots:
- '@aws-sdk/client-sso-oidc'
- '@aws-sdk/client-sts'
- aws-crt
+ optional: true
'@aws-sdk/[email protected]':
dependencies:
@@ -12273,11 +12268,11 @@ snapshots:
- '@aws-sdk/client-sso-oidc'
- aws-crt
- '@aws-sdk/[email protected](@aws-sdk/[email protected](@aws-sdk/[email protected]))':
+ '@aws-sdk/[email protected](@aws-sdk/[email protected](@aws-sdk/[email protected]))':
dependencies:
- '@aws-sdk/client-sso': 3.668.0
+ '@aws-sdk/client-sso': 3.675.0
'@aws-sdk/core': 3.667.0
- '@aws-sdk/token-providers': 3.667.0(@aws-sdk/[email protected](@aws-sdk/[email protected]))
+ '@aws-sdk/token-providers': 3.667.0(@aws-sdk/[email protected](@aws-sdk/[email protected]))
'@aws-sdk/types': 3.667.0
'@smithy/property-provider': 3.1.7
'@smithy/shared-ini-file-loader': 3.1.8
@@ -13701,23 +13696,23 @@ snapshots:
dependencies:
jsep: 1.3.9
dependencies:
'@anthropic-ai/sdk': 0.27.3
- '@langchain/core': 0.3.9([email protected]([email protected]))
+ '@langchain/core': 0.3.18([email protected]([email protected]))
fast-xml-parser: 4.5.0
zod: 3.23.8
zod-to-json-schema: 3.23.5([email protected])
transitivePeerDependencies:
- encoding
dependencies:
'@aws-sdk/client-bedrock-agent-runtime': 3.668.0
'@aws-sdk/client-bedrock-runtime': 3.668.0
'@aws-sdk/client-kendra': 3.668.0
- '@aws-sdk/credential-provider-node': 3.668.0(@aws-sdk/[email protected](@aws-sdk/[email protected]))(@aws-sdk/[email protected])
- '@langchain/core': 0.3.9([email protected]([email protected]))
+ '@aws-sdk/credential-provider-node': 3.675.0(@aws-sdk/[email protected](@aws-sdk/[email protected]))(@aws-sdk/[email protected])
+ '@langchain/core': 0.3.18([email protected]([email protected]))
zod: 3.23.8
zod-to-json-schema: 3.23.5([email protected])
transitivePeerDependencies:
@@ -13725,13 +13720,13 @@ snapshots:
- '@aws-sdk/client-sts'
- aws-crt
dependencies:
'@aws-sdk/client-bedrock-agent-runtime': 3.668.0
'@aws-sdk/client-bedrock-runtime': 3.668.0
'@aws-sdk/client-kendra': 3.668.0
- '@aws-sdk/credential-provider-node': 3.668.0(@aws-sdk/[email protected](@aws-sdk/[email protected]))(@aws-sdk/[email protected])
- '@langchain/core': 0.3.9([email protected]([email protected]))
+ '@aws-sdk/credential-provider-node': 3.675.0(@aws-sdk/[email protected])
+ '@langchain/core': 0.3.18([email protected]([email protected]))
zod: 3.23.8
zod-to-json-schema: 3.23.5([email protected])
transitivePeerDependencies:
@@ -13740,13 +13735,13 @@ snapshots:
- aws-crt
optional: true
dependencies:
ansi-styles: 5.2.0
camelcase: 6.3.0
decamelize: 1.2.0
js-tiktoken: 1.0.15
mustache: 4.2.0
p-queue: 6.6.2
p-retry: 4.6.2
@@ -13756,19 +13751,19 @@ snapshots:
transitivePeerDependencies:
- openai
dependencies:
- '@langchain/core': 0.3.9([email protected]([email protected]))
- js-tiktoken: 1.0.14
- openai: 4.62.1([email protected])
+ '@langchain/core': 0.3.18([email protected]([email protected]))
+ js-tiktoken: 1.0.15
+ openai: 4.72.0([email protected])
zod: 3.23.8
zod-to-json-schema: 3.23.5([email protected])
transitivePeerDependencies:
- encoding
dependencies:
- '@langchain/core': 0.3.9([email protected]([email protected]))
+ '@langchain/core': 0.3.18([email protected]([email protected]))
js-tiktoken: 1.0.15
'@lezer/[email protected]': {}
@@ -17056,10 +17051,10 @@ snapshots:
'@typescript-eslint/eslint-plugin': 7.3.1(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected])
'@typescript-eslint/parser': 7.12.0([email protected])([email protected])
eslint-config-prettier: 9.1.0([email protected])
+ eslint-import-resolver-alias: 1.1.2([email protected])
+ eslint-import-resolver-typescript: 3.6.1(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected])
eslint-plugin-eslint-comments: 3.2.0([email protected])
eslint-plugin-jsx-a11y: 6.8.0([email protected])
@@ -17331,7 +17326,7 @@ snapshots:
clean-stack: 2.2.0
indent-string: 4.0.0
dependencies:
'@ai-sdk/provider': 0.0.24
'@ai-sdk/provider-utils': 1.0.20([email protected])
@@ -17348,7 +17343,7 @@ snapshots:
secure-json-parse: 2.7.0
zod-to-json-schema: 3.23.2([email protected])
optionalDependencies:
- openai: 4.62.1([email protected])
+ openai: 4.72.0([email protected])
react: 18.2.0
sswr: 2.1.0([email protected])
svelte: 4.2.19
@@ -18939,7 +18934,7 @@ snapshots:
eslint: 8.57.0
eslint-import-resolver-node: 0.3.9
eslint-import-resolver-typescript: 3.6.1(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected])([email protected])
eslint-plugin-jsx-a11y: 6.8.0([email protected])
eslint-plugin-react: 7.34.1([email protected])
eslint-plugin-react-hooks: 4.6.0([email protected])
@@ -18956,7 +18951,7 @@ snapshots:
dependencies:
eslint: 8.57.0
eslint-plugin-n: 16.6.2([email protected])
eslint-plugin-promise: 6.4.0([email protected])
@@ -18965,9 +18960,9 @@ snapshots:
eslint: 8.57.0
eslint-plugin-turbo: 1.13.4([email protected])
dependencies:
dependencies:
@@ -18982,8 +18977,8 @@ snapshots:
debug: 4.3.7([email protected])
enhanced-resolve: 5.17.1
eslint: 8.57.0
fast-glob: 3.3.2
get-tsconfig: 4.8.1
is-core-module: 2.15.1
@@ -18994,13 +18989,13 @@ snapshots:
- eslint-import-resolver-webpack
- supports-color
dependencies:
debug: 4.3.7([email protected])
enhanced-resolve: 5.17.1
eslint: 8.57.0
fast-glob: 3.3.2
get-tsconfig: 4.8.1
is-core-module: 2.15.1
@@ -19011,25 +19006,25 @@ snapshots:
- eslint-import-resolver-webpack
- supports-color
dependencies:
debug: 3.2.7
optionalDependencies:
'@typescript-eslint/parser': 7.12.0([email protected])([email protected])
eslint: 8.57.0
eslint-import-resolver-node: 0.3.9
- eslint-import-resolver-typescript: 3.6.1(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected])([email protected])
+ eslint-import-resolver-typescript: 3.6.1(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected])
transitivePeerDependencies:
- supports-color
dependencies:
debug: 3.2.7
optionalDependencies:
'@typescript-eslint/parser': 7.12.0([email protected])([email protected])
eslint: 8.57.0
eslint-import-resolver-node: 0.3.9
+ eslint-import-resolver-typescript: 3.6.1(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected])([email protected])
transitivePeerDependencies:
- supports-color
@@ -19046,7 +19041,7 @@ snapshots:
eslint: 8.57.0
ignore: 5.3.1
dependencies:
array-includes: 3.1.7
array.prototype.findlastindex: 1.2.4
@@ -19056,7 +19051,7 @@ snapshots:
doctrine: 2.1.0
eslint: 8.57.0
eslint-import-resolver-node: 0.3.9
hasown: 2.0.2
is-core-module: 2.15.1
is-glob: 4.0.3
@@ -20812,10 +20807,6 @@ snapshots:
- dependencies:
- base64-js: 1.5.1
-
dependencies:
base64-js: 1.5.1
@@ -20952,15 +20943,15 @@ snapshots:
dependencies:
- '@langchain/core': 0.3.9([email protected]([email protected]))
- '@langchain/openai': 0.3.0(@langchain/[email protected]([email protected]([email protected])))
- '@langchain/textsplitters': 0.1.0(@langchain/[email protected]([email protected]([email protected])))
- js-tiktoken: 1.0.14
+ '@langchain/core': 0.3.18([email protected]([email protected]))
+ '@langchain/openai': 0.3.14(@langchain/[email protected]([email protected]([email protected])))
+ '@langchain/textsplitters': 0.1.0(@langchain/[email protected]([email protected]([email protected])))
+ js-tiktoken: 1.0.15
js-yaml: 4.1.0
jsonpointer: 5.0.1
openapi-types: 12.1.3
p-retry: 4.6.2
uuid: 10.0.0
@@ -20968,23 +20959,23 @@ snapshots:
zod: 3.23.8
zod-to-json-schema: 3.23.5([email protected])
optionalDependencies:
- '@langchain/anthropic': 0.3.1(@langchain/[email protected]([email protected]([email protected])))
- '@langchain/aws': 0.1.0(@aws-sdk/[email protected](@aws-sdk/[email protected]))(@aws-sdk/[email protected])(@langchain/[email protected]([email protected]([email protected])))
+ '@langchain/anthropic': 0.3.8(@langchain/[email protected]([email protected]([email protected])))
+ '@langchain/aws': 0.1.2(@aws-sdk/[email protected](@aws-sdk/[email protected]))(@aws-sdk/[email protected])(@langchain/[email protected]([email protected]([email protected])))
axios: 1.7.7
handlebars: 4.7.8
transitivePeerDependencies:
- encoding
- openai
dependencies:
- '@langchain/core': 0.3.9([email protected]([email protected]))
- '@langchain/openai': 0.3.0(@langchain/[email protected]([email protected]([email protected])))
- '@langchain/textsplitters': 0.1.0(@langchain/[email protected]([email protected]([email protected])))
- js-tiktoken: 1.0.14
+ '@langchain/core': 0.3.18([email protected]([email protected]))
+ '@langchain/openai': 0.3.14(@langchain/[email protected]([email protected]([email protected])))
+ '@langchain/textsplitters': 0.1.0(@langchain/[email protected]([email protected]([email protected])))
+ js-tiktoken: 1.0.15
js-yaml: 4.1.0
jsonpointer: 5.0.1
openapi-types: 12.1.3
p-retry: 4.6.2
uuid: 10.0.0
@@ -20992,14 +20983,28 @@ snapshots:
zod: 3.23.8
zod-to-json-schema: 3.23.5([email protected])
optionalDependencies:
- '@langchain/anthropic': 0.3.1(@langchain/[email protected]([email protected]([email protected])))
- '@langchain/aws': 0.1.0(@aws-sdk/[email protected](@aws-sdk/[email protected]))(@aws-sdk/[email protected])(@langchain/[email protected]([email protected]([email protected])))
+ '@langchain/anthropic': 0.3.8(@langchain/[email protected]([email protected]([email protected])))
+ '@langchain/aws': 0.1.2(@aws-sdk/[email protected])(@langchain/[email protected]([email protected]([email protected])))
axios: 1.7.7
handlebars: 4.7.8
transitivePeerDependencies:
- encoding
- openai
+ dependencies:
+ mustache: 4.2.0
+
+ dependencies:
+ langfuse: 3.30.1
+ langfuse-core: 3.30.1
+
+ dependencies:
+ langfuse-core: 3.30.1
+
dependencies:
chevrotain: 11.0.3
@@ -21008,7 +21013,7 @@ snapshots:
vscode-languageserver-textdocument: 1.0.12
vscode-uri: 3.0.8
dependencies:
'@types/uuid': 10.0.0
commander: 10.0.1
@@ -21017,7 +21022,7 @@ snapshots:
semver: 7.6.3
uuid: 10.0.0
optionalDependencies:
- openai: 4.62.1([email protected])
+ openai: 4.72.0([email protected])
@@ -22011,7 +22016,7 @@ snapshots:
is-docker: 2.2.1
is-wsl: 2.2.0
dependencies:
'@types/node': 18.19.50
'@types/node-fetch': 2.6.11
diff --git a/web/package.json b/web/package.json
index 084ea33025..dc0a13310c 100644
--- a/web/package.json
+++ b/web/package.json
@@ -35,9 +35,9 @@
"@headlessui/tailwindcss": "0.2.1",
"@heroicons/react": "^2.1.5",
"@hookform/resolvers": "^3.3.4",
- "@langchain/anthropic": "^0.3.1",
- "@langchain/core": "^0.3.9",
- "@langchain/openai": "^0.3.0",
+ "@langchain/anthropic": "^0.3.8",
+ "@langchain/core": "^0.3.18",
+ "@langchain/openai": "^0.3.14",
"@langfuse/ee": "workspace:*",
"@langfuse/shared": "workspace:*",
"@marsidev/react-turnstile": "^0.5.4",
@@ -113,7 +113,7 @@
"ip-address": "^9.0.5",
"js-tiktoken": "^1.0.15",
"kysely": "^0.27.4",
- "langchain": "^0.3.2",
+ "langchain": "^0.3.6",
"lodash": "^4.17.21",
"lucide-react": "^0.447.0",
"next": "^14.2.15",
diff --git a/web/src/ee/features/evals/server/router.ts b/web/src/ee/features/evals/server/router.ts
index 22630c3ca6..9659e8f5d9 100644
--- a/web/src/ee/features/evals/server/router.ts
+++ b/web/src/ee/features/evals/server/router.ts
@@ -453,29 +453,31 @@ export const evalRouter = createTRPCRouter({
// Make a test structured output call to validate the LLM key
try {
- await fetchLLMCompletion({
- streaming: false,
- apiKey: decrypt(parsedKey.data.secretKey), // decrypt the secret key
- baseURL: parsedKey.data.baseURL ?? undefined,
- messages: [
- {
- role: ChatMessageRole.System,
- content: "You are an expert at evaluating LLM outputs.",
+ (
+ await fetchLLMCompletion({
+ streaming: false,
+ apiKey: decrypt(parsedKey.data.secretKey), // decrypt the secret key
+ baseURL: parsedKey.data.baseURL ?? undefined,
+ messages: [
+ {
+ role: ChatMessageRole.System,
+ content: "You are an expert at evaluating LLM outputs.",
+ },
+ { role: ChatMessageRole.User, content: input.prompt },
+ ],
+ modelParams: {
+ provider: input.provider,
+ model: input.model,
+ adapter: parsedKey.data.adapter,
+ ...input.modelParams,
},
- { role: ChatMessageRole.User, content: input.prompt },
- ],
- modelParams: {
- provider: input.provider,
- model: input.model,
- adapter: parsedKey.data.adapter,
- ...input.modelParams,
- },
- structuredOutputSchema: z.object({
- score: z.string(),
- reasoning: z.string(),
- }),
- config: parsedKey.data.config,
- });
+ structuredOutputSchema: z.object({
+ score: z.string(),
+ reasoning: z.string(),
+ }),
+ config: parsedKey.data.config,
+ })
+ ).completion;
} catch (err) {
logger.error(err);
diff --git a/web/src/ee/features/playground/server/chatCompletionHandler.ts b/web/src/ee/features/playground/server/chatCompletionHandler.ts
index f80f5a330f..7565846258 100644
--- a/web/src/ee/features/playground/server/chatCompletionHandler.ts
+++ b/web/src/ee/features/playground/server/chatCompletionHandler.ts
@@ -45,7 +45,7 @@ export default async function chatCompletionHandler(req: NextRequest) {
);
}
- const stream = await fetchLLMCompletion({
+ const { completion } = await fetchLLMCompletion({
messages,
modelParams,
streaming: true,
@@ -55,7 +55,7 @@ export default async function chatCompletionHandler(req: NextRequest) {
config: parsedKey.data.config,
});
- return new StreamingTextResponse(stream);
+ return new StreamingTextResponse(completion);
} catch (err) {
logger.error("Failed to handle chat completion", err);
diff --git a/web/src/env.mjs b/web/src/env.mjs
index 1b2615e630..c02cf08497 100644
--- a/web/src/env.mjs
+++ b/web/src/env.mjs
@@ -182,26 +182,6 @@ export const env = createEnv({
.nonnegative()
.default(3600),
- // Ingestion event upload to S3
- 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"),
- LANGFUSE_ASYNC_INGESTION_PROCESSING: z
- .enum(["true", "false"])
- .default("false"),
- LANGFUSE_ASYNC_CLICKHOUSE_INGESTION_PROCESSING: z
- .enum(["true", "false"])
- .default("false"),
LANGFUSE_ALLOWED_ORGANIZATION_CREATORS: z
.string()
.optional()
@@ -213,10 +193,6 @@ export const env = createEnv({
(creator) => emailSchema.safeParse(creator).success,
);
}, "LANGFUSE_ALLOWED_ORGANIZATION_CREATORS must be a comma separated list of valid email addresses"),
- LANGFUSE_INGESTION_QUEUE_DELAY_MS: z.coerce
- .number()
- .nonnegative()
- .default(15_000),
LANGFUSE_READ_FROM_POSTGRES_ONLY: z.enum(["true", "false"]).default("true"),
LANGFUSE_RETURN_FROM_CLICKHOUSE: z.enum(["true", "false"]).default("false"),
LANGFUSE_EXPERIMENT_EXCLUDED_PROJECT_IDS: z.string().optional(),
@@ -384,23 +360,6 @@ export const env = createEnv({
process.env.LANGFUSE_S3_MEDIA_UPLOAD_FORCE_PATH_STYLE,
LANGFUSE_S3_MEDIA_DOWNLOAD_URL_EXPIRY_SECONDS:
process.env.LANGFUSE_S3_MEDIA_DOWNLOAD_URL_EXPIRY_SECONDS,
- // S3 event upload
- LANGFUSE_S3_EVENT_UPLOAD_ENABLED:
- process.env.LANGFUSE_S3_EVENT_UPLOAD_ENABLED,
- LANGFUSE_S3_EVENT_UPLOAD_BUCKET:
- process.env.LANGFUSE_S3_EVENT_UPLOAD_BUCKET,
- LANGFUSE_S3_EVENT_UPLOAD_PREFIX:
- process.env.LANGFUSE_S3_EVENT_UPLOAD_PREFIX,
- LANGFUSE_S3_EVENT_UPLOAD_REGION:
- process.env.LANGFUSE_S3_EVENT_UPLOAD_REGION,
- LANGFUSE_S3_EVENT_UPLOAD_ENDPOINT:
- process.env.LANGFUSE_S3_EVENT_UPLOAD_ENDPOINT,
- LANGFUSE_S3_EVENT_UPLOAD_ACCESS_KEY_ID:
- process.env.LANGFUSE_S3_EVENT_UPLOAD_ACCESS_KEY_ID,
- LANGFUSE_S3_EVENT_UPLOAD_SECRET_ACCESS_KEY:
- process.env.LANGFUSE_S3_EVENT_UPLOAD_SECRET_ACCESS_KEY,
- LANGFUSE_S3_EVENT_UPLOAD_FORCE_PATH_STYLE:
- process.env.LANGFUSE_S3_EVENT_UPLOAD_FORCE_PATH_STYLE,
// Database exports
DB_EXPORT_PAGE_SIZE: process.env.DB_EXPORT_PAGE_SIZE,
// Worker
@@ -444,14 +403,8 @@ export const env = createEnv({
LANGFUSE_CACHE_API_KEY_ENABLED: process.env.LANGFUSE_CACHE_API_KEY_ENABLED,
LANGFUSE_CACHE_API_KEY_TTL_SECONDS:
process.env.LANGFUSE_CACHE_API_KEY_TTL_SECONDS,
- LANGFUSE_ASYNC_INGESTION_PROCESSING:
- process.env.LANGFUSE_ASYNC_INGESTION_PROCESSING,
- LANGFUSE_ASYNC_CLICKHOUSE_INGESTION_PROCESSING:
- process.env.LANGFUSE_ASYNC_CLICKHOUSE_INGESTION_PROCESSING,
LANGFUSE_ALLOWED_ORGANIZATION_CREATORS:
process.env.LANGFUSE_ALLOWED_ORGANIZATION_CREATORS,
- LANGFUSE_INGESTION_QUEUE_DELAY_MS:
- process.env.LANGFUSE_INGESTION_QUEUE_DELAY_MS,
LANGFUSE_READ_FROM_POSTGRES_ONLY:
process.env.LANGFUSE_READ_FROM_POSTGRES_ONLY,
LANGFUSE_READ_FROM_CLICKHOUSE_ONLY:
diff --git a/web/src/pages/api/public/events.ts b/web/src/pages/api/public/events.ts
index 926bae79df..5c22a5747d 100644
--- a/web/src/pages/api/public/events.ts
+++ b/web/src/pages/api/public/events.ts
@@ -4,8 +4,12 @@ import {
} 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 { processEventBatch } from "@/src/pages/api/public/ingestion";
-import { eventTypes, logger } from "@langfuse/shared/src/server";
+import {
+ eventTypes,
+ logger,
+ processEventBatch,
+} from "@langfuse/shared/src/server";
+import { tokenCount } from "@/src/features/ingest/usage";
import { v4 } from "uuid";
export default withMiddlewares({
@@ -26,7 +30,7 @@ export default withMiddlewares({
if (!event.body.id) {
event.body.id = v4();
}
- const result = await processEventBatch([event], auth);
+ const result = await processEventBatch([event], auth, tokenCount);
if (result.errors.length > 0) {
const error = result.errors[0];
res
diff --git a/web/src/pages/api/public/generations.ts b/web/src/pages/api/public/generations.ts
index dcf554d52f..6c2be8016d 100644
--- a/web/src/pages/api/public/generations.ts
+++ b/web/src/pages/api/public/generations.ts
@@ -6,8 +6,12 @@ import {
} 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 { processEventBatch } from "@/src/pages/api/public/ingestion";
-import { eventTypes, logger } from "@langfuse/shared/src/server";
+import { tokenCount } from "@/src/features/ingest/usage";
+import {
+ eventTypes,
+ logger,
+ processEventBatch,
+} from "@langfuse/shared/src/server";
import { v4 } from "uuid";
export default withMiddlewares({
@@ -32,7 +36,7 @@ export default withMiddlewares({
if (!event.body.id) {
event.body.id = v4();
}
- const result = await processEventBatch([event], auth);
+ const result = await processEventBatch([event], auth, tokenCount);
if (result.errors.length > 0) {
const error = result.errors[0];
res
@@ -66,7 +70,7 @@ export default withMiddlewares({
output: completion,
},
};
- const result = await processEventBatch([event], auth);
+ const result = await processEventBatch([event], auth, tokenCount);
if (result.errors.length > 0) {
const error = result.errors[0];
res
diff --git a/web/src/pages/api/public/ingestion.ts b/web/src/pages/api/public/ingestion.ts
index fb9d006426..3a5ca29ebc 100644
--- a/web/src/pages/api/public/ingestion.ts
+++ b/web/src/pages/api/public/ingestion.ts
@@ -1,42 +1,21 @@
import { cors, runMiddleware } from "@/src/features/public-api/server/cors";
import { type NextApiRequest, type NextApiResponse } from "next";
import { z } from "zod";
-import { LangfuseNotFoundError } from "@langfuse/shared";
import {
- eventTypes,
- ingestionEvent,
traceException,
redis,
logger,
- handleBatch,
- recordIncrement,
getCurrentSpan,
- IngestionQueue,
- LegacyIngestionQueue,
- S3StorageService,
- instrumentAsync,
- getProcessorForEvent,
- getClickhouseEntityType,
- type AuthHeaderValidVerificationResult,
- type LegacyIngestionEventType,
- type IngestionEventType,
} from "@langfuse/shared/src/server";
import { telemetry } from "@/src/features/telemetry";
import { jsonSchema } from "@langfuse/shared";
import { isPrismaException } from "@/src/utils/exceptions";
-import { env } from "@/src/env.mjs";
import {
- InvalidRequestError,
MethodNotAllowedError,
BaseError,
UnauthorizedError,
} from "@langfuse/shared";
-import {
- addTracesToTraceUpsertQueue,
- QueueJobs,
- instrumentSync,
-} from "@langfuse/shared/src/server";
-import { randomUUID } from "crypto";
+import { instrumentSync, processEventBatch } from "@langfuse/shared/src/server";
import { prisma } from "@langfuse/shared/src/db";
import { tokenCount } from "@/src/features/ingest/usage";
import { ApiAuthService } from "@/src/features/public-api/server/apiAuth";
@@ -50,22 +29,6 @@ export const config = {
},
};
-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 handler performs multiple actions to ingest data. It is compatible with the new async workflow, but also
* supports the old synchronous workflow which processes events in the web container.
@@ -152,7 +115,11 @@ export default async function handler(
await telemetry();
- const result = await processEventBatch(parsedSchema.data.batch, authCheck);
+ const result = await processEventBatch(
+ parsedSchema.data.batch,
+ authCheck,
+ tokenCount,
+ );
return res.status(207).json(result);
} catch (error: unknown) {
if (!(error instanceof UnauthorizedError)) {
@@ -189,347 +156,3 @@ 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_MS,
- },
- )
- : 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,
-): boolean => {
- try {
- getProcessorForEvent(event, tokenCount).auth(authScope.scope);
- return true;
- } catch (error) {
- return false;
- }
-};
-
-/**
- * Sorts a batch of ingestion events. Orders by: updating events last, sorted by timestamp asc.
- */
-const sortBatch = (batch: Array<z.infer<typeof ingestionEvent>>) => {
- const updateEvents: (typeof eventTypes)[keyof typeof eventTypes][] = [
- eventTypes.GENERATION_UPDATE,
- eventTypes.SPAN_UPDATE,
- eventTypes.OBSERVATION_UPDATE, // legacy event type
- ];
- const updates = batch
- .filter((event) => updateEvents.includes(event.type))
- .sort((a, b) => {
- return new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime();
- });
- const others = batch
- .filter((event) => !updateEvents.includes(event.type))
- .sort((a, b) => {
- return new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime();
- });
-
- // Return the array with non-update events first, followed by update events
- return [...others, ...updates];
-};
-
-export const aggregateBatchResult = (
- errors: Array<{ id: string; error: unknown }>,
- results: Array<{ id: string; result: unknown }>,
-) => {
- const returnedErrors: {
- id: string;
- status: number;
- message?: string;
- error?: string;
- }[] = [];
-
- const successes: {
- id: string;
- status: number;
- }[] = [];
-
- errors.forEach((error) => {
- if (error.error instanceof InvalidRequestError) {
- returnedErrors.push({
- id: error.id,
- status: 400,
- message: "Invalid request data",
- error: error.error.message,
- });
- } else if (error.error instanceof UnauthorizedError) {
- returnedErrors.push({
- id: error.id,
- status: 401,
- message: "Authentication error",
- error: error.error.message,
- });
- } else if (error.error instanceof LangfuseNotFoundError) {
- returnedErrors.push({
- id: error.id,
- status: 404,
- message: "Resource not found",
- error: error.error.message,
- });
- } else {
- returnedErrors.push({
- id: error.id,
- status: 500,
- error: "Internal Server Error",
- });
- }
- });
-
- if (returnedErrors.length > 0) {
- traceException(errors);
- logger.error("Error processing events", returnedErrors);
- }
-
- results.forEach((result) => {
- successes.push({
- id: result.id,
- status: 201,
- });
- });
-
- return { successes, errors: returnedErrors };
-};
diff --git a/web/src/pages/api/public/scores/index.ts b/web/src/pages/api/public/scores/index.ts
index 6693197a72..7bae9d3309 100644
--- a/web/src/pages/api/public/scores/index.ts
+++ b/web/src/pages/api/public/scores/index.ts
@@ -10,8 +10,12 @@ import {
PostScoresResponse,
} from "@langfuse/shared";
import { prisma, Prisma } from "@langfuse/shared/src/db";
-import { eventTypes, logger } from "@langfuse/shared/src/server";
-import { processEventBatch } from "@/src/pages/api/public/ingestion";
+import {
+ eventTypes,
+ logger,
+ processEventBatch,
+} from "@langfuse/shared/src/server";
+import { tokenCount } from "@/src/features/ingest/usage";
export default withMiddlewares({
POST: createAuthedAPIRoute({
@@ -28,7 +32,7 @@ export default withMiddlewares({
if (!event.body.id) {
event.body.id = v4();
}
- const result = await processEventBatch([event], auth);
+ const result = await processEventBatch([event], auth, tokenCount);
if (result.errors.length > 0) {
const error = result.errors[0];
res
diff --git a/web/src/pages/api/public/spans.ts b/web/src/pages/api/public/spans.ts
index 8473e39d46..18583bf9a4 100644
--- a/web/src/pages/api/public/spans.ts
+++ b/web/src/pages/api/public/spans.ts
@@ -6,8 +6,12 @@ import {
} 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 { processEventBatch } from "@/src/pages/api/public/ingestion";
-import { eventTypes, logger } from "@langfuse/shared/src/server";
+import { tokenCount } from "@/src/features/ingest/usage";
+import {
+ eventTypes,
+ logger,
+ processEventBatch,
+} from "@langfuse/shared/src/server";
import { v4 } from "uuid";
export default withMiddlewares({
@@ -28,7 +32,7 @@ export default withMiddlewares({
if (!event.body.id) {
event.body.id = v4();
}
- const result = await processEventBatch([event], auth);
+ const result = await processEventBatch([event], auth, tokenCount);
if (result.errors.length > 0) {
const error = result.errors[0];
res
@@ -58,7 +62,7 @@ export default withMiddlewares({
type: "SPAN",
},
};
- const result = await processEventBatch([event], auth);
+ const result = await processEventBatch([event], auth, tokenCount);
if (result.errors.length > 0) {
const error = result.errors[0];
res
diff --git a/web/src/pages/api/public/traces/index.ts b/web/src/pages/api/public/traces/index.ts
index 1d3a5b9181..deb3f8a999 100644
--- a/web/src/pages/api/public/traces/index.ts
+++ b/web/src/pages/api/public/traces/index.ts
@@ -8,7 +8,9 @@ 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 { processEventBatch } from "@/src/pages/api/public/ingestion";
+import { processEventBatch } from "@langfuse/shared/src/server";
+import { tokenCount } from "@/src/features/ingest/usage";
+
import { type Trace } from "@langfuse/shared";
import {
eventTypes,
@@ -37,7 +39,7 @@ export default withMiddlewares({
if (!event.body.id) {
event.body.id = v4();
}
- const result = await processEventBatch([event], auth);
+ const result = await processEventBatch([event], auth, tokenCount);
if (result.errors.length > 0) {
const error = result.errors[0];
res
diff --git a/worker/src/features/evaluation/evalService.ts b/worker/src/features/evaluation/evalService.ts
index c1b7a6606b..6f3e647648 100644
--- a/worker/src/features/evaluation/evalService.ts
+++ b/worker/src/features/evaluation/evalService.ts
@@ -17,6 +17,7 @@ import {
IngestionQueue,
EvalExecutionQueue,
} from "@langfuse/shared/src/server";
+import { JobConfigState } from "@langfuse/shared/src/db";
import {
ApiError,
availableTraceEvalVariables,
@@ -39,7 +40,7 @@ import { kyselyPrisma, prisma } from "@langfuse/shared/src/db";
import { fetchLLMCompletion, logger } from "@langfuse/shared/src/server";
import { backOff } from "exponential-backoff";
import { env } from "../../env";
-import { JobConfigState } from "../../../../packages/shared/dist/prisma/generated/types";
+import { tokenCount } from "../tokenisation/usage";
let s3StorageServiceClient: S3StorageService;
@@ -638,7 +639,7 @@ async function callLLM(
evalScoreSchema: z.ZodObject<{ score: z.ZodNumber; reasoning: z.ZodString }>,
): Promise<z.infer<typeof evalScoreSchema>> {
try {
- const completion = await fetchLLMCompletion({
+ const { completion, processTracedEvents } = await fetchLLMCompletion({
streaming: false,
apiKey: decrypt(llmApiKey.secretKey), // decrypt the secret key
baseURL: llmApiKey.baseURL || undefined,
@@ -657,7 +658,23 @@ async function callLLM(
},
structuredOutputSchema: evalScoreSchema,
config: llmApiKey.config,
+ traceParams: {
+ tags: ["langfuse:evaluation:llm-as-a-judge"],
+ traceName: `eval-llm-${jeId.slice(0, 5)}`,
+ traceId: jeId,
+ projectId: template.projectId,
+ authCheck: {
+ validKey: true,
+ scope: {
+ projectId: template.projectId,
+ accessLevel: "all",
+ } as any,
+ },
+ tokenCountDelegate: tokenCount,
+ },
});
+
+ await processTracedEvents();
return evalScoreSchema.parse(completion);
} catch (e) {
logger.error(