Skip to content

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

feat: add traces experimentation (#4157)

Max Deichmann62e51b8cf6e5
diff --git a/web/src/server/api/routers/traces.ts b/web/src/server/api/routers/traces.ts
index 006a3c493e..7f9f6f88d5 100644
--- a/web/src/server/api/routers/traces.ts
+++ b/web/src/server/api/routers/traces.ts
@@ -166,46 +166,56 @@ export const traceRouter = createTRPCRouter({
}),
)
.query(async ({ input, ctx }) => {
- const { filterCondition, observationTimeseriesFilter, searchCondition } =
- parseTraceAllFilters(input);
- if (!input.queryClickhouse) {
- const countQuery = createTracesQuery({
- select: Prisma.sql`count(*)`,
- projectId: input.projectId,
- observationTimeseriesFilter,
- page: 0,
- limit: 1,
- searchCondition,
- filterCondition,
- });
-
- const totalTraces =
- await ctx.prisma.$queryRaw<Array<{ count: bigint }>>(countQuery);
+ return await measureAndReturnApi({
+ input,
+ operation: "traces.countAll",
+ user: ctx.session.user,
+ pgExecution: async () => {
+ const {
+ filterCondition,
+ observationTimeseriesFilter,
+ searchCondition,
+ } = parseTraceAllFilters(input);
- const totalTraceCount = totalTraces[0]?.count;
- return {
- totalCount: totalTraceCount ? Number(totalTraceCount) : undefined,
- };
- } else {
- if (!isClickhouseEligible(ctx.session.user)) {
- throw new TRPCError({
- code: "UNAUTHORIZED",
- message: "Not eligible to query clickhouse",
+ const countQuery = createTracesQuery({
+ select: Prisma.sql`count(*)`,
+ projectId: input.projectId,
+ observationTimeseriesFilter,
+ page: 0,
+ limit: 1,
+ searchCondition,
+ filterCondition,
});
- }
- const countQuery = await getTracesTableCount({
- projectId: ctx.session.projectId,
- filter: input.filter ?? [],
- searchQuery: input.searchQuery ?? undefined,
- limit: 1,
- offset: 0,
- });
+ const totalTraces =
+ await ctx.prisma.$queryRaw<Array<{ count: bigint }>>(countQuery);
- return {
- totalCount: countQuery,
- };
- }
+ const totalTraceCount = totalTraces[0]?.count;
+ return {
+ totalCount: totalTraceCount ? Number(totalTraceCount) : undefined,
+ };
+ },
+ clickhouseExecution: async () => {
+ if (!isClickhouseEligible(ctx.session.user)) {
+ throw new TRPCError({
+ code: "UNAUTHORIZED",
+ message: "Not eligible to query clickhouse",
+ });
+ }
+
+ const countQuery = await getTracesTableCount({
+ projectId: ctx.session.projectId,
+ filter: input.filter ?? [],
+ searchQuery: input.searchQuery ?? undefined,
+ limit: 1,
+ offset: 0,
+ });
+
+ return {
+ totalCount: countQuery,
+ };
+ },
+ });
}),
metrics: protectedProjectProcedure
.input(
@@ -217,10 +227,13 @@ export const traceRouter = createTRPCRouter({
)
.query(async ({ input, ctx }) => {
if (input.traceIds.length === 0) return [];
-
- if (!input.queryClickhouse) {
- const tracesQuery = createTracesQuery({
- select: Prisma.sql`
+ return await measureAndReturnApi({
+ input,
+ operation: "traces.metrics",
+ user: ctx.session.user,
+ pgExecution: async () => {
+ const tracesQuery = createTracesQuery({
+ select: Prisma.sql`
t.id,
COALESCE(generation_metrics."promptTokens", 0)::bigint AS "promptTokens",
COALESCE(generation_metrics."completionTokens", 0)::bigint AS "completionTokens",
@@ -232,73 +245,75 @@ export const traceRouter = createTRPCRouter({
COALESCE(generation_metrics."calculatedOutputCost", 0)::numeric AS "calculatedOutputCost",
observation_metrics."level" AS "level"
`,
- projectId: input.projectId,
- filterCondition: Prisma.sql`AND t.id IN (${Prisma.join(input.traceIds)})`,
- });
+ projectId: input.projectId,
+ filterCondition: Prisma.sql`AND t.id IN (${Prisma.join(input.traceIds)})`,
+ });
- const [traceMetrics, scores] = await Promise.all([
- // traceMetrics
- ctx.prisma.$queryRaw<Array<TracesMetricsReturnType>>(tracesQuery),
- // scores
- ctx.prisma.score.findMany({
- where: {
- projectId: input.projectId,
- traceId: {
- in: input.traceIds,
+ const [traceMetrics, scores] = await Promise.all([
+ // traceMetrics
+ ctx.prisma.$queryRaw<Array<TracesMetricsReturnType>>(tracesQuery),
+ // scores
+ ctx.prisma.score.findMany({
+ where: {
+ projectId: input.projectId,
+ traceId: {
+ in: input.traceIds,
+ },
},
- },
- }),
- ]);
+ }),
+ ]);
- const validatedScores = filterAndValidateDbScoreList(
- scores,
- traceException,
- );
-
- return traceMetrics.map((row) => ({
- ...row,
- scores: aggregateScores(
- validatedScores.filter((s) => s.traceId === row.id),
- ),
- }));
- } else {
- if (!isClickhouseEligible(ctx.session.user)) {
- throw new TRPCError({
- code: "UNAUTHORIZED",
- message: "Not eligible to query clickhouse",
- });
- }
-
- const res = await getTracesTable(ctx.session.projectId, [
- {
- type: "stringOptions",
- operator: "any of",
- column: "ID",
- value: input.traceIds,
- },
- ]);
+ const validatedScores = filterAndValidateDbScoreList(
+ scores,
+ traceException,
+ );
- const scores = await getScoresForTraces(
- ctx.session.projectId,
- res.map((r) => r.id),
- 1000,
- 0,
- );
-
- const validatedScores = filterAndValidateDbScoreList(
- scores,
- traceException,
- );
-
- return res.map((r) =>
- convertMetricsReturnType({
- ...r,
+ return traceMetrics.map((row) => ({
+ ...row,
scores: aggregateScores(
- validatedScores.filter((s) => s.traceId === r.id),
+ validatedScores.filter((s) => s.traceId === row.id),
),
- }),
- );
- }
+ }));
+ },
+ clickhouseExecution: async () => {
+ if (!isClickhouseEligible(ctx.session.user)) {
+ throw new TRPCError({
+ code: "UNAUTHORIZED",
+ message: "Not eligible to query clickhouse",
+ });
+ }
+
+ const res = await getTracesTable(ctx.session.projectId, [
+ {
+ type: "stringOptions",
+ operator: "any of",
+ column: "ID",
+ value: input.traceIds,
+ },
+ ]);
+
+ const scores = await getScoresForTraces(
+ ctx.session.projectId,
+ res.map((r) => r.id),
+ 1000,
+ 0,
+ );
+
+ const validatedScores = filterAndValidateDbScoreList(
+ scores,
+ traceException,
+ );
+
+ return res.map((r) =>
+ convertMetricsReturnType({
+ ...r,
+ scores: aggregateScores(
+ validatedScores.filter((s) => s.traceId === r.id),
+ ),
+ }),
+ );
+ },
+ });
}),
filterOptions: protectedProjectProcedure
.input(
@@ -309,45 +324,49 @@ export const traceRouter = createTRPCRouter({
}),
)
.query(async ({ input, ctx }) => {
- if (!input.queryClickhouse) {
- const { timestampFilter } = input;
- const prismaTimestampFilter = timestampFilter
- ? datetimeFilterToPrisma(timestampFilter)
- : {};
-
- const rawTimestampFilter =
- timestampFilter && timestampFilter.type === "datetime"
- ? datetimeFilterToPrismaSql(
- "timestamp",
- timestampFilter.operator,
- timestampFilter.value,
- )
- : Prisma.empty;
-
- const [scores, names, tags] = await Promise.all([
- ctx.prisma.score.groupBy({
- where: {
- projectId: input.projectId,
- timestamp: prismaTimestampFilter,
- dataType: { in: ["NUMERIC", "BOOLEAN"] },
- },
- take: 1000,
- orderBy: { name: "asc" },
- by: ["name"],
- }),
- ctx.prisma.trace.groupBy({
- where: {
- projectId: input.projectId,
- timestamp: prismaTimestampFilter,
- },
- by: ["name"],
- // limiting to 1k trace names to avoid performance issues.
- // some users have unique names for large amounts of traces
- // sending all trace names to the FE exceeds the cloud function return size limit
- take: 1000,
- orderBy: { name: "asc" },
- }),
- ctx.prisma.$queryRaw<{ value: string }[]>`
+ return await measureAndReturnApi({
+ input,
+ operation: "traces.filterOptions",
+ user: ctx.session.user,
+ pgExecution: async () => {
+ const { timestampFilter } = input;
+ const prismaTimestampFilter = timestampFilter
+ ? datetimeFilterToPrisma(timestampFilter)
+ : {};
+
+ const rawTimestampFilter =
+ timestampFilter && timestampFilter.type === "datetime"
+ ? datetimeFilterToPrismaSql(
+ "timestamp",
+ timestampFilter.operator,
+ timestampFilter.value,
+ )
+ : Prisma.empty;
+
+ const [scores, names, tags] = await Promise.all([
+ ctx.prisma.score.groupBy({
+ where: {
+ projectId: input.projectId,
+ timestamp: prismaTimestampFilter,
+ dataType: { in: ["NUMERIC", "BOOLEAN"] },
+ },
+ take: 1000,
+ orderBy: { name: "asc" },
+ by: ["name"],
+ }),
+ ctx.prisma.trace.groupBy({
+ where: {
+ projectId: input.projectId,
+ timestamp: prismaTimestampFilter,
+ },
+ by: ["name"],
+ // limiting to 1k trace names to avoid performance issues.
+ // some users have unique names for large amounts of traces
+ // sending all trace names to the FE exceeds the cloud function return size limit
+ take: 1000,
+ orderBy: { name: "asc" },
+ }),
+ ctx.prisma.$queryRaw<{ value: string }[]>`
SELECT tags.tag as value
FROM traces, UNNEST(traces.tags) AS tags(tag)
WHERE traces.project_id = ${input.projectId} ${rawTimestampFilter}
@@ -355,50 +374,52 @@ export const traceRouter = createTRPCRouter({
ORDER BY tags.tag ASC
LIMIT 1000
`,
- ]);
- const res: TraceOptions = {
- scores_avg: scores.map((score) => score.name),
- name: names
- .filter((n) => n.name !== null)
- .map((name) => ({
- value: name.name ?? "undefined",
- })),
- tags: tags,
- };
- return res;
- } else {
- if (!isClickhouseEligible(ctx.session.user)) {
- throw new TRPCError({
- code: "UNAUTHORIZED",
- message: "Not eligible to query clickhouse",
- });
- }
-
- const { timestampFilter } = input;
+ ]);
+ const res: TraceOptions = {
+ scores_avg: scores.map((score) => score.name),
+ name: names
+ .filter((n) => n.name !== null)
+ .map((name) => ({
+ value: name.name ?? "undefined",
+ })),
+ tags: tags,
+ };
+ return res;
+ },
+ clickhouseExecution: async () => {
+ if (!isClickhouseEligible(ctx.session.user)) {
+ throw new TRPCError({
+ code: "UNAUTHORIZED",
+ message: "Not eligible to query clickhouse",
+ });
+ }
- const [scoreNames, traceNames, tags] = await Promise.all([
- getScoresGroupedByName(
- input.projectId,
- timestampFilter ? [timestampFilter] : [],
- ),
- getTracesGroupedByName(
- input.projectId,
- tracesTableUiColumnDefinitions,
- timestampFilter ? [timestampFilter] : [],
- ),
- getTracesGroupedByTags({
- projectId: input.projectId,
- filter: timestampFilter ? [timestampFilter] : [],
- }),
- ]);
+ const { timestampFilter } = input;
- const res: TraceOptions = {
- name: traceNames.map((n) => ({ value: n.name })),
- scores_avg: scoreNames.map((s) => s.name),
- tags: tags,
- };
- return res;
- }
+ const [scoreNames, traceNames, tags] = await Promise.all([
+ getScoresGroupedByName(
+ input.projectId,
+ timestampFilter ? [timestampFilter] : [],
+ ),
+ getTracesGroupedByName(
+ input.projectId,
+ tracesTableUiColumnDefinitions,
+ timestampFilter ? [timestampFilter] : [],
+ ),
+ getTracesGroupedByTags({
+ projectId: input.projectId,
+ filter: timestampFilter ? [timestampFilter] : [],
+ }),
+ ]);
+
+ const res: TraceOptions = {
+ name: traceNames.map((n) => ({ value: n.name })),
+ scores_avg: scoreNames.map((s) => s.name),
+ tags: tags,
+ };
+ return res;
+ },
+ });
}),
byId: protectedGetTraceProcedure
.input(
@@ -410,27 +431,33 @@ export const traceRouter = createTRPCRouter({
}),
)
.query(async ({ input, ctx }) => {
- if (!input.queryClickhouse) {
- return await ctx.prisma.trace.findFirstOrThrow({
- where: {
- id: input.traceId,
- projectId: input.projectId,
- },
- });
- } else {
- if (!isClickhouseEligible(ctx.session.user)) {
- throw new TRPCError({
- code: "UNAUTHORIZED",
- message: "Not eligible to query clickhouse",
+ return await measureAndReturnApi({
+ input,
+ operation: "traces.byId",
+ user: ctx.session.user ?? undefined,
+ pgExecution: async () => {
+ return await ctx.prisma.trace.findFirstOrThrow({
+ where: {
+ id: input.traceId,
+ projectId: input.projectId,
+ },
});
- }
+ },
+ clickhouseExecution: async () => {
+ if (!isClickhouseEligible(ctx.session.user)) {
+ throw new TRPCError({
+ code: "UNAUTHORIZED",
+ message: "Not eligible to query clickhouse",
+ });
+ }
- return await getTraceByIdOrThrow(
- input.traceId,
- input.projectId,
- input.timestamp ?? undefined,
- );
- }
+ return await getTraceByIdOrThrow(
+ input.traceId,
+ input.projectId,
+ input.timestamp ?? undefined,
+ );
+ },
+ });
}),
byIdWithObservationsAndScores: protectedGetTraceProcedure
.input(
@@ -442,144 +469,142 @@ export const traceRouter = createTRPCRouter({
}),
)
.query(async ({ input, ctx }) => {
- if (!input.queryClickhouse) {
- 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,
+ return await measureAndReturnApi({
+ input,
+ operation: "traces.byIdWithObservationsAndScores",
+ user: ctx.session.user ?? undefined,
+ pgExecution: async () => {
+ 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,
- },
- }),
- ]);
- 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() -
+ }),
+ 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()
- : undefined
- : undefined;
-
- return {
- ...trace,
- scores: validatedScores,
- latency: latencyMs !== undefined ? latencyMs / 1000 : undefined,
- observations: observations as ObservationReturnType[],
- };
- }
+ : obsStartTimes.length > 1
+ ? obsStartTimes[obsStartTimes.length - 1]!.getTime() -
+ obsStartTimes[0]!.getTime()
+ : undefined
+ : undefined;
- if (!isClickhouseEligible(ctx.session.user)) {
- throw new TRPCError({
- code: "UNAUTHORIZED",
- message: "Not eligible to query clickhouse",
- });
- }
+ return {
+ ...trace,
+ scores: validatedScores,
+ latency: latencyMs !== undefined ? latencyMs / 1000 : undefined,
+ observations: observations as ObservationReturnType[],
+ };
+ },
+ clickhouseExecution: async () => {
+ const [trace, observations, scores] = await Promise.all([
+ getTraceByIdOrThrow(
+ input.traceId,
+ input.projectId,
+ input.timestamp ?? undefined,
+ ),
+ getObservationsViewForTrace(input.traceId, input.projectId),
+ getScoresForTraces(
+ input.projectId,
+ [input.traceId],
+ undefined,
+ undefined,
+ ),
+ ]);
- const [trace, observations, scores] = await Promise.all([
- getTraceByIdOrThrow(
- input.traceId,
- input.projectId,
- input.timestamp ?? undefined,
- ),
- getObservationsViewForTrace(input.traceId, input.projectId),
- getScoresForTraces(
- input.projectId,
- [input.traceId],
- undefined,
- undefined,
- ),
- ]);
+ const validatedScores = filterAndValidateDbScoreList(
+ scores,
+ traceException,
+ );
- 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[],
- };
- }),
+ 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[],
+ };
+ },
+ });
+ }),
deleteMany: protectedProjectProcedure
.input(
z.object({
diff --git a/web/src/server/utils/checkClickhouseAccess.ts b/web/src/server/utils/checkClickhouseAccess.ts
index f17ce101c8..6b11701cb2 100644
--- a/web/src/server/utils/checkClickhouseAccess.ts
+++ b/web/src/server/utils/checkClickhouseAccess.ts
@@ -47,10 +47,16 @@ export const measureAndReturnApi = async <T, Y>(args: {
});
}
- if (!input.queryClickhouse) {
- return await pgExecution(input);
+ // if query clickhouse, return clickhouse only. Only possible for admin users
+ if (input.queryClickhouse) {
+ return await clickhouseExecution(input);
}
+ // logic for regular users:
+ // if env.LANGFUSE_READ_FROM_POSTGRES_ONLY is true, return postgres only
+ // otherwise fetch both and compare timing
+ // if env.LANGFUSE_RETURN_FROM_CLICKHOUSE is true, return clickhouse data
+
if (env.LANGFUSE_READ_FROM_POSTGRES_ONLY === "true") {
logger.info("Read from postgres only");
return await pgExecution(input);