Skip to content

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

chore: add migration hints for legacy public ClickHouse APIs (#13475)

Max Deichmannd0642a6d7c52
diff --git a/web/src/__tests__/server/withMiddlewares.servertest.ts b/web/src/__tests__/server/withMiddlewares.servertest.ts
index 7e2d58df9d..aa89da0767 100644
--- a/web/src/__tests__/server/withMiddlewares.servertest.ts
+++ b/web/src/__tests__/server/withMiddlewares.servertest.ts
@@ -1,5 +1,8 @@
import type { NextApiRequest, NextApiResponse } from "next";
-import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";
+import {
+ LEGACY_PUBLIC_API_METRICS_CLICKHOUSE_RESOURCE_ERROR_MESSAGE,
+ withMiddlewares,
+} from "@/src/features/public-api/server/withMiddlewares";
import {
BaseError,
LangfuseNotFoundError,
@@ -211,6 +214,44 @@ describe("withMiddlewares error handling", () => {
);
expect(jsonData["error"]).toBe("Request timed out");
});
+
+ it("should handle ClickHouseResourceError with custom advice", async () => {
+ const originalError = new Error("Timeout exceeded");
+ const resourceError = new ClickHouseResourceError(
+ "TIMEOUT",
+ originalError,
+ );
+
+ const handler = withMiddlewares(
+ {
+ GET: async () => {
+ throw resourceError;
+ },
+ },
+ {
+ clickHouseResourceErrorMessage:
+ LEGACY_PUBLIC_API_METRICS_CLICKHOUSE_RESOURCE_ERROR_MESSAGE,
+ },
+ );
+
+ const { req, res } = createMocks<NextApiRequest, NextApiResponse>({
+ method: "GET",
+ headers: {
+ "x-langfuse-public-key": "test-key",
+ },
+ });
+
+ await handler(req, res);
+
+ expect(res._getStatusCode()).toBe(422);
+ const jsonData = JSON.parse(res._getData());
+ expect(jsonData["message"]).toBe(
+ LEGACY_PUBLIC_API_METRICS_CLICKHOUSE_RESOURCE_ERROR_MESSAGE,
+ );
+ expect(jsonData["message"]).toContain(
+ "https://langfuse.com/docs/metrics/features/metrics-api",
+ );
+ });
});
describe("Prisma exception handling", () => {
diff --git a/web/src/features/public-api/server/withMiddlewares.ts b/web/src/features/public-api/server/withMiddlewares.ts
index 964dcd7db0..0d41927004 100644
--- a/web/src/features/public-api/server/withMiddlewares.ts
+++ b/web/src/features/public-api/server/withMiddlewares.ts
@@ -37,13 +37,29 @@ const defaultHandler = () => {
throw new MethodNotAllowedError();
};
-const CH_ERROR_ADVICE_FULL = [
+const DEFAULT_CLICKHOUSE_RESOURCE_ERROR_MESSAGE = [
ClickHouseResourceError.ERROR_ADVICE_MESSAGE,
"See https://langfuse.com/docs/api-and-data-platform/features/public-api for more details.",
].join("\n");
+export const LEGACY_PUBLIC_API_OBSERVATIONS_CLICKHOUSE_RESOURCE_ERROR_MESSAGE =
+ [
+ ClickHouseResourceError.ERROR_ADVICE_MESSAGE,
+ "This legacy endpoint can be slow. Please migrate to the high-performance Observations API v2 at /api/public/v2/observations.",
+ "This applies to Langfuse Cloud only until v4 is released in OSS.",
+ "Docs: https://langfuse.com/docs/api-and-data-platform/features/observations-api",
+ ].join("\n");
+
+export const LEGACY_PUBLIC_API_METRICS_CLICKHOUSE_RESOURCE_ERROR_MESSAGE = [
+ ClickHouseResourceError.ERROR_ADVICE_MESSAGE,
+ "This legacy endpoint can be slow. Please migrate to the high-performance Metrics API v2 at /api/public/v2/metrics.",
+ "This applies to Langfuse Cloud only until v4 is released in OSS.",
+ "Docs: https://langfuse.com/docs/metrics/features/metrics-api",
+].join("\n");
+
type MiddlewareOptions = {
errorContract?: PublicApiErrorContract;
+ clickHouseResourceErrorMessage?: string;
};
export function withMiddlewares(
@@ -124,15 +140,18 @@ export function withMiddlewares(
// Handle ClickHouse resource errors
if (error instanceof ClickHouseResourceError) {
const resourceError = error as ClickHouseResourceError;
+ const errorMessage =
+ options?.clickHouseResourceErrorMessage ??
+ DEFAULT_CLICKHOUSE_RESOURCE_ERROR_MESSAGE;
logger.warn("ClickHouse resource limit exceeded", {
errorType: resourceError.errorType,
message: resourceError.message,
- suggestion: CH_ERROR_ADVICE_FULL,
+ suggestion: errorMessage,
});
return res.status(422).json({
- message: CH_ERROR_ADVICE_FULL,
+ message: errorMessage,
error: "Request timed out",
});
}
diff --git a/web/src/pages/api/public/metrics/index.ts b/web/src/pages/api/public/metrics/index.ts
index 0ea455337d..1ecf63dd91 100644
--- a/web/src/pages/api/public/metrics/index.ts
+++ b/web/src/pages/api/public/metrics/index.ts
@@ -1,4 +1,7 @@
-import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";
+import {
+ LEGACY_PUBLIC_API_METRICS_CLICKHOUSE_RESOURCE_ERROR_MESSAGE,
+ withMiddlewares,
+} from "@/src/features/public-api/server/withMiddlewares";
import { createAuthedProjectAPIRoute } from "@/src/features/public-api/server/createAuthedProjectAPIRoute";
import { logger } from "@langfuse/shared/src/server";
import {
@@ -7,40 +10,46 @@ import {
} from "@/src/features/public-api/types/metrics";
import { executeQuery } from "@/src/features/query/server/queryExecutor";
-export default withMiddlewares({
- GET: createAuthedProjectAPIRoute({
- name: "Get Metrics",
- rateLimitResource: "public-api-metrics",
- querySchema: GetMetricsV1Query,
- responseSchema: GetMetricsV1Response,
- fn: async ({ query, auth }) => {
- try {
- // Extract the parsed query object
- const queryParams = query.query;
+export default withMiddlewares(
+ {
+ GET: createAuthedProjectAPIRoute({
+ name: "Get Metrics",
+ rateLimitResource: "public-api-metrics",
+ querySchema: GetMetricsV1Query,
+ responseSchema: GetMetricsV1Response,
+ fn: async ({ query, auth }) => {
+ try {
+ // Extract the parsed query object
+ const queryParams = query.query;
- // Log the received query for debugging
- logger.debug("Received metrics query", {
- query: queryParams,
- projectId: auth.scope.projectId,
- });
+ // Log the received query for debugging
+ logger.debug("Received metrics query", {
+ query: queryParams,
+ projectId: auth.scope.projectId,
+ });
- // Execute the query using QueryBuilder
- const result = await executeQuery(auth.scope.projectId, queryParams);
+ // Execute the query using QueryBuilder
+ const result = await executeQuery(auth.scope.projectId, queryParams);
- // Format and return the result
- return {
- data: result,
- // meta: {
- // page: queryParams.page,
- // limit: queryParams.limit,
- // totalItems: result.length,
- // totalPages: Math.ceil(result.length / queryParams.limit),
- // },
- };
- } catch (error) {
- logger.error("Error in metrics API", { error, query });
- throw error;
- }
- },
- }),
-});
+ // Format and return the result
+ return {
+ data: result,
+ // meta: {
+ // page: queryParams.page,
+ // limit: queryParams.limit,
+ // totalItems: result.length,
+ // totalPages: Math.ceil(result.length / queryParams.limit),
+ // },
+ };
+ } catch (error) {
+ logger.error("Error in metrics API", { error, query });
+ throw error;
+ }
+ },
+ }),
+ },
+ {
+ clickHouseResourceErrorMessage:
+ LEGACY_PUBLIC_API_METRICS_CLICKHOUSE_RESOURCE_ERROR_MESSAGE,
+ },
+);
diff --git a/web/src/pages/api/public/observations/[observationId].ts b/web/src/pages/api/public/observations/[observationId].ts
index 660821c6c9..977f42e754 100644
--- a/web/src/pages/api/public/observations/[observationId].ts
+++ b/web/src/pages/api/public/observations/[observationId].ts
@@ -4,7 +4,10 @@ import {
GetObservationV1Response,
transformDbToApiObservation,
} from "@/src/features/public-api/types/observations";
-import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";
+import {
+ LEGACY_PUBLIC_API_OBSERVATIONS_CLICKHOUSE_RESOURCE_ERROR_MESSAGE,
+ withMiddlewares,
+} from "@/src/features/public-api/server/withMiddlewares";
import { createAuthedProjectAPIRoute } from "@/src/features/public-api/server/createAuthedProjectAPIRoute";
import { LangfuseNotFoundError } from "@langfuse/shared";
import {
@@ -14,79 +17,85 @@ import {
} from "@langfuse/shared/src/server";
import { env } from "@/src/env.mjs";
-export default withMiddlewares({
- GET: createAuthedProjectAPIRoute({
- name: "Get Observation",
- querySchema: GetObservationV1Query,
- responseSchema: GetObservationV1Response,
- fn: async ({ query, auth }) => {
- // Use events table if query parameter is explicitly set, otherwise use environment variable
- const useEventsTable =
- query.useEventsTable !== undefined && query.useEventsTable !== null
- ? query.useEventsTable === true
- : env.LANGFUSE_ENABLE_EVENTS_TABLE_OBSERVATIONS;
+export default withMiddlewares(
+ {
+ GET: createAuthedProjectAPIRoute({
+ name: "Get Observation",
+ querySchema: GetObservationV1Query,
+ responseSchema: GetObservationV1Response,
+ fn: async ({ query, auth }) => {
+ // Use events table if query parameter is explicitly set, otherwise use environment variable
+ const useEventsTable =
+ query.useEventsTable !== undefined && query.useEventsTable !== null
+ ? query.useEventsTable === true
+ : env.LANGFUSE_ENABLE_EVENTS_TABLE_OBSERVATIONS;
- const clickhouseObservation = useEventsTable
- ? await getObservationByIdFromEventsTable({
- id: query.observationId,
- projectId: auth.scope.projectId,
- fetchWithInputOutput: true,
- })
- : await getObservationById({
- id: query.observationId,
- projectId: auth.scope.projectId,
- fetchWithInputOutput: true,
- preferredClickhouseService: "ReadOnly",
- });
+ const clickhouseObservation = useEventsTable
+ ? await getObservationByIdFromEventsTable({
+ id: query.observationId,
+ projectId: auth.scope.projectId,
+ fetchWithInputOutput: true,
+ })
+ : await getObservationById({
+ id: query.observationId,
+ projectId: auth.scope.projectId,
+ fetchWithInputOutput: true,
+ preferredClickhouseService: "ReadOnly",
+ });
- if (!clickhouseObservation) {
- throw new LangfuseNotFoundError(
- "Observation not found within authorized project",
- );
- }
+ if (!clickhouseObservation) {
+ throw new LangfuseNotFoundError(
+ "Observation not found within authorized project",
+ );
+ }
- const model = clickhouseObservation.internalModelId
- ? await prisma.model.findFirst({
- where: {
- AND: [
- {
- id: clickhouseObservation.internalModelId,
- },
- {
- OR: [
- {
- projectId: auth.scope.projectId,
- },
- {
- projectId: null,
- },
- ],
+ const model = clickhouseObservation.internalModelId
+ ? await prisma.model.findFirst({
+ where: {
+ AND: [
+ {
+ id: clickhouseObservation.internalModelId,
+ },
+ {
+ OR: [
+ {
+ projectId: auth.scope.projectId,
+ },
+ {
+ projectId: null,
+ },
+ ],
+ },
+ ],
+ },
+ include: {
+ Price: true,
+ },
+ orderBy: {
+ projectId: {
+ sort: "desc",
+ nulls: "last",
},
- ],
- },
- include: {
- Price: true,
- },
- orderBy: {
- projectId: {
- sort: "desc",
- nulls: "last",
},
- },
- })
- : undefined;
+ })
+ : undefined;
- const observation = {
- ...clickhouseObservation,
- ...enrichObservationWithModelData(model),
- };
+ const observation = {
+ ...clickhouseObservation,
+ ...enrichObservationWithModelData(model),
+ };
- if (!observation) {
- throw new LangfuseNotFoundError(
- "Observation not found within authorized project",
- );
- }
- return transformDbToApiObservation(observation);
- },
- }),
-});
+ if (!observation) {
+ throw new LangfuseNotFoundError(
+ "Observation not found within authorized project",
+ );
+ }
+ return transformDbToApiObservation(observation);
+ },
+ }),
+ },
+ {
+ clickHouseResourceErrorMessage:
+ LEGACY_PUBLIC_API_OBSERVATIONS_CLICKHOUSE_RESOURCE_ERROR_MESSAGE,
+ },
+);
diff --git a/web/src/pages/api/public/observations/index.ts b/web/src/pages/api/public/observations/index.ts
index a3fa87e2b5..a5e6b0b309 100644
--- a/web/src/pages/api/public/observations/index.ts
+++ b/web/src/pages/api/public/observations/index.ts
@@ -5,7 +5,10 @@ import {
} from "@langfuse/shared/src/server";
import { env } from "@/src/env.mjs";
-import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";
+import {
+ LEGACY_PUBLIC_API_OBSERVATIONS_CLICKHOUSE_RESOURCE_ERROR_MESSAGE,
+ withMiddlewares,
+} from "@/src/features/public-api/server/withMiddlewares";
import { createAuthedProjectAPIRoute } from "@/src/features/public-api/server/createAuthedProjectAPIRoute";
import {
@@ -18,107 +21,116 @@ import {
getObservationsCountForPublicApi,
} from "@/src/features/public-api/server/observations";
-export default withMiddlewares({
- GET: createAuthedProjectAPIRoute({
- name: "Get Observations",
- querySchema: GetObservationsV1Query,
- responseSchema: GetObservationsV1Response,
- fn: async ({ query, auth }) => {
- const filterProps = {
- projectId: auth.scope.projectId,
- page: query.page,
- limit: query.limit,
- traceId: query.traceId ?? undefined,
- userId: query.userId ?? undefined,
- level: query.level ?? undefined,
- name: query.name ?? undefined,
- type: query.type ?? undefined,
- environment: query.environment ?? undefined,
- parentObservationId: query.parentObservationId ?? undefined,
- fromStartTime: query.fromStartTime ?? undefined,
- toStartTime: query.toStartTime ?? undefined,
- version: query.version ?? undefined,
- advancedFilters: query.filter,
- };
+export default withMiddlewares(
+ {
+ GET: createAuthedProjectAPIRoute({
+ name: "Get Observations",
+ querySchema: GetObservationsV1Query,
+ responseSchema: GetObservationsV1Response,
+ fn: async ({ query, auth }) => {
+ const filterProps = {
+ projectId: auth.scope.projectId,
+ page: query.page,
+ limit: query.limit,
+ traceId: query.traceId ?? undefined,
+ userId: query.userId ?? undefined,
+ level: query.level ?? undefined,
+ name: query.name ?? undefined,
+ type: query.type ?? undefined,
+ environment: query.environment ?? undefined,
+ parentObservationId: query.parentObservationId ?? undefined,
+ fromStartTime: query.fromStartTime ?? undefined,
+ toStartTime: query.toStartTime ?? undefined,
+ version: query.version ?? undefined,
+ advancedFilters: query.filter,
+ };
+
+ // Use events table if query parameter is explicitly set, otherwise use environment variable
+ const useEventsTable =
+ query.useEventsTable !== undefined && query.useEventsTable !== null
+ ? query.useEventsTable === true
+ : env.LANGFUSE_ENABLE_EVENTS_TABLE_OBSERVATIONS;
- // Use events table if query parameter is explicitly set, otherwise use environment variable
- const useEventsTable =
- query.useEventsTable !== undefined && query.useEventsTable !== null
- ? query.useEventsTable === true
- : env.LANGFUSE_ENABLE_EVENTS_TABLE_OBSERVATIONS;
+ if (useEventsTable) {
+ const [items, count] = await Promise.all([
+ getObservationsFromEventsTableForPublicApi(filterProps),
+ getObservationsCountFromEventsTableForPublicApi(filterProps),
+ ]);
- if (useEventsTable) {
+ return {
+ data: items.map(transformDbToApiObservation),
+ meta: {
+ page: query.page,
+ limit: query.limit,
+ totalItems: count,
+ totalPages: Math.ceil(count / query.limit),
+ },
+ };
+ }
+
+ // Legacy code path using observations table
const [items, count] = await Promise.all([
- getObservationsFromEventsTableForPublicApi(filterProps),
- getObservationsCountFromEventsTableForPublicApi(filterProps),
+ generateObservationsForPublicApi(filterProps),
+ getObservationsCountForPublicApi(filterProps),
]);
+ const uniqueModels: string[] = Array.from(
+ new Set(
+ items
+ .map((r) => r.internalModelId)
+ .filter((r): r is string => Boolean(r)),
+ ),
+ );
+
+ const models =
+ uniqueModels.length > 0
+ ? await prisma.model.findMany({
+ where: {
+ id: {
+ in: uniqueModels,
+ },
+ OR: [
+ { projectId: auth.scope.projectId },
+ { projectId: null },
+ ],
+ },
+ include: {
+ Price: true,
+ },
+ })
+ : [];
+ const finalCount = count ? count : 0;
return {
- data: items.map(transformDbToApiObservation),
+ data: items
+ .map((i) => {
+ const model = models.find((m) => m.id === i.internalModelId);
+ return {
+ ...i,
+ modelId: model?.id ?? null,
+ inputPrice:
+ model?.Price?.find((m) => m.usageType === "input")?.price ??
+ null,
+ outputPrice:
+ model?.Price?.find((m) => m.usageType === "output")?.price ??
+ null,
+ totalPrice:
+ model?.Price?.find((m) => m.usageType === "total")?.price ??
+ null,
+ };
+ })
+ .map(transformDbToApiObservation),
meta: {
page: query.page,
limit: query.limit,
- totalItems: count,
- totalPages: Math.ceil(count / query.limit),
+ totalItems: finalCount,
+ totalPages: Math.ceil(finalCount / query.limit),
},
};
- }
-
- // Legacy code path using observations table
- const [items, count] = await Promise.all([
- generateObservationsForPublicApi(filterProps),
- getObservationsCountForPublicApi(filterProps),
- ]);
- const uniqueModels: string[] = Array.from(
- new Set(
- items
- .map((r) => r.internalModelId)
- .filter((r): r is string => Boolean(r)),
- ),
- );
-
- const models =
- uniqueModels.length > 0
- ? await prisma.model.findMany({
- where: {
- id: {
- in: uniqueModels,
- },
- OR: [{ projectId: auth.scope.projectId }, { projectId: null }],
- },
- include: {
- Price: true,
- },
- })
- : [];
- const finalCount = count ? count : 0;
-
- return {
- data: items
- .map((i) => {
- const model = models.find((m) => m.id === i.internalModelId);
- return {
- ...i,
- modelId: model?.id ?? null,
- inputPrice:
- model?.Price?.find((m) => m.usageType === "input")?.price ??
- null,
- outputPrice:
- model?.Price?.find((m) => m.usageType === "output")?.price ??
- null,
- totalPrice:
- model?.Price?.find((m) => m.usageType === "total")?.price ??
- null,
- };
- })
- .map(transformDbToApiObservation),
- meta: {
- page: query.page,
- limit: query.limit,
- totalItems: finalCount,
- totalPages: Math.ceil(finalCount / query.limit),
- },
- };
- },
- }),
-});
+ },
+ }),
+ },
+ {
+ clickHouseResourceErrorMessage:
+ LEGACY_PUBLIC_API_OBSERVATIONS_CLICKHOUSE_RESOURCE_ERROR_MESSAGE,
+ },
+);
diff --git a/web/src/pages/api/public/traces/[traceId].ts b/web/src/pages/api/public/traces/[traceId].ts
index eae2460176..1b43b4e9fd 100644
--- a/web/src/pages/api/public/traces/[traceId].ts
+++ b/web/src/pages/api/public/traces/[traceId].ts
@@ -1,5 +1,8 @@
import { createAuthedProjectAPIRoute } from "@/src/features/public-api/server/createAuthedProjectAPIRoute";
-import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";
+import {
+ LEGACY_PUBLIC_API_OBSERVATIONS_CLICKHOUSE_RESOURCE_ERROR_MESSAGE,
+ withMiddlewares,
+} from "@/src/features/public-api/server/withMiddlewares";
import { transformDbToApiObservation } from "@/src/features/public-api/types/observations";
import {
GetTraceV1Query,
@@ -25,180 +28,191 @@ import {
import Decimal from "decimal.js";
import { auditLog } from "@/src/features/audit-logs/auditLog";
-export default withMiddlewares({
- GET: createAuthedProjectAPIRoute({
- name: "Get Single Trace",
- querySchema: GetTraceV1Query,
- responseSchema: GetTraceV1Response,
- fn: async ({ query, auth }) => {
- const { traceId } = query;
+export default withMiddlewares(
+ {
+ GET: createAuthedProjectAPIRoute({
+ name: "Get Single Trace",
+ querySchema: GetTraceV1Query,
+ responseSchema: GetTraceV1Response,
+ fn: async ({ query, auth }) => {
+ const { traceId } = query;
- let effectiveFields: readonly TraceFieldGroup[] =
- query.fields ?? TRACE_FIELD_GROUPS;
- if (!query.fields && env.LANGFUSE_API_TRACEBYID_DEFAULT_FIELDS) {
- const parsed = env.LANGFUSE_API_TRACEBYID_DEFAULT_FIELDS.split(",")
- .map((f) => f.trim())
- .filter((f): f is TraceFieldGroup =>
- TRACE_FIELD_GROUPS.includes(f as TraceFieldGroup),
- );
- if (parsed.length > 0) {
- effectiveFields = parsed;
+ let effectiveFields: readonly TraceFieldGroup[] =
+ query.fields ?? TRACE_FIELD_GROUPS;
+ if (!query.fields && env.LANGFUSE_API_TRACEBYID_DEFAULT_FIELDS) {
+ const parsed = env.LANGFUSE_API_TRACEBYID_DEFAULT_FIELDS.split(",")
+ .map((f) => f.trim())
+ .filter((f): f is TraceFieldGroup =>
+ TRACE_FIELD_GROUPS.includes(f as TraceFieldGroup),
+ );
+ if (parsed.length > 0) {
+ effectiveFields = parsed;
+ }
}
- }
- const requestedFields = effectiveFields;
- const includeIO = requestedFields.includes("io");
- const includeObservations = requestedFields.includes("observations");
- const includeScores = requestedFields.includes("scores");
- const includeMetrics = requestedFields.includes("metrics");
+ const requestedFields = effectiveFields;
+ const includeIO = requestedFields.includes("io");
+ const includeObservations = requestedFields.includes("observations");
+ const includeScores = requestedFields.includes("scores");
+ const includeMetrics = requestedFields.includes("metrics");
- const trace = await getTraceById({
- traceId,
- projectId: auth.scope.projectId,
- clickhouseFeatureTag: "tracing-public-api",
- preferredClickhouseService: "ReadOnly",
- excludeInputOutput: !includeIO,
- excludeMetadata: !includeIO,
- });
+ const trace = await getTraceById({
+ traceId,
+ projectId: auth.scope.projectId,
+ clickhouseFeatureTag: "tracing-public-api",
+ preferredClickhouseService: "ReadOnly",
+ excludeInputOutput: !includeIO,
+ excludeMetadata: !includeIO,
+ });
- if (!trace) {
- throw new LangfuseNotFoundError(
- `Trace ${traceId} not found within authorized project`,
- );
- }
+ if (!trace) {
+ throw new LangfuseNotFoundError(
+ `Trace ${traceId} not found within authorized project`,
+ );
+ }
- const [observations, scores] = await Promise.all([
- includeObservations || includeMetrics
- ? getObservationsForTrace({
- traceId,
- projectId: auth.scope.projectId,
- timestamp: trace?.timestamp,
- includeIO: includeObservations,
- preferredClickhouseService: "ReadOnly",
- })
- : Promise.resolve([]),
- includeScores
- ? getScoresForTraces({
- projectId: auth.scope.projectId,
- traceIds: [traceId],
- timestamp: trace?.timestamp,
- preferredClickhouseService: "ReadOnly",
- })
- : Promise.resolve([]),
- ]);
+ const [observations, scores] = await Promise.all([
+ includeObservations || includeMetrics
+ ? getObservationsForTrace({
+ traceId,
+ projectId: auth.scope.projectId,
+ timestamp: trace?.timestamp,
+ includeIO: includeObservations,
+ preferredClickhouseService: "ReadOnly",
+ })
+ : Promise.resolve([]),
+ includeScores
+ ? getScoresForTraces({
+ projectId: auth.scope.projectId,
+ traceIds: [traceId],
+ timestamp: trace?.timestamp,
+ preferredClickhouseService: "ReadOnly",
+ })
+ : Promise.resolve([]),
+ ]);
- const uniqueModels: string[] = Array.from(
- new Set(
- observations
- .map((r) => r.internalModelId)
- .filter((r): r is string => Boolean(r)),
- ),
- );
+ const uniqueModels: string[] = Array.from(
+ new Set(
+ observations
+ .map((r) => r.internalModelId)
+ .filter((r): r is string => Boolean(r)),
+ ),
+ );
- const models =
- uniqueModels.length > 0
- ? await prisma.model.findMany({
- where: {
- id: {
- in: uniqueModels,
+ const models =
+ uniqueModels.length > 0
+ ? await prisma.model.findMany({
+ where: {
+ id: {
+ in: uniqueModels,
+ },
+ OR: [
+ { projectId: auth.scope.projectId },
+ { projectId: null },
+ ],
},
- OR: [{ projectId: auth.scope.projectId }, { projectId: null }],
- },
- include: {
- Price: true,
- },
- })
- : [];
+ include: {
+ Price: true,
+ },
+ })
+ : [];
- const observationsView = observations.map((o) => {
- const model = models.find((m) => m.id === o.internalModelId);
- const inputPrice =
- model?.Price.find((p) => p.usageType === "input")?.price ??
- new Decimal(0);
- const outputPrice =
- model?.Price.find((p) => p.usageType === "output")?.price ??
- new Decimal(0);
- const totalPrice =
- model?.Price.find((p) => p.usageType === "total")?.price ??
- new Decimal(0);
- return {
- ...o,
- inputPrice,
- outputPrice,
- totalPrice,
- };
- });
+ const observationsView = observations.map((o) => {
+ const model = models.find((m) => m.id === o.internalModelId);
+ const inputPrice =
+ model?.Price.find((p) => p.usageType === "input")?.price ??
+ new Decimal(0);
+ const outputPrice =
+ model?.Price.find((p) => p.usageType === "output")?.price ??
+ new Decimal(0);
+ const totalPrice =
+ model?.Price.find((p) => p.usageType === "total")?.price ??
+ new Decimal(0);
+ return {
+ ...o,
+ inputPrice,
+ outputPrice,
+ totalPrice,
+ };
+ });
- const outObservations = observationsView.map(transformDbToApiObservation);
- // As these are traces scores, we expect all scores to have a traceId set
- // For type consistency, we validate the scores against the v1 schema which requires a traceId
- const validatedScores = filterAndValidateDbLegacyTraceScoreList({
- scores,
- onParseError: traceException,
- });
+ const outObservations = observationsView.map(
+ transformDbToApiObservation,
+ );
+ // As these are traces scores, we expect all scores to have a traceId set
+ // For type consistency, we validate the scores against the v1 schema which requires a traceId
+ const validatedScores = filterAndValidateDbLegacyTraceScoreList({
+ scores,
+ onParseError: traceException,
+ });
- const obsStartTimes = observations
- .map((o) => o.startTime)
- .sort((a, b) => a.getTime() - b.getTime());
- const obsEndTimes = observations
- .map((o) => o.endTime)
- .filter((t) => t)
- .sort((a, b) => (a as Date).getTime() - (b as Date).getTime());
+ const obsStartTimes = observations
+ .map((o) => o.startTime)
+ .sort((a, b) => a.getTime() - b.getTime());
+ const obsEndTimes = observations
+ .map((o) => o.endTime)
+ .filter((t) => t)
+ .sort((a, b) => (a as Date).getTime() - (b as Date).getTime());
- const latencyMs =
- obsStartTimes.length > 0
- ? obsEndTimes.length > 0
- ? (obsEndTimes[obsEndTimes.length - 1] as Date).getTime() -
- obsStartTimes[0]!.getTime()
- : obsStartTimes.length > 1
- ? obsStartTimes[obsStartTimes.length - 1]!.getTime() -
+ const latencyMs =
+ obsStartTimes.length > 0
+ ? obsEndTimes.length > 0
+ ? (obsEndTimes[obsEndTimes.length - 1] as Date).getTime() -
obsStartTimes[0]!.getTime()
- : undefined
- : undefined;
- return {
- ...trace,
- externalId: null,
- metadata: includeIO ? trace.metadata : {},
- scores: includeScores ? validatedScores : [],
- latency: includeMetrics
- ? latencyMs !== undefined
- ? latencyMs / 1000
- : 0
- : -1,
- observations: includeObservations ? outObservations : [],
- htmlPath: `/project/${auth.scope.projectId}/traces/${traceId}`,
- totalCost: includeMetrics
- ? outObservations
- .reduce(
- (acc, obs) =>
- acc.add(obs.calculatedTotalCost ?? new Decimal(0)),
- new Decimal(0),
- )
- .toNumber()
- : -1,
- };
- },
- }),
+ : obsStartTimes.length > 1
+ ? obsStartTimes[obsStartTimes.length - 1]!.getTime() -
+ obsStartTimes[0]!.getTime()
+ : undefined
+ : undefined;
+ return {
+ ...trace,
+ externalId: null,
+ metadata: includeIO ? trace.metadata : {},
+ scores: includeScores ? validatedScores : [],
+ latency: includeMetrics
+ ? latencyMs !== undefined
+ ? latencyMs / 1000
+ : 0
+ : -1,
+ observations: includeObservations ? outObservations : [],
+ htmlPath: `/project/${auth.scope.projectId}/traces/${traceId}`,
+ totalCost: includeMetrics
+ ? outObservations
+ .reduce(
+ (acc, obs) =>
+ acc.add(obs.calculatedTotalCost ?? new Decimal(0)),
+ new Decimal(0),
+ )
+ .toNumber()
+ : -1,
+ };
+ },
+ }),
- DELETE: createAuthedProjectAPIRoute({
- name: "Delete Single Trace",
- querySchema: DeleteTraceV1Query,
- responseSchema: DeleteTraceV1Response,
- rateLimitResource: "trace-delete",
- fn: async ({ query, auth }) => {
- const { traceId } = query;
+ DELETE: createAuthedProjectAPIRoute({
+ name: "Delete Single Trace",
+ querySchema: DeleteTraceV1Query,
+ responseSchema: DeleteTraceV1Response,
+ rateLimitResource: "trace-delete",
+ fn: async ({ query, auth }) => {
+ const { traceId } = query;
- await auditLog({
- resourceType: "trace",
- resourceId: traceId,
- action: "delete",
- projectId: auth.scope.projectId,
- apiKeyId: auth.scope.apiKeyId,
- orgId: auth.scope.orgId,
- });
+ await auditLog({
+ resourceType: "trace",
+ resourceId: traceId,
+ action: "delete",
+ projectId: auth.scope.projectId,
+ apiKeyId: auth.scope.apiKeyId,
+ orgId: auth.scope.orgId,
+ });
- await traceDeletionProcessor(auth.scope.projectId, [traceId]);
+ await traceDeletionProcessor(auth.scope.projectId, [traceId]);
- return { message: "Trace deleted successfully" };
- },
- }),
-});
+ return { message: "Trace deleted successfully" };
+ },
+ }),
+ },
+ {
+ clickHouseResourceErrorMessage:
+ LEGACY_PUBLIC_API_OBSERVATIONS_CLICKHOUSE_RESOURCE_ERROR_MESSAGE,
+ },
+);
diff --git a/web/src/pages/api/public/traces/index.ts b/web/src/pages/api/public/traces/index.ts
index 142149ca06..827e99baa2 100644
--- a/web/src/pages/api/public/traces/index.ts
+++ b/web/src/pages/api/public/traces/index.ts
@@ -9,7 +9,10 @@ import {
type TraceFieldGroup,
} from "@/src/features/public-api/types/traces";
import { InvalidRequestError } from "@langfuse/shared";
-import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";
+import {
+ LEGACY_PUBLIC_API_OBSERVATIONS_CLICKHOUSE_RESOURCE_ERROR_MESSAGE,
+ withMiddlewares,
+} from "@/src/features/public-api/server/withMiddlewares";
import { createAuthedProjectAPIRoute } from "@/src/features/public-api/server/createAuthedProjectAPIRoute";
import { processEventBatch } from "@langfuse/shared/src/server";
import {
@@ -28,116 +31,145 @@ import {
} from "@/src/features/public-api/server/traces";
import { env } from "@/src/env.mjs";
-export default withMiddlewares({
- POST: createAuthedProjectAPIRoute({
- name: "Create Trace (Legacy)",
- bodySchema: PostTracesV1Body,
- responseSchema: PostTracesV1Response, // Adjust this if you have a specific response schema
- rateLimitResource: "legacy-ingestion",
- fn: async ({ body, auth, res }) => {
- await telemetry();
- const event = {
- id: v4(),
- type: eventTypes.TRACE_CREATE,
- timestamp: new Date().toISOString(),
- body: body,
- };
- 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 };
- },
- }),
+export default withMiddlewares(
+ {
+ POST: createAuthedProjectAPIRoute({
+ name: "Create Trace (Legacy)",
+ bodySchema: PostTracesV1Body,
+ responseSchema: PostTracesV1Response, // Adjust this if you have a specific response schema
+ rateLimitResource: "legacy-ingestion",
+ fn: async ({ body, auth, res }) => {
+ await telemetry();
+ const event = {
+ id: v4(),
+ type: eventTypes.TRACE_CREATE,
+ timestamp: new Date().toISOString(),
+ body: body,
+ };
+ 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 };
+ },
+ }),
- GET: createAuthedProjectAPIRoute({
- name: "Get Traces",
- querySchema: GetTracesV1Query,
- responseSchema: GetTracesV1Response,
- fn: async ({ query, auth }) => {
- // Api-performance controls.
- // 1. Reject if no date range and rejection is enabled
- if (
- env.LANGFUSE_API_TRACES_REJECT_NO_DATE_RANGE === "true" &&
- !query.fromTimestamp
- ) {
- throw new InvalidRequestError(
- "fromTimestamp is required. Set the fromTimestamp query parameter to filter traces by date.",
- );
- }
+ GET: createAuthedProjectAPIRoute({
+ name: "Get Traces",
+ querySchema: GetTracesV1Query,
+ responseSchema: GetTracesV1Response,
+ fn: async ({ query, auth }) => {
+ // Api-performance controls.
+ // 1. Reject if no date range and rejection is enabled
+ if (
+ env.LANGFUSE_API_TRACES_REJECT_NO_DATE_RANGE === "true" &&
+ !query.fromTimestamp
+ ) {
+ throw new InvalidRequestError(
+ "fromTimestamp is required. Set the fromTimestamp query parameter to filter traces by date.",
+ );
+ }
- // 2. Apply default date range if configured and no fromTimestamp provided
- const defaultDateRangeDays =
- env.LANGFUSE_API_TRACES_DEFAULT_DATE_RANGE_DAYS;
- let effectiveFromTimestamp = query.fromTimestamp ?? undefined;
- if (!query.fromTimestamp && defaultDateRangeDays) {
- const referenceDateMs = query.toTimestamp
- ? new Date(query.toTimestamp).getTime()
- : Date.now();
- effectiveFromTimestamp = new Date(
- referenceDateMs - defaultDateRangeDays * 24 * 60 * 60 * 1000,
- ).toISOString();
- }
+ // 2. Apply default date range if configured and no fromTimestamp provided
+ const defaultDateRangeDays =
+ env.LANGFUSE_API_TRACES_DEFAULT_DATE_RANGE_DAYS;
+ let effectiveFromTimestamp = query.fromTimestamp ?? undefined;
+ if (!query.fromTimestamp && defaultDateRangeDays) {
+ const referenceDateMs = query.toTimestamp
+ ? new Date(query.toTimestamp).getTime()
+ : Date.now();
+ effectiveFromTimestamp = new Date(
+ referenceDateMs - defaultDateRangeDays * 24 * 60 * 60 * 1000,
+ ).toISOString();
+ }
- // 3. Apply default fields if configured and no fields query param provided
- let effectiveFields = query.fields ?? undefined;
- if (!query.fields && env.LANGFUSE_API_TRACES_DEFAULT_FIELDS) {
- const parsed = env.LANGFUSE_API_TRACES_DEFAULT_FIELDS.split(",")
- .map((f) => f.trim())
- .filter((f): f is TraceFieldGroup =>
- TRACE_FIELD_GROUPS.includes(f as TraceFieldGroup),
- );
- if (parsed.length > 0) {
- effectiveFields = parsed;
+ // 3. Apply default fields if configured and no fields query param provided
+ let effectiveFields = query.fields ?? undefined;
+ if (!query.fields && env.LANGFUSE_API_TRACES_DEFAULT_FIELDS) {
+ const parsed = env.LANGFUSE_API_TRACES_DEFAULT_FIELDS.split(",")
+ .map((f) => f.trim())
+ .filter((f): f is TraceFieldGroup =>
+ TRACE_FIELD_GROUPS.includes(f as TraceFieldGroup),
+ );
+ if (parsed.length > 0) {
+ effectiveFields = parsed;
+ }
}
- }
- const filterProps = {
- projectId: auth.scope.projectId,
- page: query.page ?? undefined,
- limit: query.limit ?? undefined,
- fields: effectiveFields,
- userId: query.userId ?? undefined,
- name: query.name ?? undefined,
- tags: query.tags ?? undefined,
- environment: query.environment ?? undefined,
- sessionId: query.sessionId ?? undefined,
- version: query.version ?? undefined,
- release: query.release ?? undefined,
- fromTimestamp: effectiveFromTimestamp,
- toTimestamp: query.toTimestamp ?? undefined,
- };
+ const filterProps = {
+ projectId: auth.scope.projectId,
+ page: query.page ?? undefined,
+ limit: query.limit ?? undefined,
+ fields: effectiveFields,
+ userId: query.userId ?? undefined,
+ name: query.name ?? undefined,
+ tags: query.tags ?? undefined,
+ environment: query.environment ?? undefined,
+ sessionId: query.sessionId ?? undefined,
+ version: query.version ?? undefined,
+ release: query.release ?? undefined,
+ fromTimestamp: effectiveFromTimestamp,
+ toTimestamp: query.toTimestamp ?? undefined,
+ };
+
+ // Use events table if query parameter is explicitly set, otherwise use environment variable
+ const useEventsTable =
+ query.useEventsTable !== undefined && query.useEventsTable !== null
+ ? query.useEventsTable === true
+ : env.LANGFUSE_ENABLE_EVENTS_TABLE_OBSERVATIONS === "true";
- // Use events table if query parameter is explicitly set, otherwise use environment variable
- const useEventsTable =
- query.useEventsTable !== undefined && query.useEventsTable !== null
- ? query.useEventsTable === true
- : env.LANGFUSE_ENABLE_EVENTS_TABLE_OBSERVATIONS === "true";
+ if (useEventsTable) {
+ const [items, count] = await Promise.all([
+ getTracesFromEventsTableForPublicApi({
+ ...filterProps,
+ advancedFilters: query.filter,
+ orderBy: query.orderBy ?? null,
+ }),
+ getTracesCountFromEventsTableForPublicApi({
+ ...filterProps,
+ advancedFilters: query.filter,
+ }),
+ ]);
+
+ return {
+ data: items.map((item) => ({
+ ...item,
+ externalId: null,
+ })),
+ meta: {
+ page: query.page,
+ limit: query.limit,
+ totalItems: count,
+ totalPages: Math.ceil(count / query.limit),
+ },
+ };
+ }
- if (useEventsTable) {
+ // Legacy code path using traces table
const [items, count] = await Promise.all([
- getTracesFromEventsTableForPublicApi({
- ...filterProps,
+ generateTracesForPublicApi({
+ props: filterProps,
advancedFilters: query.filter,
orderBy: query.orderBy ?? null,
}),
- getTracesCountFromEventsTableForPublicApi({
- ...filterProps,
+ getTracesCountForPublicApi({
+ props: filterProps,
advancedFilters: query.filter,
}),
]);
+ const finalCount = count || 0;
return {
data: items.map((item) => ({
...item,
@@ -146,65 +178,42 @@ export default withMiddlewares({
meta: {
page: query.page,
limit: query.limit,
- totalItems: count,
- totalPages: Math.ceil(count / query.limit),
+ totalItems: finalCount,
+ totalPages: Math.ceil(finalCount / query.limit),
},
};
- }
+ },
+ }),
- // Legacy code path using traces table
- const [items, count] = await Promise.all([
- generateTracesForPublicApi({
- props: filterProps,
- advancedFilters: query.filter,
- orderBy: query.orderBy ?? null,
- }),
- getTracesCountForPublicApi({
- props: filterProps,
- advancedFilters: query.filter,
- }),
- ]);
+ DELETE: createAuthedProjectAPIRoute({
+ name: "Delete Multiple Traces",
+ bodySchema: DeleteTracesV1Body,
+ responseSchema: DeleteTracesV1Response,
+ rateLimitResource: "trace-delete",
+ fn: async ({ body, auth }) => {
+ const { traceIds } = body;
- const finalCount = count || 0;
- return {
- data: items.map((item) => ({
- ...item,
- externalId: null,
- })),
- meta: {
- page: query.page,
- limit: query.limit,
- totalItems: finalCount,
- totalPages: Math.ceil(finalCount / query.limit),
- },
- };
- },
- }),
-
- DELETE: createAuthedProjectAPIRoute({
- name: "Delete Multiple Traces",
- bodySchema: DeleteTracesV1Body,
- responseSchema: DeleteTracesV1Response,
- rateLimitResource: "trace-delete",
- fn: async ({ body, auth }) => {
- const { traceIds } = body;
-
- await Promise.all(
- traceIds.map((traceId) =>
- auditLog({
- resourceType: "trace",
- resourceId: traceId,
- action: "delete",
- projectId: auth.scope.projectId,
- apiKeyId: auth.scope.apiKeyId,
- orgId: auth.scope.orgId,
- }),
- ),
- );
+ await Promise.all(
+ traceIds.map((traceId) =>
+ auditLog({
+ resourceType: "trace",
+ resourceId: traceId,
+ action: "delete",
+ projectId: auth.scope.projectId,
+ apiKeyId: auth.scope.apiKeyId,
+ orgId: auth.scope.orgId,
+ }),
+ ),
+ );
- await traceDeletionProcessor(auth.scope.projectId, traceIds);
+ await traceDeletionProcessor(auth.scope.projectId, traceIds);
- return { message: "Traces deleted successfully" };
- },
- }),
-});
+ return { message: "Traces deleted successfully" };
+ },
+ }),
+ },
+ {
+ clickHouseResourceErrorMessage:
+ LEGACY_PUBLIC_API_OBSERVATIONS_CLICKHOUSE_RESOURCE_ERROR_MESSAGE,
+ },
+);