Skip to content

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

feat: support for traces detail view with clickhouse (#3982)

Max Deichmann7d94831c0181
diff --git a/packages/shared/src/server/repositories/index.ts b/packages/shared/src/server/repositories/index.ts
index c0f0bd503c..147dd5a284 100644
--- a/packages/shared/src/server/repositories/index.ts
+++ b/packages/shared/src/server/repositories/index.ts
@@ -1,2 +1,3 @@
export * from "./scores";
export * from "./traces";
+export * from "./observations";
diff --git a/packages/shared/src/server/repositories/observations.ts b/packages/shared/src/server/repositories/observations.ts
new file mode 100644
index 0000000000..2cc37aa66c
--- /dev/null
+++ b/packages/shared/src/server/repositories/observations.ts
@@ -0,0 +1,221 @@
+import { ObservationClickhouseRecord } from "../clickhouse/schema";
+import { queryClickhouse } from "./clickhouse";
+import {
+ Model,
+ Observation,
+ ObservationLevel,
+ ObservationType,
+ ObservationView,
+ Price,
+} from "@prisma/client";
+import { logger } from "../logger";
+import { InternalServerError, LangfuseNotFoundError } from "../../errors";
+import Decimal from "decimal.js";
+import { prisma } from "../../db";
+import { jsonSchema } from "../../utils/zod";
+
+export const convertObservation = async (
+ record: ObservationClickhouseRecord,
+): Promise<Observation> => {
+ const model = await prisma.model.findFirst({
+ where: {
+ id: record.internal_model_id,
+ },
+ include: {
+ Price: true,
+ },
+ });
+ return await convertObservationAndModel(record, model);
+};
+
+export const convertObservationToView = async (
+ record: ObservationClickhouseRecord,
+): Promise<ObservationView> => {
+ const model = await prisma.model.findFirst({
+ where: {
+ id: record.internal_model_id,
+ },
+ include: {
+ Price: true,
+ },
+ });
+ return {
+ ...(await convertObservationAndModel(record, model)),
+ latency: record.end_time
+ ? new Date(record.end_time).getTime() -
+ new Date(record.start_time).getTime()
+ : null,
+ timeToFirstToken: record.completion_start_time
+ ? new Date(record.start_time).getTime() -
+ new Date(record.completion_start_time).getTime()
+ : 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,
+ promptName: record.prompt_name ?? null,
+ promptVersion: record.prompt_version ?? null,
+ modelId: record.internal_model_id ?? null,
+ };
+};
+
+const convertObservationAndModel = async (
+ record: ObservationClickhouseRecord,
+ model: (Model & { Price: Price[] }) | null,
+): Promise<Observation> => {
+ return {
+ id: record.id,
+ traceId: record.trace_id,
+ projectId: record.project_id,
+ type: record.type as ObservationType,
+ parentObservationId: record.parent_observation_id ?? null,
+ startTime: new Date(record.start_time),
+ endTime: record.end_time ? new Date(record.end_time) : null,
+ name: record.name,
+ metadata: record.metadata,
+ level: record.level as ObservationLevel,
+ statusMessage: record.status_message ?? null,
+ version: record.version ?? null,
+ input: jsonSchema.nullish().parse(record.input) ?? null,
+ output: jsonSchema.nullish().parse(record.output) ?? null,
+ modelParameters: jsonSchema.nullable().parse(record.model_parameters),
+ completionStartTime: record.completion_start_time
+ ? new Date(record.completion_start_time)
+ : null,
+ promptId: record.prompt_id ?? null,
+ createdAt: new Date(record.created_at),
+ updatedAt: new Date(record.updated_at),
+ promptTokens: record.usage_details?.input ?? 0,
+ completionTokens: record.usage_details?.output ?? 0,
+ totalTokens: record.usage_details?.total ?? 0,
+ calculatedInputCost: record.cost_details?.input
+ ? new Decimal(record.cost_details.input)
+ : null,
+ calculatedOutputCost: record.cost_details?.output
+ ? new Decimal(record.cost_details.output)
+ : null,
+ calculatedTotalCost: record.cost_details?.total
+ ? new Decimal(record.cost_details.total)
+ : null,
+ inputCost: record.cost_details?.input
+ ? new Decimal(record.cost_details?.input)
+ : null,
+ outputCost: record.cost_details?.output
+ ? new Decimal(record.cost_details?.output)
+ : null,
+ totalCost: record.cost_details?.total
+ ? new Decimal(record.cost_details?.total)
+ : null,
+
+ model: record.provided_model_name ?? null,
+ internalModelId: record.internal_model_id ?? null,
+ internalModel: model?.modelName ?? null, // to be removed
+ unit: model?.Price?.shift()?.usageType ?? null,
+ };
+};
+
+export const getObservationsViewForTrace = async (
+ traceId: string,
+ projectId: string,
+ fetchWithInputOutput: boolean = false,
+) => {
+ const query = `
+ SELECT
+ id,
+ trace_id,
+ project_id,
+ type,
+ parent_observation_id,
+ start_time,
+ end_time,
+ name,
+ metadata,
+ level,
+ status_message,
+ version,
+ ${fetchWithInputOutput ? "input, output," : ""}
+ provided_model_name,
+ internal_model_id,
+ model_parameters,
+ provided_usage_details,
+ usage_details,
+ provided_cost_details,
+ cost_details,
+ total_cost,
+ completion_start_time,
+ prompt_id,
+ prompt_name,
+ prompt_version,
+ created_at,
+ updated_at,
+ event_ts
+ FROM observations FINAL WHERE trace_id = {traceId: String} AND project_id = {projectId: String}`;
+ const records = await queryClickhouse<ObservationClickhouseRecord>({
+ query,
+ params: { traceId, projectId },
+ });
+
+ return await Promise.all(
+ records.map(async (o) => await convertObservationToView(o)),
+ );
+};
+
+export const getObservationById = async (
+ id: string,
+ projectId: string,
+ fetchWithInputOutput: boolean = false,
+) => {
+ const query = `
+ SELECT
+ id,
+ trace_id,
+ project_id,
+ type,
+ parent_observation_id,
+ start_time,
+ end_time,
+ name,
+ metadata,
+ level,
+ status_message,
+ version,
+ ${fetchWithInputOutput ? "input, output," : ""}
+ provided_model_name,
+ internal_model_id,
+ model_parameters,
+ provided_usage_details,
+ usage_details,
+ provided_cost_details,
+ cost_details,
+ total_cost,
+ completion_start_time,
+ prompt_id,
+ prompt_name,
+ prompt_version,
+ created_at,
+ updated_at,
+ event_ts
+ FROM observations FINAL WHERE id = {id: String} AND project_id = {projectId: String}`;
+ const records = await queryClickhouse<ObservationClickhouseRecord>({
+ query,
+ params: { id, projectId },
+ });
+
+ const mapped = records.map((r) => convertObservation(r));
+
+ if (mapped.length === 0) {
+ throw new LangfuseNotFoundError(`Observation with id ${id} not found`);
+ }
+
+ if (mapped.length > 1) {
+ logger.error(
+ `Multiple observations found for id ${id} and project ${projectId}`,
+ );
+ throw new InternalServerError(
+ `Multiple observations found for id ${id} and project ${projectId}`,
+ );
+ }
+ return mapped.shift();
+};
diff --git a/packages/shared/src/server/repositories/scores.ts b/packages/shared/src/server/repositories/scores.ts
index d1d350bccd..98bf42f41a 100644
--- a/packages/shared/src/server/repositories/scores.ts
+++ b/packages/shared/src/server/repositories/scores.ts
@@ -50,8 +50,8 @@ const convertToScore = (row: FetchScoresReturnType) => {
export const getScoresForTraces = async (
projectId: string,
traceIds: string[],
- limit: number,
- offset: number,
+ limit?: number,
+ offset?: number,
) => {
const query = `
select
@@ -59,7 +59,7 @@ export const getScoresForTraces = async (
from scores s final
WHERE s.project_id = {projectId: String}
AND s.trace_id IN ({traceIds: Array(String)})
- limit {limit: Int32} offset {offset: Int32};
+ ${limit && offset ? `limit {limit: Int32} offset {offset: Int32}` : ""}
`;
const rows = await queryClickhouse<FetchScoresReturnType>({
diff --git a/packages/shared/src/server/repositories/traces.ts b/packages/shared/src/server/repositories/traces.ts
index 8ef14097ef..0260306e4a 100644
--- a/packages/shared/src/server/repositories/traces.ts
+++ b/packages/shared/src/server/repositories/traces.ts
@@ -4,7 +4,7 @@ import {
createFilterFromFilterState,
getProjectIdDefaultFilter,
} from "../queries/clickhouse-filter/factory";
-import { ObservationLevel } from "@prisma/client";
+import { ObservationLevel, Trace } from "@prisma/client";
import { FilterState } from "../../types";
import { logger } from "../logger";
import { FilterList } from "../queries/clickhouse-filter/clickhouse-filter";
@@ -165,33 +165,44 @@ const getTracesTableGeneric = async <T>(
return rows;
};
-export const getTraceById = async (traceId: string, projectId: string) => {
+export const getTraceByIdOrThrow = async (
+ traceId: string,
+ projectId: string,
+) => {
const query = `SELECT * FROM traces where id = {traceId: String} and project_id = {projectId: String} order by event_ts desc LIMIT 1 by id, project_id`;
const records = await queryClickhouse<TraceClickhouseRecord>({
query,
params: { traceId, projectId },
});
- const res = records.map((record) => {
+ const res = records.map<Trace>((record) => {
return {
id: record.id,
projectId: record.project_id,
- name: record.name,
+ name: record.name ?? null,
timestamp: new Date(record.timestamp),
tags: record.tags,
bookmarked: record.bookmarked,
- release: record.release,
- version: record.version,
- userId: record.user_id,
- sessionId: record.session_id,
+ release: record.release ?? null,
+ version: record.version ?? null,
+ userId: record.user_id ?? null,
+ sessionId: record.session_id ?? null,
public: record.public,
- input: record.input,
- output: record.output,
+ input: record.input ?? null,
+ output: record.output ?? null,
metadata: record.metadata,
+ createdAt: new Date(record.created_at),
+ updatedAt: new Date(record.updated_at),
+ externalId: null,
};
});
- return res.length ? res[0] : undefined;
+ if (res.length !== 1) {
+ const errorMessage = `Trace not found or multiple traces found for traceId: ${traceId}, projectId: ${projectId}`;
+ logger.error(errorMessage);
+ throw new Error(errorMessage);
+ }
+ return res[0] as Trace;
};
export const getTracesGroupedByName = async (
diff --git a/web/src/components/layouts/ClickhouseAdminToggle.tsx b/web/src/components/layouts/ClickhouseAdminToggle.tsx
index fb37f6f9e7..9e296a9840 100644
--- a/web/src/components/layouts/ClickhouseAdminToggle.tsx
+++ b/web/src/components/layouts/ClickhouseAdminToggle.tsx
@@ -21,7 +21,8 @@ export function ClickhouseAdminToggle() {
};
return (
- <div className="ml-auto flex items-center space-x-1">
+ <div className="flex items-center space-x-1">
+ <span className="mr-2">Clickhouse Queries</span>
<div
title={
isEnabled ? "Disable Clickhouse Queries" : "Enable Clickhouse Queries"
diff --git a/web/src/components/trace/ObservationPreview.tsx b/web/src/components/trace/ObservationPreview.tsx
index 9e2bb3c3b3..de1eb4da2a 100644
--- a/web/src/components/trace/ObservationPreview.tsx
+++ b/web/src/components/trace/ObservationPreview.tsx
@@ -37,6 +37,7 @@ import {
TabsBarList,
TabsBarTrigger,
} from "@/src/components/ui/tabs-bar";
+import { useClickhouse } from "@/src/components/layouts/ClickhouseAdminToggle";
export const ObservationPreview = ({
observations,
@@ -72,6 +73,7 @@ export const ObservationPreview = ({
observationId: currentObservationId,
traceId: traceId,
projectId: projectId,
+ queryClickhouse: useClickhouse(),
});
const preloadedObservation = observations.find(
diff --git a/web/src/components/trace/index.tsx b/web/src/components/trace/index.tsx
index d98a350888..10c8ef8ff0 100644
--- a/web/src/components/trace/index.tsx
+++ b/web/src/components/trace/index.tsx
@@ -35,6 +35,7 @@ import { type APIScore } from "@langfuse/shared";
import { FullScreenPage } from "@/src/components/layouts/full-screen-page";
import { calculateDisplayTotalCost } from "@/src/components/trace/lib/helpers";
import { useIsAuthenticatedAndProjectMember } from "@/src/features/auth/hooks";
+import { useClickhouse } from "@/src/components/layouts/ClickhouseAdminToggle";
import {
TabsBar,
TabsBarContent,
@@ -253,7 +254,11 @@ export function TracePage({ traceId }: { traceId: string }) {
router.query.projectId as string,
);
const trace = api.traces.byIdWithObservationsAndScores.useQuery(
- { traceId, projectId: router.query.projectId as string },
+ {
+ traceId,
+ projectId: router.query.projectId as string,
+ queryClickhouse: useClickhouse(),
+ },
{
retry(failureCount, error) {
if (error.data?.code === "UNAUTHORIZED") return false;
diff --git a/web/src/server/api/routers/observations.ts b/web/src/server/api/routers/observations.ts
index ea4d731822..2540887251 100644
--- a/web/src/server/api/routers/observations.ts
+++ b/web/src/server/api/routers/observations.ts
@@ -2,8 +2,52 @@ import {
createTRPCRouter,
protectedGetTraceProcedure,
} from "@/src/server/api/trpc";
+import { isClickhouseEligible } from "@/src/server/utils/checkClickhouseAccess";
+import {
+ type jsonSchema,
+ type ObservationLevel,
+ type ObservationType,
+} from "@langfuse/shared";
+import { getObservationById } from "@langfuse/shared/src/server";
+import { TRPCError } from "@trpc/server";
+import type Decimal from "decimal.js";
import { z } from "zod";
+export type SingleObservationReturnType = {
+ name: string | null;
+ id: string;
+ createdAt: Date;
+ updatedAt: Date;
+ type: ObservationType;
+ traceId: string | null;
+ projectId: string;
+ input: z.infer<typeof jsonSchema> | null;
+ startTime: Date;
+ endTime: Date | null;
+ metadata: z.infer<typeof jsonSchema> | null;
+ parentObservationId: string | null;
+ level: ObservationLevel;
+ statusMessage: string | null;
+ version: string | null;
+ model: string | null;
+ internalModel: string | null;
+ internalModelId: string | null;
+ modelParameters: z.infer<typeof jsonSchema> | null;
+ output: z.infer<typeof jsonSchema> | null;
+ promptTokens: number;
+ completionTokens: number;
+ totalTokens: number;
+ unit: string | null;
+ inputCost: Decimal | null;
+ outputCost: Decimal | null;
+ totalCost: Decimal | null;
+ calculatedInputCost: Decimal | null;
+ calculatedOutputCost: Decimal | null;
+ calculatedTotalCost: Decimal | null;
+ completionStartTime: Date | null;
+ promptId: string | null;
+};
+
export const observationsRouter = createTRPCRouter({
byId: protectedGetTraceProcedure
.input(
@@ -11,15 +55,30 @@ export const observationsRouter = createTRPCRouter({
observationId: z.string(),
traceId: z.string(), // required for protectedGetTraceProcedure
projectId: z.string(), // required for protectedGetTraceProcedure
+ queryClickhouse: z.boolean().default(false),
}),
)
.query(async ({ input, ctx }) => {
- return ctx.prisma.observation.findFirstOrThrow({
- where: {
- id: input.observationId,
- traceId: input.traceId,
- projectId: input.projectId,
- },
- });
+ if (!input.queryClickhouse) {
+ return ctx.prisma.observation.findFirstOrThrow({
+ where: {
+ id: input.observationId,
+ traceId: input.traceId,
+ projectId: input.projectId,
+ },
+ });
+ } else {
+ if (!isClickhouseEligible(ctx.session.user)) {
+ throw new TRPCError({
+ code: "UNAUTHORIZED",
+ message: "Not eligible to query clickhouse",
+ });
+ }
+ return await getObservationById(
+ input.observationId,
+ input.projectId,
+ true,
+ );
+ }
}),
});
diff --git a/web/src/server/api/routers/traces.ts b/web/src/server/api/routers/traces.ts
index fb73ceb0cd..e9fa8a7a3e 100644
--- a/web/src/server/api/routers/traces.ts
+++ b/web/src/server/api/routers/traces.ts
@@ -31,11 +31,12 @@ import {
getTracesTable,
getTracesTableCount,
getScoresForTraces,
- getTraceById,
+ getTraceByIdOrThrow,
type TracesTableReturnType,
getScoresGroupedByName,
getTracesGroupedByName,
getTracesGroupedByTags,
+ getObservationsViewForTrace,
} from "@langfuse/shared/src/server";
import { TRPCError } from "@trpc/server";
import Decimal from "decimal.js";
@@ -469,7 +470,7 @@ export const traceRouter = createTRPCRouter({
});
}
- return await getTraceById(input.traceId, input.projectId);
+ return await getTraceByIdOrThrow(input.traceId, input.projectId);
}
}),
byIdWithObservationsAndScores: protectedGetTraceProcedure
@@ -477,62 +478,113 @@ export const traceRouter = createTRPCRouter({
z.object({
traceId: z.string(), // used for security check
projectId: z.string(), // used for security check
+ queryClickhouse: z.boolean().default(false),
}),
)
.query(async ({ input, ctx }) => {
- const [trace, observations, scores] = await Promise.all([
- ctx.prisma.trace.findFirstOrThrow({
- where: {
- id: input.traceId,
- projectId: input.projectId,
- },
- }),
- ctx.prisma.observationView.findMany({
- select: {
- id: true,
- traceId: true,
- projectId: true,
- type: true,
- startTime: true,
- endTime: true,
- name: true,
- parentObservationId: true,
- level: true,
- statusMessage: true,
- version: true,
- createdAt: true,
- model: true,
- modelParameters: true,
- promptTokens: true,
- completionTokens: true,
- totalTokens: true,
- unit: true,
- completionStartTime: true,
- timeToFirstToken: true,
- promptId: true,
- modelId: true,
- inputPrice: true,
- outputPrice: true,
- totalPrice: true,
- calculatedInputCost: true,
- calculatedOutputCost: true,
- calculatedTotalCost: true,
- },
- where: {
- traceId: {
- equals: input.traceId,
- not: null,
+ if (!input.queryClickhouse) {
+ const [trace, observations, scores] = await Promise.all([
+ ctx.prisma.trace.findFirstOrThrow({
+ where: {
+ id: input.traceId,
+ projectId: input.projectId,
},
- projectId: input.projectId,
- },
- }),
- ctx.prisma.score.findMany({
- where: {
- traceId: input.traceId,
- projectId: input.projectId,
- },
- }),
+ }),
+ ctx.prisma.observationView.findMany({
+ select: {
+ id: true,
+ traceId: true,
+ projectId: true,
+ type: true,
+ startTime: true,
+ endTime: true,
+ name: true,
+ parentObservationId: true,
+ level: true,
+ statusMessage: true,
+ version: true,
+ createdAt: true,
+ model: true,
+ modelParameters: true,
+ promptTokens: true,
+ completionTokens: true,
+ totalTokens: true,
+ unit: true,
+ completionStartTime: true,
+ timeToFirstToken: true,
+ promptId: true,
+ modelId: true,
+ inputPrice: true,
+ outputPrice: true,
+ totalPrice: true,
+ calculatedInputCost: true,
+ calculatedOutputCost: true,
+ calculatedTotalCost: true,
+ },
+ where: {
+ traceId: {
+ equals: input.traceId,
+ not: null,
+ },
+ projectId: input.projectId,
+ },
+ }),
+ ctx.prisma.score.findMany({
+ where: {
+ traceId: input.traceId,
+ projectId: input.projectId,
+ },
+ }),
+ ]);
+ const validatedScores = filterAndValidateDbScoreList(
+ scores,
+ 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 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() -
+ obsStartTimes[0]!.getTime()
+ : undefined
+ : undefined;
+
+ return {
+ ...trace,
+ scores: validatedScores,
+ latency: latencyMs !== undefined ? latencyMs / 1000 : undefined,
+ observations: observations as ObservationReturnType[],
+ };
+ }
+
+ if (!isClickhouseEligible(ctx.session.user)) {
+ throw new TRPCError({
+ code: "UNAUTHORIZED",
+ message: "Not eligible to query clickhouse",
+ });
+ }
+
+ const [trace, observations, scores] = await Promise.all([
+ getTraceByIdOrThrow(input.traceId, input.projectId),
+ getObservationsViewForTrace(input.traceId, input.projectId),
+ getScoresForTraces(
+ input.projectId,
+ [input.traceId],
+ undefined,
+ undefined,
+ ),
]);
+
const validatedScores = filterAndValidateDbScoreList(
scores,
traceException,
@@ -563,6 +615,7 @@ export const traceRouter = createTRPCRouter({
observations: observations as ObservationReturnType[],
};
}),
+
deleteMany: protectedProjectProcedure
.input(
z.object({
diff --git a/web/src/server/api/trpc.ts b/web/src/server/api/trpc.ts
index 934b7ea6ee..d023548586 100644
--- a/web/src/server/api/trpc.ts
+++ b/web/src/server/api/trpc.ts
@@ -78,7 +78,12 @@ import superjson from "superjson";
import { ZodError } from "zod";
import { setUpSuperjson } from "@/src/utils/superjson";
import { DB } from "@/src/server/db";
-import { addUserToSpan, logger } from "@langfuse/shared/src/server";
+import {
+ addUserToSpan,
+ getTraceByIdOrThrow,
+ logger,
+} from "@langfuse/shared/src/server";
+import { isClickhouseEligible } from "@/src/server/utils/checkClickhouseAccess";
setUpSuperjson();
@@ -330,15 +335,28 @@ const enforceTraceAccess = t.middleware(async ({ ctx, rawInput, next }) => {
const traceId = result.data.traceId;
const projectId = result.data.projectId;
- const trace = await prisma.trace.findFirst({
- where: {
- id: traceId,
- projectId: projectId,
- },
- select: {
- public: true,
- },
- });
+ // if the user is eligible for clickhouse, and wants to use clickhouse, do so.
+ let trace;
+
+ if (
+ result.data.queryClickhouse === true &&
+ isClickhouseEligible(ctx.session?.user)
+ ) {
+ logger.info(
+ `Querying Clickhouse for traceid: ${traceId} and project: ${projectId} `,
+ );
+ trace = await getTraceByIdOrThrow(traceId, projectId);
+ } else {
+ trace = await prisma.trace.findFirst({
+ where: {
+ id: traceId,
+ projectId: projectId,
+ },
+ select: {
+ public: true,
+ },
+ });
+ }
if (!trace)
throw new TRPCError({