Skip to content

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

chore: remove outdated postgres executions (#5069)

Steffen Schmitzd7ec924ed8f5
diff --git a/packages/shared/src/server/repositories/scores.ts b/packages/shared/src/server/repositories/scores.ts
index 6a5ff3f3b1..de7c27a3b1 100644
--- a/packages/shared/src/server/repositories/scores.ts
+++ b/packages/shared/src/server/repositories/scores.ts
@@ -204,20 +204,24 @@ export const getScoresForObservations = async (
return rows.map(convertToScore);
};
-export const getScoresGroupedByNameSourceType = async (projectId: string) => {
+export const getScoresGroupedByNameSourceType = async (
+ projectId: string,
+ timestamp: Date | undefined,
+) => {
// We mainly use queries like this to retrieve filter options.
// Therefore, we can skip final as some inaccuracy in count is acceptable.
const query = `
- select
- name,
- source,
- data_type
- from scores s
- WHERE s.project_id = {projectId: String}
- GROUP BY name, source, data_type
- ORDER BY count() desc
- LIMIT 1000;
- `;
+ select
+ name,
+ source,
+ data_type
+ from scores s
+ WHERE s.project_id = {projectId: String}
+ ${timestamp ? `AND s.timestamp >= {timestamp: DateTime64(3)}` : ""}
+ GROUP BY name, source, data_type
+ ORDER BY count() desc
+ LIMIT 1000;
+ `;
const rows = await queryClickhouse<{
name: string;
@@ -227,6 +231,9 @@ export const getScoresGroupedByNameSourceType = async (projectId: string) => {
query: query,
params: {
projectId: projectId,
+ ...(timestamp
+ ? { timestamp: convertDateToClickhouseDateTime(timestamp) }
+ : {}),
},
});
diff --git a/web/src/ee/features/annotation-queues/server/annotationQueueItems.ts b/web/src/ee/features/annotation-queues/server/annotationQueueItems.ts
index 3c4490ca19..625668e163 100644
--- a/web/src/ee/features/annotation-queues/server/annotationQueueItems.ts
+++ b/web/src/ee/features/annotation-queues/server/annotationQueueItems.ts
@@ -5,7 +5,6 @@ import {
createTRPCRouter,
protectedProjectProcedure,
} from "@/src/server/api/trpc";
-import { measureAndReturnApi } from "@/src/server/utils/checkClickhouseAccess";
import {
type AnnotationQueueItem,
AnnotationQueueObjectType,
@@ -79,38 +78,14 @@ export const queueItemRouter = createTRPCRouter({
};
if (item.objectType === AnnotationQueueObjectType.OBSERVATION) {
- await measureAndReturnApi({
- input: { projectId: input.projectId, queryClickhouse: false },
- operation: "annotations.byId",
- user: ctx.session.user,
- pgExecution: async () => {
- const observation = await ctx.prisma.observation.findUnique({
- where: {
- id: item.objectId,
- projectId: input.projectId,
- },
- select: {
- id: true,
- traceId: true,
- },
- });
-
- return {
- ...inflatedItem,
- parentTraceId: observation?.traceId,
- };
- },
- clickhouseExecution: async () => {
- const clickhouseObservation = await getObservationById(
- item.objectId,
- input.projectId,
- );
- return {
- ...inflatedItem,
- parentTraceId: clickhouseObservation?.traceId,
- };
- },
- });
+ const clickhouseObservation = await getObservationById(
+ item.objectId,
+ input.projectId,
+ );
+ return {
+ ...inflatedItem,
+ parentTraceId: clickhouseObservation?.traceId,
+ };
}
return inflatedItem;
@@ -147,131 +122,68 @@ export const queueItemRouter = createTRPCRouter({
scope: "annotationQueues:read",
});
- return await measureAndReturnApi({
- input: { projectId: input.projectId, queryClickhouse: false },
- operation: "annotationQueueItems.itemsByQueue",
- user: ctx.session.user,
- pgExecution: async () => {
- const [queueItems, totalItems] = await Promise.all([
- // queueItems
- ctx.prisma.$queryRaw<
- Array<{
- id: string;
- status: AnnotationQueueStatus;
- objectId: string;
- objectType: AnnotationQueueObjectType;
- parentTraceId: string | null;
- completedAt: string | null;
- annotatorUserId: string | null;
- annotatorUserImage: string | null;
- annotatorUserName: string | null;
- }>
- >(Prisma.sql`
- SELECT
- aqi.id,
- aqi.status,
- aqi.object_id AS "objectId",
- aqi.object_type AS "objectType",
- o.trace_id AS "parentTraceId",
- aqi.completed_at AS "completedAt",
- aqi.annotator_user_id AS "annotatorUserId",
- u.image AS "annotatorUserImage",
- u.name AS "annotatorUserName"
- FROM
- annotation_queue_items aqi
- LEFT JOIN
- observations o ON o.id = aqi.object_id AND aqi.object_type = 'OBSERVATION' AND o.project_id = ${input.projectId}
- LEFT JOIN
- users u ON u.id = aqi.annotator_user_id AND u.id in (SELECT user_id FROM organization_memberships WHERE org_id = ${ctx.session.orgId})
- WHERE
- aqi.project_id = ${input.projectId} AND aqi.queue_id = ${input.queueId}
- ORDER BY
- aqi.created_at ASC,
- aqi.object_id ASC,
- aqi.object_type ASC
- ${input.limit ? Prisma.sql`LIMIT ${input.limit}` : Prisma.empty}
- ${input.page && input.limit ? Prisma.sql`OFFSET ${input.page * input.limit}` : Prisma.empty}
- `),
- // totalItems
- ctx.prisma.annotationQueueItem.count({
- where: {
- queueId: input.queueId,
- projectId: input.projectId,
- },
- }),
- ]);
-
- return { queueItems, totalItems };
- },
- clickhouseExecution: async () => {
- const [queueItems, totalItems] = await Promise.all([
- await ctx.prisma.$queryRaw<
- Array<{
- id: string;
- status: AnnotationQueueStatus;
- objectId: string;
- objectType: AnnotationQueueObjectType;
- completedAt: string | null;
- annotatorUserId: string | null;
- annotatorUserImage: string | null;
- annotatorUserName: string | null;
- }>
- >(Prisma.sql`
- SELECT
- aqi.id,
- aqi.status,
- aqi.object_id AS "objectId",
- aqi.object_type AS "objectType",
- aqi.completed_at AS "completedAt",
- aqi.annotator_user_id AS "annotatorUserId",
- u.image AS "annotatorUserImage",
- u.name AS "annotatorUserName"
- FROM
- annotation_queue_items aqi
- LEFT JOIN
- users u ON u.id = aqi.annotator_user_id AND u.id in (SELECT user_id FROM organization_memberships WHERE org_id = ${ctx.session.orgId})
- WHERE
- aqi.project_id = ${input.projectId} AND aqi.queue_id = ${input.queueId}
- ORDER BY
- aqi.created_at ASC,
- aqi.object_id ASC,
- aqi.object_type ASC
- ${input.limit ? Prisma.sql`LIMIT ${input.limit}` : Prisma.empty}
- ${input.page && input.limit ? Prisma.sql`OFFSET ${input.page * input.limit}` : Prisma.empty}
- `),
- ctx.prisma.annotationQueueItem.count({
- where: {
- queueId: input.queueId,
- projectId: input.projectId,
- },
- }),
- ]);
+ const [queueItems, totalItems] = await Promise.all([
+ await ctx.prisma.$queryRaw<
+ Array<{
+ id: string;
+ status: AnnotationQueueStatus;
+ objectId: string;
+ objectType: AnnotationQueueObjectType;
+ completedAt: string | null;
+ annotatorUserId: string | null;
+ annotatorUserImage: string | null;
+ annotatorUserName: string | null;
+ }>
+ >(Prisma.sql`
+ SELECT
+ aqi.id,
+ aqi.status,
+ aqi.object_id AS "objectId",
+ aqi.object_type AS "objectType",
+ aqi.completed_at AS "completedAt",
+ aqi.annotator_user_id AS "annotatorUserId",
+ u.image AS "annotatorUserImage",
+ u.name AS "annotatorUserName"
+ FROM
+ annotation_queue_items aqi
+ LEFT JOIN
+ users u ON u.id = aqi.annotator_user_id AND u.id in (SELECT user_id FROM organization_memberships WHERE org_id = ${ctx.session.orgId})
+ WHERE
+ aqi.project_id = ${input.projectId} AND aqi.queue_id = ${input.queueId}
+ ORDER BY
+ aqi.created_at ASC,
+ aqi.object_id ASC,
+ aqi.object_type ASC
+ ${input.limit ? Prisma.sql`LIMIT ${input.limit}` : Prisma.empty}
+ ${input.page && input.limit ? Prisma.sql`OFFSET ${input.page * input.limit}` : Prisma.empty}
+ `),
+ ctx.prisma.annotationQueueItem.count({
+ where: {
+ queueId: input.queueId,
+ projectId: input.projectId,
+ },
+ }),
+ ]);
- const observationIds = queueItems
- .filter(
- (item) =>
- item.objectType === AnnotationQueueObjectType.OBSERVATION,
- )
- .map((item) => item.objectId);
+ const observationIds = queueItems
+ .filter(
+ (item) => item.objectType === AnnotationQueueObjectType.OBSERVATION,
+ )
+ .map((item) => item.objectId);
- const traceIds =
- observationIds.length > 0
- ? await getTraceIdsForObservations(
- input.projectId,
- observationIds,
- )
- : [];
+ const traceIds =
+ observationIds.length > 0
+ ? await getTraceIdsForObservations(input.projectId, observationIds)
+ : [];
- return {
- queueItems: queueItems.map((item) => ({
- ...item,
- parentTraceId:
- traceIds.find((t) => t.id === item.objectId)?.traceId || null,
- })),
- totalItems,
- };
- },
- });
+ return {
+ queueItems: queueItems.map((item) => ({
+ ...item,
+ parentTraceId:
+ traceIds.find((t) => t.id === item.objectId)?.traceId || null,
+ })),
+ totalItems,
+ };
} catch (error) {
logger.error(error);
if (error instanceof TRPCError) {
diff --git a/web/src/ee/features/annotation-queues/server/annotationQueues.ts b/web/src/ee/features/annotation-queues/server/annotationQueues.ts
index 0f600df5f4..81abd1f0a3 100644
--- a/web/src/ee/features/annotation-queues/server/annotationQueues.ts
+++ b/web/src/ee/features/annotation-queues/server/annotationQueues.ts
@@ -5,7 +5,6 @@ import {
createTRPCRouter,
protectedProjectProcedure,
} from "@/src/server/api/trpc";
-import { measureAndReturnApi } from "@/src/server/utils/checkClickhouseAccess";
import {
AnnotationQueueObjectType,
AnnotationQueueStatus,
@@ -530,38 +529,14 @@ export const queueRouter = createTRPCRouter({
};
if (item.objectType === AnnotationQueueObjectType.OBSERVATION) {
- await measureAndReturnApi({
- input: { projectId: input.projectId, queryClickhouse: false },
- operation: "fetchAndLockNext",
- user: ctx.session.user,
- pgExecution: async () => {
- const observation = await ctx.prisma.observation.findUnique({
- where: {
- id: item.objectId,
- projectId: input.projectId,
- },
- select: {
- id: true,
- traceId: true,
- },
- });
-
- return {
- ...inflatedUpdatedItem,
- parentTraceId: observation?.traceId,
- };
- },
- clickhouseExecution: async () => {
- const clickhouseObservation = await getObservationById(
- item.objectId,
- input.projectId,
- );
- return {
- ...inflatedUpdatedItem,
- parentTraceId: clickhouseObservation?.traceId,
- };
- },
- });
+ const clickhouseObservation = await getObservationById(
+ item.objectId,
+ input.projectId,
+ );
+ return {
+ ...inflatedUpdatedItem,
+ parentTraceId: clickhouseObservation?.traceId,
+ };
}
return inflatedUpdatedItem;
diff --git a/web/src/ee/features/evals/server/router.ts b/web/src/ee/features/evals/server/router.ts
index 87c0b736f5..0d561b90de 100644
--- a/web/src/ee/features/evals/server/router.ts
+++ b/web/src/ee/features/evals/server/router.ts
@@ -30,7 +30,6 @@ import { EvalReferencedEvaluators } from "@/src/ee/features/evals/types";
import { EvaluatorStatus } from "../types";
import { traceException } from "@langfuse/shared/src/server";
import { isNotNullOrUndefined } from "@/src/utils/types";
-import { measureAndReturnApi } from "@/src/server/utils/checkClickhouseAccess";
const APIEvaluatorSchema = z.object({
id: z.string(),
@@ -730,22 +729,7 @@ export const evalRouter = createTRPCRouter({
const scores =
scoreIds.length > 0
- ? await measureAndReturnApi({
- input: { projectId: input.projectId, queryClickhouse: false },
- operation: "get-scores-eval-log",
- user: ctx.session.user,
- pgExecution: async () => {
- return await ctx.prisma.score.findMany({
- where: {
- projectId: input.projectId,
- id: { in: scoreIds },
- },
- });
- },
- clickhouseExecution: async () => {
- return await getScoresByIds(input.projectId, scoreIds);
- },
- })
+ ? await getScoresByIds(input.projectId, scoreIds)
: [];
return {
diff --git a/web/src/features/datasets/server/dataset-router.ts b/web/src/features/datasets/server/dataset-router.ts
index a45e50f670..a38a3793cd 100644
--- a/web/src/features/datasets/server/dataset-router.ts
+++ b/web/src/features/datasets/server/dataset-router.ts
@@ -4,23 +4,11 @@ import {
createTRPCRouter,
protectedProjectProcedure,
} from "@/src/server/api/trpc";
-import {
- type DatasetRuns,
- Prisma,
- type Dataset,
-} from "@langfuse/shared/src/db";
+import { Prisma, type Dataset } from "@langfuse/shared/src/db";
import { throwIfNoProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
import { auditLog } from "@/src/features/audit-logs/auditLog";
import { DB } from "@/src/server/db";
-import {
- type PrismaClient,
- type ScoreAggregate,
- type ScoreSimplified,
- filterAndValidateDbScoreList,
- paginationZod,
-} from "@langfuse/shared";
-import { aggregateScores } from "@/src/features/scores/lib/aggregateScores";
-import { measureAndReturnApi } from "@/src/server/utils/checkClickhouseAccess";
+import { paginationZod } from "@langfuse/shared";
import {
createDatasetRunsTable,
createDatasetRunsTableWithoutMetrics,
@@ -28,7 +16,6 @@ import {
fetchDatasetItems,
getRunItemsByRunIdOrItemId,
} from "@/src/features/datasets/server/service";
-import { traceException } from "@langfuse/shared/src/server";
export const datasetRouter = createTRPCRouter({
allDatasetMeta: protectedProjectProcedure
@@ -163,64 +150,42 @@ export const datasetRouter = createTRPCRouter({
runsByDatasetId: protectedProjectProcedure
.input(datasetRunsTableSchema)
.query(async ({ input, ctx }) => {
- return await measureAndReturnApi({
- input,
- operation: "datasets.runsByDatasetId",
- user: ctx.session.user,
- pgExecution: async () => {
- return await runsByDatasetIdPg(ctx.prisma, input);
- },
- clickhouseExecution: async () => {
- // we cannot easily join all the tracing data with the dataset run items
- // hence, we pull the trace_ids and observation_ids separately for all run items
- // afterwards, we aggregate them per run
-
- const runs = await createDatasetRunsTableWithoutMetrics(input);
-
- const totalRuns = await ctx.prisma.datasetRuns.count({
- where: {
- datasetId: input.datasetId,
- projectId: input.projectId,
- },
- });
+ // we cannot easily join all the tracing data with the dataset run items
+ // hence, we pull the trace_ids and observation_ids separately for all run items
+ // afterwards, we aggregate them per run
+ const runs = await createDatasetRunsTableWithoutMetrics(input);
- return {
- totalRuns,
- runs,
- };
+ const totalRuns = await ctx.prisma.datasetRuns.count({
+ where: {
+ datasetId: input.datasetId,
+ projectId: input.projectId,
},
});
+
+ return {
+ totalRuns,
+ runs,
+ };
}),
runsByDatasetIdMetrics: protectedProjectProcedure
.input(datasetRunsTableSchema)
.query(async ({ input, ctx }) => {
- return await measureAndReturnApi({
- input,
- operation: "datasets.runsByDatasetId",
- user: ctx.session.user,
- pgExecution: async () => {
- return await runsByDatasetIdPg(ctx.prisma, input);
- },
- clickhouseExecution: async () => {
- // we cannot easily join all the tracing data with the dataset run items
- // hence, we pull the trace_ids and observation_ids separately for all run items
- // afterwards, we aggregate them per run
-
- const runs = await createDatasetRunsTable(input);
+ // we cannot easily join all the tracing data with the dataset run items
+ // hence, we pull the trace_ids and observation_ids separately for all run items
+ // afterwards, we aggregate them per run
+ const runs = await createDatasetRunsTable(input);
- const totalRuns = await ctx.prisma.datasetRuns.count({
- where: {
- datasetId: input.datasetId,
- projectId: input.projectId,
- },
- });
-
- return {
- totalRuns,
- runs,
- };
+ const totalRuns = await ctx.prisma.datasetRuns.count({
+ where: {
+ datasetId: input.datasetId,
+ projectId: input.projectId,
},
});
+
+ return {
+ totalRuns,
+ runs,
+ };
}),
itemById: protectedProjectProcedure
.input(
@@ -686,107 +651,11 @@ export const datasetRouter = createTRPCRouter({
},
});
- return await measureAndReturnApi({
- input,
- operation: "datasets.runitemsByRunIdOrItemId",
- user: ctx.session.user,
- pgExecution: async () => {
- const traceScores = await ctx.prisma.score.findMany({
- where: {
- projectId: ctx.session.projectId,
- traceId: {
- in: runItems.map((ri) => ri.traceId),
- },
- },
- });
-
- const observations = await ctx.prisma.observationView.findMany({
- where: {
- id: {
- in: runItems
- .map((ri) => ri.observationId)
- .filter(Boolean) as string[],
- },
- projectId: ctx.session.projectId,
- },
- select: {
- id: true,
- latency: true,
- calculatedTotalCost: true,
- },
- });
-
- // Directly access 'traces' table and calculate duration via lateral join
- // Previously used 'traces_view' was not performant enough
- const traceIdsSQL = Prisma.sql`ARRAY[${Prisma.join(runItems.map((ri) => ri.traceId))}]`;
- const traces = await ctx.prisma.$queryRaw<
- {
- id: string;
- duration: number;
- totalCost: number;
- }[]
- >(
- Prisma.sql`
- SELECT
- t.id,
- o.duration,
- o.total_cost as "totalCost"
- FROM
- traces t
- LEFT JOIN LATERAL (
- SELECT
- EXTRACT(epoch FROM COALESCE(max(o1.end_time), max(o1.start_time)))::double precision - EXTRACT(epoch FROM min(o1.start_time))::double precision AS duration,
- SUM(COALESCE(o1.calculated_total_cost, 0))::double precision AS total_cost
- FROM
- -- Use observations_view as cost are not backfilled for self-hosters. Once V3 is migration is done, we can use observations instead
- observations_view o1
- WHERE
- o1.project_id = ${input.projectId}
- AND o1.trace_id = t.id
- GROUP BY
- o1.project_id,
- o1.trace_id) o ON TRUE
- WHERE
- t.project_id = ${input.projectId}
- AND t.id = ANY(${traceIdsSQL})
- `,
- );
-
- const validatedTraceScores = filterAndValidateDbScoreList(
- traceScores,
- traceException,
- );
-
- const items = runItems.map((ri) => {
- return {
- id: ri.id,
- createdAt: ri.createdAt,
- datasetItemId: ri.datasetItemId,
- observation: observations.find((o) => o.id === ri.observationId),
- trace: traces.find((t) => t.id === ri.traceId),
- scores: aggregateScores(
- validatedTraceScores.filter((s) => s.traceId === ri.traceId),
- ),
- };
- });
-
- // Note: We early return in case of no run items, when adding parameters here, make sure to update the early return above
- return {
- totalRunItems,
- runItems: items,
- };
- },
- clickhouseExecution: async () => {
- // Note: We early return in case of no run items, when adding parameters here, make sure to update the early return above
- return {
- totalRunItems,
- runItems: await getRunItemsByRunIdOrItemId(
- input.projectId,
- runItems,
- ),
- };
- },
- });
+ // Note: We early return in case of no run items, when adding parameters here, make sure to update the early return above
+ return {
+ totalRunItems,
+ runItems: await getRunItemsByRunIdOrItemId(input.projectId, runItems),
+ };
}),
datasetItemsBasedOnTraceOrObservation: protectedProjectProcedure
.input(
@@ -851,161 +720,3 @@ export const datasetRouter = createTRPCRouter({
return deletedDatasetRun;
}),
});
-
-async function runsByDatasetIdPg(
- prisma: PrismaClient,
- input: {
- projectId: string;
- datasetId: string;
- queryClickhouse: boolean;
- page?: number;
- limit?: number;
- runIds?: string[];
- },
-) {
- const scoresByRunId = await prisma.$queryRaw<
- Array<{ scores: Array<ScoreSimplified>; runId: string }>
- >(Prisma.sql`
- SELECT
- runs.id "runId",
- array_agg(s.score) AS "scores"
- FROM
- dataset_runs runs
- JOIN datasets ON datasets.id = runs.dataset_id AND datasets.project_id = ${input.projectId}
- LEFT JOIN LATERAL (
- SELECT
- jsonb_build_object ('name', s.name, 'stringValue', s.string_value, 'value', s.value, 'source', s."source", 'dataType', s.data_type, 'comment', s.comment) AS "score"
- FROM
- dataset_run_items ri
- JOIN scores s
- ON s.trace_id = ri.trace_id
- AND (ri.observation_id IS NULL OR s.observation_id = ri.observation_id)
- AND s.project_id = ${input.projectId}
- JOIN traces t ON t.id = s.trace_id AND t.project_id = ${input.projectId}
- WHERE
- ri.project_id = ${input.projectId}
- AND ri.dataset_run_id = runs.id
- ) s ON true
- WHERE
- runs.dataset_id = ${input.datasetId}
- AND runs.project_id = ${input.projectId}
- AND s.score IS NOT NULL
- ${input.runIds ? Prisma.sql`AND runs.id IN (${Prisma.join(input.runIds)})` : Prisma.empty}
- GROUP BY
- runs.id
- ${input.limit ? Prisma.sql`LIMIT ${input.limit}` : Prisma.empty}
- ${input.page && input.limit ? Prisma.sql`OFFSET ${input.page * input.limit}` : Prisma.empty}
- `);
-
- const runs = await prisma.$queryRaw<
- Array<
- DatasetRuns & {
- avgLatency: number | undefined;
- avgTotalCost: Prisma.Decimal | undefined;
- countRunItems: number;
- }
- >
- >(Prisma.sql`
- SELECT
- runs.id,
- runs.name,
- runs.description,
- runs.metadata,
- runs.created_at "createdAt",
- runs.updated_at "updatedAt",
- COALESCE(o_latency_and_total_cost. "o_avgLatency", t_latency_and_total_cost."t_avgLatency", 0) "avgLatency",
- COALESCE(o_latency_and_total_cost. "o_avgTotalCost", t_latency_and_total_cost."t_avgTotalCost", 0) "avgTotalCost",
- COALESCE(run_items_count.count, 0)::int "countRunItems"
- FROM
- dataset_runs runs
- JOIN datasets ON datasets.id = runs.dataset_id
- AND datasets.project_id = ${input.projectId}
-
- -- Add average latency and cost if a run's items are linked to observations
- -- LIMITATION: this will only work if all items for a given run are linked to either observations or traces
- -- If a run has items linked to both observations and traces, the average latency and cost will be incorrect as only those from the observations will be used
- LEFT JOIN LATERAL (
- SELECT
- AVG(o.latency) AS "o_avgLatency",
- AVG(COALESCE(o.calculated_total_cost, 0)) AS "o_avgTotalCost"
- FROM
- dataset_run_items ri
- JOIN observations_view o ON o.id = ri.observation_id
- AND o.project_id = ${input.projectId}
- WHERE
- ri.project_id = ${input.projectId}
- AND ri.dataset_run_id = runs.id) o_latency_and_total_cost ON TRUE
-
- -- Add average latency and cost if run's items are linked to traces
- LEFT JOIN LATERAL (
- -- Average across run items. One run has many items
- SELECT
- AVG(trace_latency_cost.duration) AS "t_avgLatency",
- AVG(trace_latency_cost.total_cost) AS "t_avgTotalCost"
- FROM
- dataset_run_items ri
- LEFT JOIN LATERAL (
- -- Latency and cost for a run item's trace
- SELECT
- t.id,
- o.duration,
- o.total_cost
- FROM
- traces t
- LEFT JOIN LATERAL (
- -- Latency and cost across a trace's observations
- SELECT
- EXTRACT(epoch FROM COALESCE(max(o1.end_time), max(o1.start_time)))::double precision - EXTRACT(epoch FROM min(o1.start_time))::double precision AS duration,
- SUM(COALESCE(o1.calculated_total_cost, 0)) AS total_cost
- FROM
- -- Use observations_view as cost are not backfilled for self-hosters. Once V3 is migration is done, we can use observations instead
- observations_view o1
- WHERE
- o1.project_id = ${input.projectId}
- AND o1.trace_id = t.id
- GROUP BY
- o1.project_id,
- o1.trace_id) o ON TRUE
- WHERE
- t.project_id = ${input.projectId}
- AND t.id = ri.trace_id) trace_latency_cost ON TRUE
- WHERE
- ri.project_id = ${input.projectId}
- AND ri.dataset_run_id = runs.id) t_latency_and_total_cost ON TRUE
-
- -- Add run item counts
- LEFT JOIN LATERAL (
- SELECT
- count(*) AS count
- FROM
- dataset_run_items ri
- WHERE
- ri.dataset_run_id = runs.id
- AND ri.project_id = ${input.projectId}) run_items_count ON TRUE
- WHERE
- runs.dataset_id = ${input.datasetId}
- AND runs.project_id = ${input.projectId}
- ${input.runIds ? Prisma.sql`AND runs.id IN (${Prisma.join(input.runIds)})` : Prisma.empty}
- ORDER BY
- runs.created_at DESC
- ${input.limit ? Prisma.sql`LIMIT ${input.limit}` : Prisma.empty}
- ${input.page && input.limit ? Prisma.sql`OFFSET ${input.page * input.limit}` : Prisma.empty}
- `);
-
- const totalRuns = await prisma.datasetRuns.count({
- where: {
- datasetId: input.datasetId,
- projectId: input.projectId,
- },
- });
-
- return {
- totalRuns,
- runs: runs.map((run) => ({
- ...run,
- scores: aggregateScores(
- scoresByRunId.flatMap((s) => (s.runId === run.id ? s.scores : [])),
- ) as ScoreAggregate | undefined,
- })),
- };
-}
diff --git a/web/src/features/datasets/server/service.ts b/web/src/features/datasets/server/service.ts
index 7fb994751f..7605253b58 100644
--- a/web/src/features/datasets/server/service.ts
+++ b/web/src/features/datasets/server/service.ts
@@ -25,7 +25,6 @@ import {
} from "@langfuse/shared/src/server";
import { aggregateScores } from "@/src/features/scores/lib/aggregateScores";
import Decimal from "decimal.js";
-import { measureAndReturnApi } from "@/src/server/utils/checkClickhouseAccess";
import { env } from "@/src/env.mjs";
export const datasetRunsTableSchema = z.object({
@@ -71,8 +70,8 @@ export const createDatasetRunsTableWithoutMetrics = async (
createdAt: run.run_created_at,
updatedAt: run.run_updated_at,
// return metric fields as undefined
- avgTotalCost: undefined,
- avgLatency: undefined,
+ avgTotalCost: undefined as Decimal | undefined,
+ avgLatency: undefined as number | undefined,
scores: undefined,
}));
};
@@ -187,8 +186,6 @@ export const createTempTableInClickhouse = async (
)
ENGINE = ${env.CLICKHOUSE_CLUSTER_ENABLED === "true" ? "ReplicatedMergeTree()" : "MergeTree()"}
PRIMARY KEY (project_id, dataset_id, run_id, trace_id)
-
-
`;
await commandClickhouse({
query,
@@ -425,65 +422,27 @@ export const fetchDatasetItems = async (input: DatasetRunItemsTableInput) => {
});
// check in clickhouse if the traces already exist. They arrive delayed.
- const tracingData = await measureAndReturnApi({
- input: { queryClickhouse: false, projectId: input.projectId },
- operation: "datasets.itemsByDatasetId",
- user: null,
- pgExecution: async () => {
- const traces = await input.prisma.trace.findMany({
- where: {
- id: {
- in: datasetItems
- .map((item) => item.sourceTraceId)
- .filter((id): id is string => Boolean(id)),
- },
- projectId: input.projectId,
- },
- });
-
- const observations = await input.prisma.observation.findMany({
- where: {
- id: {
- in: datasetItems
- .map((item) => item.sourceObservationId)
- .filter((id): id is string => Boolean(id)),
- },
- projectId: input.projectId,
- },
- });
-
- return {
- traceIds: traces.map((t) => t.id),
- observationIds: observations.map((o) => ({
- id: o.id,
- traceId: o.traceId,
- })),
- };
- },
- clickhouseExecution: async () => {
- const traces = await getTracesByIds(
- datasetItems
- .map((item) => item.sourceTraceId)
- .filter((id): id is string => Boolean(id)),
- input.projectId,
- );
+ const traces = await getTracesByIds(
+ datasetItems
+ .map((item) => item.sourceTraceId)
+ .filter((id): id is string => Boolean(id)),
+ input.projectId,
+ );
- const observations = await getObservationsById(
- datasetItems
- .map((item) => item.sourceObservationId)
- .filter((id): id is string => Boolean(id)),
- input.projectId,
- );
+ const observations = await getObservationsById(
+ datasetItems
+ .map((item) => item.sourceObservationId)
+ .filter((id): id is string => Boolean(id)),
+ input.projectId,
+ );
- return {
- traceIds: traces.map((t) => t.id),
- observationIds: observations.map((o) => ({
- id: o.id,
- traceId: o.traceId,
- })),
- };
- },
- });
+ const tracingData = {
+ traceIds: traces.map((t) => t.id),
+ observationIds: observations.map((o) => ({
+ id: o.id,
+ traceId: o.traceId,
+ })),
+ };
return {
totalDatasetItems,
diff --git a/web/src/features/prompts/server/routers/promptRouter.ts b/web/src/features/prompts/server/routers/promptRouter.ts
index 0110ca6480..a19188c7ae 100644
--- a/web/src/features/prompts/server/routers/promptRouter.ts
+++ b/web/src/features/prompts/server/routers/promptRouter.ts
@@ -12,7 +12,6 @@ import {
} from "@/src/server/api/trpc";
import { type Prompt, Prisma } from "@langfuse/shared/src/db";
import { createPrompt } from "../actions/createPrompt";
-import { type ScoreSimplified } from "@langfuse/shared";
import { promptsTableCols } from "@/src/server/api/definitions/promptsTable";
import { optionalPaginationZod, paginationZod } from "@langfuse/shared";
import { orderBy, singleFilter } from "@langfuse/shared";
@@ -28,7 +27,6 @@ import {
getAggregatedScoresForPrompts,
} from "@langfuse/shared/src/server";
import { aggregateScores } from "@/src/features/scores/lib/aggregateScores";
-import { measureAndReturnApi } from "@/src/server/utils/checkClickhouseAccess";
const PromptFilterOptions = z.object({
projectId: z.string(), // Required for protectedProjectProcedure
@@ -107,63 +105,16 @@ export const promptRouter = createTRPCRouter({
queryClickhouse: z.boolean().default(false),
}),
)
- .query(async ({ input, ctx }) => {
+ .query(async ({ input }) => {
if (input.promptNames.length === 0) return [];
-
- return await measureAndReturnApi({
- input,
- operation: "prompts.metrics",
- user: ctx.session.user,
- pgExecution: async () => {
- const promptCounts = await ctx.prisma.$queryRaw<
- {
- promptName: string;
- observationCount: bigint;
- }[]
- >(
- Prisma.sql`
- WITH prompt_ids AS (
- SELECT
- p.id,
- p.name
- FROM
- prompts p
- WHERE
- p.project_id = ${input.projectId}
- AND p.name IN (${Prisma.join(input.promptNames)})
- )
- SELECT
- p.name AS "promptName", SUM(oc.observation_count) AS "observationCount"
- FROM
- prompt_ids p
- LEFT JOIN LATERAL (
- SELECT
- COUNT(*) AS observation_count
- FROM
- observations o
- WHERE
- o.project_id = ${input.projectId}
- AND o.prompt_id = p.id) oc ON TRUE
- GROUP BY
- p.name
- `,
- );
- return promptCounts.map(({ promptName, observationCount }) => ({
- promptName,
- observationCount: Number(observationCount),
- }));
- },
- clickhouseExecution: async () => {
- const res = await getObservationsWithPromptName(
- input.projectId,
- input.promptNames,
- );
- return res.map(({ promptName, count }) => ({
- promptName,
- observationCount: count,
- }));
- },
- });
+ const res = await getObservationsWithPromptName(
+ input.projectId,
+ input.promptNames,
+ );
+ return res.map(({ promptName, count }) => ({
+ promptName,
+ observationCount: count,
+ }));
}),
byId: protectedProjectProcedure
.input(
@@ -708,171 +659,34 @@ export const promptRouter = createTRPCRouter({
scope: "prompts:read",
});
- return await measureAndReturnApi({
- input,
- operation: "prompts.versionMetrics",
- user: ctx.session.user,
- pgExecution: async () => {
- if (input.promptIds.length === 0) return [];
- const [metrics, generationScores, traceScores] = await Promise.all([
- // metrics
- ctx.prisma.$queryRaw<
- Array<{
- id: string;
- observationCount: bigint;
- firstUsed: Date | null;
- lastUsed: Date | null;
- medianOutputTokens: number | null;
- medianInputTokens: number | null;
- medianTotalCost: number | null;
- medianLatency: number | null;
- }>
- >(
- Prisma.sql`
- select p.id, p.version, observation_metrics.* from prompts p
- LEFT JOIN LATERAL (
- SELECT
- count(*) AS "observationCount",
- MIN(o.start_time) AS "firstUsed",
- MAX(o.start_time) AS "lastUsed",
- PERCENTILE_CONT(0.5) WITHIN GROUP(ORDER BY o.completion_tokens) AS "medianOutputTokens",
- PERCENTILE_CONT(0.5) WITHIN GROUP(ORDER BY o.prompt_tokens) AS "medianInputTokens",
- PERCENTILE_CONT(0.5) WITHIN GROUP(ORDER BY o.calculated_total_cost) AS "medianTotalCost",
- PERCENTILE_CONT(0.5) WITHIN GROUP(ORDER BY o.latency) AS "medianLatency"
- FROM
- "observations_view" o
- WHERE
- o.prompt_id = p.id
- AND "type" = 'GENERATION'
- AND "project_id" = ${input.projectId}
- ) AS observation_metrics ON true
- WHERE "project_id" = ${input.projectId}
- AND p.id in (${Prisma.join(input.promptIds)})
- ORDER BY version DESC
- `,
- ),
- // generationScores
- ctx.prisma.$queryRaw<
- Array<{
- promptId: string;
- scores: Array<ScoreSimplified>;
- }>
- >(Prisma.sql`
- SELECT
- p.id AS "promptId",
- array_agg(s.score) AS "scores"
- FROM
- prompts p
- LEFT JOIN LATERAL (
- SELECT
- jsonb_build_object ('name', s.name, 'stringValue', s.string_value, 'value', s.value, 'source', s."source", 'dataType', s.data_type, 'comment', s.comment) AS "score"
- FROM
- observations AS o
- LEFT JOIN scores s ON o.trace_id = s.trace_id
- AND s.observation_id = o.id
- AND s.project_id = ${input.projectId}
- WHERE
- o.prompt_id IS NOT NULL
- AND o.type = 'GENERATION'
- AND o.prompt_id = p.id
- AND o.project_id = ${input.projectId}
- AND s.name IS NOT NULL
- AND p.id IN (${Prisma.join(input.promptIds)})
- ) s ON TRUE
- WHERE
- p.project_id = ${input.projectId}
- AND s.score IS NOT NULL
- GROUP BY
- p.id
- `),
- // traceScores
- ctx.prisma.$queryRaw<
- Array<{
- promptId: string;
- scores: Array<ScoreSimplified>;
- }>
- >(Prisma.sql`
- SELECT
- p.id AS "promptId",
- array_agg(s.score) AS "scores"
- FROM
- prompts p
- LEFT JOIN LATERAL (
- SELECT
- jsonb_build_object ('name', s.name, 'stringValue', s.string_value, 'value', s.value, 'source', s."source", 'dataType', s.data_type, 'comment', s.comment) AS "score"
- FROM
- scores s
- WHERE
- s.trace_id IN (
- SELECT o.trace_id
- FROM observations o
- WHERE
- o.prompt_id IS NOT NULL
- AND o.prompt_id = p.id
- AND o.type = 'GENERATION'
- AND o.project_id = ${input.projectId}
- AND o.prompt_id IN (${Prisma.join(input.promptIds)})
- )
- AND s.observation_id IS NULL
- AND s.project_id = ${input.projectId}
- ) s ON TRUE
- WHERE
- p.project_id = ${input.projectId}
- AND s.score IS NOT NULL
- GROUP BY
- p.id
- `),
- ]);
-
- return metrics.map((metric) => ({
- ...metric,
- observationScores: aggregateScores(
- generationScores.find((score) => score.promptId === metric.id)
- ?.scores ?? [],
- ),
- traceScores: aggregateScores(
- traceScores.find((score) => score.promptId === metric.id)
- ?.scores ?? [],
- ),
- }));
- },
- clickhouseExecution: async () => {
- console.log("clickhouseExecution", input.promptIds);
- const [observations, observationScores, traceScores] =
- await Promise.all([
- getObservationMetricsForPrompts(input.projectId, input.promptIds),
- getScoresForPromptIds(
- input.projectId,
- input.promptIds,
- "observation",
- ),
- getScoresForPromptIds(input.projectId, input.promptIds, "trace"),
- ]);
-
- return observations.map((r) => {
- const promptObservationScores = observationScores.find(
- (score) => score.promptId === r.promptId,
- );
- const promptTraceScores = traceScores.find(
- (score) => score.promptId === r.promptId,
- );
+ const [observations, observationScores, traceScores] = await Promise.all([
+ getObservationMetricsForPrompts(input.projectId, input.promptIds),
+ getScoresForPromptIds(input.projectId, input.promptIds, "observation"),
+ getScoresForPromptIds(input.projectId, input.promptIds, "trace"),
+ ]);
- return {
- id: r.promptId,
- observationCount: BigInt(r.count),
- firstUsed: r.firstObservation,
- lastUsed: r.lastObservation,
- medianOutputTokens: r.medianOutputUsage,
- medianInputTokens: r.medianInputUsage,
- medianTotalCost: r.medianTotalCost,
- medianLatency: r.medianLatencyMs,
- observationScores: aggregateScores(
- promptObservationScores?.scores ?? [],
- ),
- traceScores: aggregateScores(promptTraceScores?.scores ?? []),
- };
- });
- },
+ return observations.map((r) => {
+ const promptObservationScores = observationScores.find(
+ (score) => score.promptId === r.promptId,
+ );
+ const promptTraceScores = traceScores.find(
+ (score) => score.promptId === r.promptId,
+ );
+
+ return {
+ id: r.promptId,
+ observationCount: BigInt(r.count),
+ firstUsed: r.firstObservation,
+ lastUsed: r.lastObservation,
+ medianOutputTokens: r.medianOutputUsage,
+ medianInputTokens: r.medianInputUsage,
+ medianTotalCost: r.medianTotalCost,
+ medianLatency: r.medianLatencyMs,
+ observationScores: aggregateScores(
+ promptObservationScores?.scores ?? [],
+ ),
+ traceScores: aggregateScores(promptTraceScores?.scores ?? []),
+ };
});
}),
});
diff --git a/web/src/pages/api/public/metrics/daily.ts b/web/src/pages/api/public/metrics/daily.ts
index c2fc7ba25a..18b26da93f 100644
--- a/web/src/pages/api/public/metrics/daily.ts
+++ b/web/src/pages/api/public/metrics/daily.ts
@@ -1,13 +1,9 @@
-import { Prisma, prisma } from "@langfuse/shared/src/db";
import {
GetMetricsDailyV1Query,
GetMetricsDailyV1Response,
} from "@/src/features/public-api/types/metrics";
import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";
import { createAuthedAPIRoute } from "@/src/features/public-api/server/createAuthedAPIRoute";
-import { type z } from "zod";
-import { env } from "@/src/env.mjs";
-import { measureAndReturnApi } from "@/src/server/utils/checkClickhouseAccess";
import {
generateDailyMetrics,
getDailyMetricsCount,
@@ -20,162 +16,32 @@ export default withMiddlewares({
responseSchema: GetMetricsDailyV1Response,
rateLimitResource: "public-api-metrics",
fn: async ({ query, auth }) => {
- return measureAndReturnApi({
- input: { projectId: auth.scope.projectId, queryClickhouse: false },
- operation: "api/public/metrics/daily",
- user: null,
- pgExecution: async () => {
- const traceNameCondition = query.traceName
- ? Prisma.sql`AND t.name = ${query.traceName}`
- : Prisma.empty;
- const userCondition = query.userId
- ? Prisma.sql`AND t."user_id" = ${query.userId}`
- : Prisma.empty;
- const tagsCondition = query.tags
- ? Prisma.sql`AND ARRAY[${Prisma.join(
- (Array.isArray(query.tags)
- ? query.tags
- : query.tags.split(",")
- ).map((v) => Prisma.sql`${v}`),
- ", ",
- )}] <@ t."tags"`
- : Prisma.empty;
- const fromTimestampCondition = query.fromTimestamp
- ? Prisma.sql`AND t."timestamp" >= ${query.fromTimestamp}::timestamp with time zone at time zone 'UTC'`
- : Prisma.empty;
- const toTimestampCondition = query.toTimestamp
- ? Prisma.sql`AND t."timestamp" < ${query.toTimestamp}::timestamp with time zone at time zone 'UTC'`
- : Prisma.empty;
- const fromObservationStartTimeCondition = query.fromTimestamp
- ? Prisma.sql`AND o."start_time" >= ${query.fromTimestamp}::timestamp with time zone at time zone 'UTC' - INTERVAL '1 day'`
- : Prisma.empty;
- const toObservationStartTimeCondition = query.toTimestamp
- ? Prisma.sql`AND o."start_time" < ${query.toTimestamp}::timestamp with time zone at time zone 'UTC' + INTERVAL '1 day'`
- : Prisma.empty;
+ const filterProps = {
+ projectId: auth.scope.projectId,
+ page: query.page ?? undefined,
+ limit: query.limit ?? undefined,
+ traceName: query.traceName ?? undefined,
+ userId: query.userId ?? undefined,
+ tags: query.tags ?? undefined,
+ fromTimestamp: query.fromTimestamp ?? undefined,
+ toTimestamp: query.toTimestamp ?? undefined,
+ };
- // TODO: We can use observations as soon as we compute costs on write and backfill self-hosters
- const observationtable =
- env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION === undefined
- ? Prisma.sql`observations_view`
- : Prisma.sql`observations`;
+ const [usage, count] = await Promise.all([
+ generateDailyMetrics(filterProps),
+ getDailyMetricsCount(filterProps),
+ ]);
- const [usage, totalItemsRes] = await Promise.all([
- prisma.$queryRaw`
- WITH model_usage AS (
- SELECT DATE_TRUNC('DAY', o.start_time) "date",
- o.model,
- count(o.id)::integer as "countObservations",
- count(distinct t.id)::integer as "countTraces",
- SUM(o.prompt_tokens) "inputUsage",
- SUM(o.completion_tokens) "outputUsage",
- SUM(o.total_tokens) "totalUsage",
- COALESCE(SUM(o.calculated_total_cost), 0)::DOUBLE PRECISION as "totalCost"
- FROM traces t
- LEFT JOIN ${observationtable} o
- ON o.trace_id = t.id
- AND o.project_id = t.project_id
- WHERE o.start_time IS NOT NULL
- AND t.project_id = ${auth.scope.projectId}
- ${traceNameCondition}
- ${userCondition}
- ${tagsCondition}
- ${fromTimestampCondition}
- ${toTimestampCondition}
- ${fromObservationStartTimeCondition}
- ${toObservationStartTimeCondition}
- GROUP BY 1, 2),
- daily_model_usage AS (
- SELECT "date",
- sum("countObservations")::integer "countObservations",
- sum("totalCost")::DOUBLE PRECISION "totalCost",
- json_agg(json_build_object(
- 'model', "model",
- 'inputUsage', "inputUsage",
- 'outputUsage', "outputUsage",
- 'totalUsage', "totalUsage",
- 'totalCost', "totalCost",
- 'countObservations', "countObservations",
- 'countTraces', "countTraces"
- )) daily_usage_json
- FROM model_usage
- GROUP BY 1),
- trace_usage AS (
- SELECT DATE_TRUNC('DAY', t.timestamp) "date",
- count(t.id)::integer as "countTraces"
- FROM traces t
- WHERE t.project_id = ${auth.scope.projectId}
- ${traceNameCondition}
- ${userCondition}
- ${tagsCondition}
- ${fromTimestampCondition}
- ${toTimestampCondition}
- GROUP BY 1)
-
- SELECT TO_CHAR(COALESCE(trace_usage.date, daily_model_usage.date), 'YYYY-MM-DD') AS "date",
- COALESCE(trace_usage."countTraces", 0) "countTraces",
- COALESCE("countObservations", 0) "countObservations",
- COALESCE("totalCost", 0) "totalCost",
- COALESCE(daily_usage_json, '[]'::JSON) usage
- FROM daily_model_usage
- FULL OUTER JOIN trace_usage
- ON daily_model_usage."date" = trace_usage."date"
- ORDER BY 1 DESC
- LIMIT ${query.limit} OFFSET ${(query.page - 1) * query.limit}
- `,
- prisma.$queryRaw<{ count: number }[]>`
- SELECT COUNT(DISTINCT DATE_TRUNC('DAY', t.timestamp))::integer
- FROM traces t
- WHERE t.project_id = ${auth.scope.projectId}
- ${traceNameCondition}
- ${userCondition}
- ${tagsCondition}
- ${fromTimestampCondition}
- ${toTimestampCondition}
- `,
- ]);
-
- const totalItems = totalItemsRes[0]?.count ?? 0;
-
- return {
- // cannot use type warnings due to query raw, covered by tests
- data: usage as z.infer<typeof GetMetricsDailyV1Response>["data"],
- meta: {
- page: query.page,
- limit: query.limit,
- totalItems,
- totalPages: Math.ceil(totalItems / query.limit),
- },
- };
- },
- clickhouseExecution: async () => {
- const filterProps = {
- projectId: auth.scope.projectId,
- page: query.page ?? undefined,
- limit: query.limit ?? undefined,
- traceName: query.traceName ?? undefined,
- userId: query.userId ?? undefined,
- tags: query.tags ?? undefined,
- fromTimestamp: query.fromTimestamp ?? undefined,
- toTimestamp: query.toTimestamp ?? undefined,
- };
-
- const [usage, count] = await Promise.all([
- generateDailyMetrics(filterProps),
- getDailyMetricsCount(filterProps),
- ]);
-
- const finalCount = count || 0;
- return {
- data: usage,
- meta: {
- page: query.page,
- limit: query.limit,
- totalItems: finalCount,
- totalPages: Math.ceil(finalCount / query.limit),
- },
- };
+ const finalCount = count || 0;
+ return {
+ data: usage,
+ meta: {
+ page: query.page,
+ limit: query.limit,
+ totalItems: finalCount,
+ totalPages: Math.ceil(finalCount / query.limit),
},
- });
+ };
},
}),
});
diff --git a/web/src/pages/api/public/observations/[observationId].ts b/web/src/pages/api/public/observations/[observationId].ts
index de36c39112..bc269935fd 100644
--- a/web/src/pages/api/public/observations/[observationId].ts
+++ b/web/src/pages/api/public/observations/[observationId].ts
@@ -7,7 +7,6 @@ import {
import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";
import { createAuthedAPIRoute } from "@/src/features/public-api/server/createAuthedAPIRoute";
import { LangfuseNotFoundError } from "@langfuse/shared";
-import { measureAndReturnApi } from "@/src/server/utils/checkClickhouseAccess";
import { getObservationViewById } from "@langfuse/shared/src/server";
export default withMiddlewares({
@@ -16,77 +15,58 @@ export default withMiddlewares({
querySchema: GetObservationV1Query,
responseSchema: GetObservationV1Response,
fn: async ({ query, auth }) => {
- const { observationId } = query;
- const observation = await measureAndReturnApi({
- input: { projectId: auth.scope.projectId, queryClickhouse: false },
- operation: "api/public/observations/[observationId]",
- user: null,
- pgExecution: async () => {
- return await prisma.observationView.findFirst({
- where: {
- id: observationId,
- projectId: auth.scope.projectId,
- },
- });
- },
- clickhouseExecution: async () => {
- const observation = await getObservationViewById(
- observationId,
- auth.scope.projectId,
- true,
- );
- if (!observation) {
- throw new LangfuseNotFoundError(
- "Observation not found within authorized project",
- );
- }
+ const clickhouseObservation = await getObservationViewById(
+ query.observationId,
+ auth.scope.projectId,
+ true,
+ );
+ if (!clickhouseObservation) {
+ throw new LangfuseNotFoundError(
+ "Observation not found within authorized project",
+ );
+ }
- const model = observation.modelId
- ? await prisma.model.findFirst({
- where: {
- AND: [
+ const model = clickhouseObservation.modelId
+ ? await prisma.model.findFirst({
+ where: {
+ AND: [
+ {
+ id: clickhouseObservation.modelId,
+ },
+ {
+ OR: [
{
- id: observation.modelId,
+ projectId: auth.scope.projectId,
},
{
- OR: [
- {
- projectId: auth.scope.projectId,
- },
- {
- projectId: null,
- },
- ],
+ projectId: null,
},
],
},
- include: {
- Price: true,
- },
- orderBy: {
- projectId: {
- sort: "desc",
- nulls: "last",
- },
- },
- })
- : undefined;
-
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ ],
+ },
+ include: {
+ Price: true,
+ },
+ orderBy: {
+ projectId: {
+ sort: "desc",
+ nulls: "last",
+ },
+ },
+ })
+ : undefined;
- return {
- ...observation,
- 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,
- };
- },
- });
+ const observation = {
+ ...clickhouseObservation,
+ 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,
+ };
if (!observation) {
throw new LangfuseNotFoundError(
diff --git a/web/src/pages/api/public/observations/index.ts b/web/src/pages/api/public/observations/index.ts
index 1a4243ea4f..dbc37c64a9 100644
--- a/web/src/pages/api/public/observations/index.ts
+++ b/web/src/pages/api/public/observations/index.ts
@@ -2,15 +2,12 @@ import { prisma } from "@langfuse/shared/src/db";
import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";
import { createAuthedAPIRoute } from "@/src/features/public-api/server/createAuthedAPIRoute";
-import { Prisma, type ObservationView } from "@langfuse/shared/src/db";
-import { InternalServerError } from "@langfuse/shared";
import {
GetObservationsV1Query,
GetObservationsV1Response,
transformDbToApiObservation,
} from "@/src/features/public-api/types/observations";
-import { measureAndReturnApi } from "@/src/server/utils/checkClickhouseAccess";
import {
generateObservationsForPublicApi,
getObservationsCountForPublicApi,
@@ -22,194 +19,71 @@ export default withMiddlewares({
querySchema: GetObservationsV1Query,
responseSchema: GetObservationsV1Response,
fn: async ({ query, auth }) => {
- return await measureAndReturnApi({
- input: { projectId: auth.scope.projectId, queryClickhouse: false },
- operation: "api/public/observations",
- user: null,
- pgExecution: async () => {
- const userIdCondition = query.userId
- ? Prisma.sql`AND traces."user_id" = ${query.userId}`
- : Prisma.empty;
+ const filterProps = {
+ projectId: auth.scope.projectId,
+ page: query.page ?? undefined,
+ limit: query.limit ?? undefined,
+ traceId: query.traceId ?? undefined,
+ userId: query.userId ?? undefined,
+ name: query.name ?? undefined,
+ type: query.type ?? undefined,
+ parentObservationId: query.parentObservationId ?? undefined,
+ fromStartTime: query.fromStartTime ?? undefined,
+ toStartTime: query.toStartTime ?? undefined,
+ version: query.version ?? undefined,
+ };
+ const [items, count] = await Promise.all([
+ generateObservationsForPublicApi(filterProps),
+ getObservationsCountForPublicApi(filterProps),
+ ]);
+ const uniqueModels: string[] = Array.from(
+ new Set(
+ items.map((r) => r.modelId).filter((r): r is string => Boolean(r)),
+ ),
+ );
- const nameCondition = query.name
- ? Prisma.sql`AND o."name" = ${query.name}`
- : Prisma.empty;
+ 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;
- const observationTypeCondition = query.type
- ? Prisma.sql`AND o."type" = ${query.type}::"ObservationType"`
- : Prisma.empty;
-
- const traceIdCondition = query.traceId
- ? Prisma.sql`AND o."trace_id" = ${query.traceId}`
- : Prisma.empty;
-
- const parentObservationIdCondition = query.parentObservationId
- ? Prisma.sql`AND o."parent_observation_id" = ${query.parentObservationId}`
- : Prisma.empty;
-
- const fromStartTimeCondition = query.fromStartTime
- ? Prisma.sql`AND o."start_time" >= ${query.fromStartTime}::timestamp with time zone at time zone 'UTC'`
- : Prisma.empty;
-
- const toStartTimeCondition = query.toStartTime
- ? Prisma.sql`AND o."start_time" < ${query.toStartTime}::timestamp with time zone at time zone 'UTC'`
- : Prisma.empty;
-
- const versionCondition = query.version
- ? Prisma.sql`AND o."version" = ${query.version}`
- : Prisma.empty;
-
- const observations = await prisma.$queryRaw<ObservationView[]>`
- SELECT
- o."id",
- o."name",
- o."start_time" AS "startTime",
- o."end_time" AS "endTime",
- o."parent_observation_id" AS "parentObservationId",
- o."type",
- o."metadata",
- o."model",
- o."input",
- o."output",
- o."level",
- o."status_message" AS "statusMessage",
- o."completion_start_time" AS "completionStartTime",
- o."completion_tokens" AS "completionTokens",
- o."prompt_tokens" AS "promptTokens",
- o."total_tokens" AS "totalTokens",
- o."unit" AS "unit",
- o."version",
- o."project_id" AS "projectId",
- o."trace_id" AS "traceId",
- o."modelParameters" AS "modelParameters",
- o."model_id" as "modelId",
- o."input_price" as "inputPrice",
- o."output_price" as "outputPrice",
- o."total_price" as "totalPrice",
- o."calculated_input_cost" as "calculatedInputCost",
- o."calculated_output_cost" as "calculatedOutputCost",
- o."calculated_total_cost" as "calculatedTotalCost",
- o."latency",
- o."prompt_id" as "promptId",
- o."prompt_name" as "promptName",
- o."prompt_version" as "promptVersion",
- o."created_at" as "createdAt",
- o."updated_at" as "updatedAt",
- o."time_to_first_token" as "timeToFirstToken"
- FROM observations_view o LEFT JOIN traces ON o."trace_id" = traces."id" AND traces."project_id" = o."project_id"
- WHERE o."project_id" = ${auth.scope.projectId}
- ${nameCondition}
- ${userIdCondition}
- ${observationTypeCondition}
- ${traceIdCondition}
- ${versionCondition}
- ${parentObservationIdCondition}
- ${fromStartTimeCondition}
- ${toStartTimeCondition}
- ORDER by o."start_time" DESC
- OFFSET ${(query.page - 1) * query.limit}
- LIMIT ${query.limit}
- `;
- const countRes = await prisma.$queryRaw<{ count: bigint }[]>`
- SELECT COUNT(*) FROM observations o LEFT JOIN traces ON o."trace_id" = traces."id"
- WHERE o."project_id" = ${auth.scope.projectId}
- ${observationTypeCondition}
- ${nameCondition}
- ${userIdCondition}
- ${traceIdCondition}
- ${versionCondition}
- ${parentObservationIdCondition}
- ${fromStartTimeCondition}
- ${toStartTimeCondition}
- `;
- if (countRes.length !== 1) {
- throw new InternalServerError("Unexpected totalItems result");
- }
- const totalItems = Number(countRes[0].count);
-
- return {
- data: observations.map(transformDbToApiObservation),
- meta: {
- page: query.page,
- limit: query.limit,
- totalItems,
- totalPages: Math.ceil(totalItems / query.limit),
- },
- };
- },
- clickhouseExecution: async () => {
- const filterProps = {
- projectId: auth.scope.projectId,
- page: query.page ?? undefined,
- limit: query.limit ?? undefined,
- traceId: query.traceId ?? undefined,
- userId: query.userId ?? undefined,
- name: query.name ?? undefined,
- type: query.type ?? undefined,
- parentObservationId: query.parentObservationId ?? undefined,
- fromStartTime: query.fromStartTime ?? undefined,
- toStartTime: query.toStartTime ?? undefined,
- version: query.version ?? undefined,
- };
- const [items, count] = await Promise.all([
- generateObservationsForPublicApi(filterProps),
- getObservationsCountForPublicApi(filterProps),
- ]);
- const uniqueModels: string[] = Array.from(
- new Set(
- items
- .map((r) => r.modelId)
- .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.modelId);
- 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),
- },
- };
+ return {
+ data: items
+ .map((i) => {
+ const model = models.find((m) => m.id === i.modelId);
+ 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),
},
- });
+ };
},
}),
});
diff --git a/web/src/pages/api/public/scores/[scoreId].ts b/web/src/pages/api/public/scores/[scoreId].ts
index 8500026e47..01ffc41b4d 100644
--- a/web/src/pages/api/public/scores/[scoreId].ts
+++ b/web/src/pages/api/public/scores/[scoreId].ts
@@ -1,6 +1,5 @@
import { createAuthedAPIRoute } from "@/src/features/public-api/server/createAuthedAPIRoute";
import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";
-import { measureAndReturnApi } from "@/src/server/utils/checkClickhouseAccess";
import {
DeleteScoreQuery,
DeleteScoreResponse,
@@ -9,7 +8,6 @@ import {
InternalServerError,
LangfuseNotFoundError,
} from "@langfuse/shared";
-import { prisma } from "@langfuse/shared/src/db";
import {
deleteScore,
getScoreById,
@@ -23,24 +21,7 @@ export default withMiddlewares({
querySchema: GetScoreQuery,
responseSchema: GetScoreResponse,
fn: async ({ query, auth }) => {
- const { scoreId } = query;
-
- const score = await measureAndReturnApi({
- input: { projectId: auth.scope.projectId, queryClickhouse: false },
- operation: "api/public/scores/[scoreId]",
- user: null,
- pgExecution: async () => {
- return await prisma.score.findUnique({
- where: {
- id: scoreId,
- projectId: auth.scope.projectId,
- },
- });
- },
- clickhouseExecution: async () => {
- return await getScoreById(auth.scope.projectId, scoreId);
- },
- });
+ const score = await getScoreById(auth.scope.projectId, query.scoreId);
if (!score) {
throw new LangfuseNotFoundError("Score not found");
@@ -63,17 +44,7 @@ export default withMiddlewares({
responseSchema: DeleteScoreResponse,
fn: async ({ query, auth }) => {
const { scoreId } = query;
-
- await Promise.all([
- prisma.score.deleteMany({
- where: {
- id: scoreId,
- projectId: auth.scope.projectId,
- },
- }),
- deleteScore(auth.scope.projectId, scoreId),
- ]);
-
+ await deleteScore(auth.scope.projectId, scoreId);
return { message: "Score deleted successfully" };
},
}),
diff --git a/web/src/pages/api/public/scores/index.ts b/web/src/pages/api/public/scores/index.ts
index ef718a865b..1a43a45e26 100644
--- a/web/src/pages/api/public/scores/index.ts
+++ b/web/src/pages/api/public/scores/index.ts
@@ -9,14 +9,12 @@ import {
PostScoresBody,
PostScoresResponse,
} from "@langfuse/shared";
-import { prisma, Prisma } from "@langfuse/shared/src/db";
import {
eventTypes,
logger,
processEventBatch,
} from "@langfuse/shared/src/server";
import { tokenCount } from "@/src/features/ingest/usage";
-import { measureAndReturnApi } from "@/src/server/utils/checkClickhouseAccess";
import {
generateScoresForPublicApi,
getScoresCountForPublicApi,
@@ -57,193 +55,54 @@ export default withMiddlewares({
querySchema: GetScoresQuery,
responseSchema: GetScoresResponse,
fn: async ({ query, auth }) => {
- const {
- page,
- limit,
- configId,
- queueId,
- traceTags,
- userId,
- name,
- fromTimestamp,
- toTimestamp,
- source,
- operator,
- value,
- scoreIds,
- dataType,
- } = query;
+ const [items, count] = await Promise.all([
+ generateScoresForPublicApi({
+ projectId: auth.scope.projectId,
+ page: query.page ?? undefined,
+ limit: query.limit ?? undefined,
+ userId: query.userId ?? undefined,
+ name: query.name ?? undefined,
+ configId: query.configId ?? undefined,
+ queueId: query.queueId ?? undefined,
+ traceTags: query.traceTags ?? undefined,
+ dataType: query.dataType ?? undefined,
+ fromTimestamp: query.fromTimestamp ?? undefined,
+ toTimestamp: query.toTimestamp ?? undefined,
+ source: query.source ?? undefined,
+ value: query.value ?? undefined,
+ operator: query.operator ?? undefined,
+ scoreIds: query.scoreIds ?? undefined,
+ }),
+ getScoresCountForPublicApi({
+ projectId: auth.scope.projectId,
+ page: query.page ?? undefined,
+ limit: query.limit ?? undefined,
+ userId: query.userId ?? undefined,
+ name: query.name ?? undefined,
+ configId: query.configId ?? undefined,
+ queueId: query.queueId ?? undefined,
+ traceTags: query.traceTags ?? undefined,
+ dataType: query.dataType ?? undefined,
+ fromTimestamp: query.fromTimestamp ?? undefined,
+ toTimestamp: query.toTimestamp ?? undefined,
+ source: query.source ?? undefined,
+ value: query.value ?? undefined,
+ operator: query.operator ?? undefined,
+ scoreIds: query.scoreIds ?? undefined,
+ }),
+ ]);
- return await measureAndReturnApi({
- input: { projectId: auth.scope.projectId, queryClickhouse: false },
- operation: "api/public/scores",
- user: null,
- pgExecution: async () => {
- const skipValue = (page - 1) * limit;
- const configCondition = configId
- ? Prisma.sql`AND s."config_id" = ${configId}`
- : Prisma.empty;
- const queueCondition = queueId
- ? Prisma.sql`AND s."queue_id" = ${queueId}`
- : Prisma.empty;
- const traceTagsCondition = traceTags
- ? Prisma.sql`AND ARRAY[${Prisma.join(
- (Array.isArray(traceTags)
- ? traceTags
- : traceTags.split(",")
- ).map((v) => Prisma.sql`${v}`),
- ", ",
- )}] <@ t."tags"`
- : Prisma.empty;
- const dataTypeCondition = dataType
- ? Prisma.sql`AND s."data_type" = ${dataType}::"ScoreDataType"`
- : Prisma.empty;
- const userCondition = userId
- ? Prisma.sql`AND t."user_id" = ${userId}`
- : Prisma.empty;
- const nameCondition = name
- ? Prisma.sql`AND s."name" = ${name}`
- : Prisma.empty;
- const fromTimestampCondition = fromTimestamp
- ? Prisma.sql`AND s."timestamp" >= ${fromTimestamp}::timestamp with time zone at time zone 'UTC'`
- : Prisma.empty;
- const toTimestampCondition = toTimestamp
- ? Prisma.sql`AND s."timestamp" < ${toTimestamp}::timestamp with time zone at time zone 'UTC'`
- : Prisma.empty;
- const sourceCondition = source
- ? Prisma.sql`AND s."source" = ${source}::"ScoreSource"`
- : Prisma.empty;
- const valueCondition =
- operator && value !== null && value !== undefined
- ? Prisma.sql`AND s."value" ${Prisma.raw(`${operator}`)} ${value}`
- : Prisma.empty;
- const scoreIdCondition = scoreIds
- ? Prisma.sql`AND s."id" = ANY(${scoreIds})`
- : Prisma.empty;
+ const finalCount = count ? count : 0;
- const scores = await prisma.$queryRaw<Array<unknown>>(Prisma.sql`
- SELECT
- s.id,
- s.timestamp,
- s.name,
- s.value,
- s.string_value as "stringValue",
- s.author_user_id as "authorUserId",
- s.project_id as "projectId",
- s.created_at as "createdAt",
- s.updated_at as "updatedAt",
- s.source,
- s.comment,
- s.data_type as "dataType",
- s.config_id as "configId",
- s.queue_id as "queueId",
- s.trace_id as "traceId",
- s.observation_id as "observationId",
- json_build_object('userId', t.user_id, 'tags', t.tags) as "trace"
- FROM "scores" AS s
- LEFT JOIN "traces" AS t ON t.id = s.trace_id AND t.project_id = ${auth.scope.projectId}
- WHERE s.project_id = ${auth.scope.projectId}
- ${configCondition}
- ${queueCondition}
- ${traceTagsCondition}
- ${dataTypeCondition}
- ${userCondition}
- ${nameCondition}
- ${sourceCondition}
- ${fromTimestampCondition}
- ${toTimestampCondition}
- ${valueCondition}
- ${scoreIdCondition}
- ORDER BY s."timestamp" DESC
- LIMIT ${limit} OFFSET ${skipValue}
- `);
-
- const totalItemsRes = await prisma.$queryRaw<{ count: bigint }[]>(
- Prisma.sql`
- SELECT COUNT(*) as count
- FROM "scores" AS s
- LEFT JOIN "traces" AS t ON t.id = s.trace_id AND t.project_id = ${auth.scope.projectId}
- WHERE s.project_id = ${auth.scope.projectId}
- ${configCondition}
- ${queueCondition}
- ${traceTagsCondition}
- ${dataTypeCondition}
- ${userCondition}
- ${nameCondition}
- ${sourceCondition}
- ${fromTimestampCondition}
- ${toTimestampCondition}
- ${valueCondition}
- ${scoreIdCondition}
- `,
- );
-
- const validatedScores = legacyFilterAndValidateV1GetScoreList(scores);
-
- const totalItems =
- totalItemsRes[0] !== undefined ? Number(totalItemsRes[0].count) : 0;
-
- return {
- data: validatedScores,
- meta: {
- page: page,
- limit: limit,
- totalItems,
- totalPages: Math.ceil(totalItems / limit),
- },
- };
+ return {
+ data: legacyFilterAndValidateV1GetScoreList(items),
+ meta: {
+ page: query.page,
+ limit: query.limit,
+ totalItems: finalCount,
+ totalPages: Math.ceil(finalCount / query.limit),
},
- clickhouseExecution: async () => {
- const [items, count] = await Promise.all([
- generateScoresForPublicApi({
- projectId: auth.scope.projectId,
- page: query.page ?? undefined,
- limit: query.limit ?? undefined,
- userId: query.userId ?? undefined,
- name: query.name ?? undefined,
- configId: query.configId ?? undefined,
- queueId: query.queueId ?? undefined,
- traceTags: query.traceTags ?? undefined,
- dataType: query.dataType ?? undefined,
- fromTimestamp: query.fromTimestamp ?? undefined,
- toTimestamp: query.toTimestamp ?? undefined,
- source: query.source ?? undefined,
- value: query.value ?? undefined,
- operator: query.operator ?? undefined,
- scoreIds: query.scoreIds ?? undefined,
- }),
- getScoresCountForPublicApi({
- projectId: auth.scope.projectId,
- page: query.page ?? undefined,
- limit: query.limit ?? undefined,
- userId: query.userId ?? undefined,
- name: query.name ?? undefined,
- configId: query.configId ?? undefined,
- queueId: query.queueId ?? undefined,
- traceTags: query.traceTags ?? undefined,
- dataType: query.dataType ?? undefined,
- fromTimestamp: query.fromTimestamp ?? undefined,
- toTimestamp: query.toTimestamp ?? undefined,
- source: query.source ?? undefined,
- value: query.value ?? undefined,
- operator: query.operator ?? undefined,
- scoreIds: query.scoreIds ?? undefined,
- }),
- ]);
-
- const finalCount = count ? count : 0;
-
- return {
- data: legacyFilterAndValidateV1GetScoreList(items),
- meta: {
- page: query.page,
- limit: query.limit,
- totalItems: finalCount,
- totalPages: Math.ceil(finalCount / query.limit),
- },
- };
- },
- });
+ };
},
}),
});
diff --git a/web/src/pages/api/public/sessions/[sessionId].ts b/web/src/pages/api/public/sessions/[sessionId].ts
index 03e04de606..15345e8ab5 100644
--- a/web/src/pages/api/public/sessions/[sessionId].ts
+++ b/web/src/pages/api/public/sessions/[sessionId].ts
@@ -6,7 +6,6 @@ import {
import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";
import { createAuthedAPIRoute } from "@/src/features/public-api/server/createAuthedAPIRoute";
import { LangfuseNotFoundError } from "@langfuse/shared";
-import { measureAndReturnApi } from "@/src/server/utils/checkClickhouseAccess";
import { getTracesBySessionId } from "@langfuse/shared/src/server";
export default withMiddlewares({
@@ -16,47 +15,34 @@ export default withMiddlewares({
responseSchema: GetSessionV1Response,
fn: async ({ query, auth }) => {
const { sessionId } = query;
-
- return await measureAndReturnApi({
- input: { projectId: auth.scope.projectId, queryClickhouse: false },
- operation: "scores.countAll",
- user: null,
- pgExecution: async () => {
- throw new LangfuseNotFoundError(
- "Session not found within authorized project",
- );
+ const session = await prisma.traceSession.findUnique({
+ where: {
+ id_projectId: {
+ id: sessionId,
+ projectId: auth.scope.projectId,
+ },
+ },
+ select: {
+ id: true,
+ createdAt: true,
+ projectId: true,
},
- clickhouseExecution: async () => {
- const session = await prisma.traceSession.findUnique({
- where: {
- id_projectId: {
- id: sessionId,
- projectId: auth.scope.projectId,
- },
- },
- select: {
- id: true,
- createdAt: true,
- projectId: true,
- },
- });
+ });
- if (!session) {
- throw new LangfuseNotFoundError(
- "Session not found within authorized project",
- );
- }
+ if (!session) {
+ throw new LangfuseNotFoundError(
+ "Session not found within authorized project",
+ );
+ }
- const traces = await getTracesBySessionId(auth.scope.projectId, [
- sessionId,
- ]);
+ const traces = await getTracesBySessionId(auth.scope.projectId, [
+ sessionId,
+ ]);
- return {
- ...session,
- traces,
- };
- },
- });
+ return {
+ ...session,
+ traces,
+ };
},
}),
});
diff --git a/web/src/pages/api/public/traces/[traceId].ts b/web/src/pages/api/public/traces/[traceId].ts
index e1b585dae9..8be262eede 100644
--- a/web/src/pages/api/public/traces/[traceId].ts
+++ b/web/src/pages/api/public/traces/[traceId].ts
@@ -5,7 +5,6 @@ import {
GetTraceV1Query,
GetTraceV1Response,
} from "@/src/features/public-api/types/traces";
-import { measureAndReturnApi } from "@/src/server/utils/checkClickhouseAccess";
import {
filterAndValidateDbScoreList,
LangfuseNotFoundError,
@@ -26,171 +25,106 @@ export default withMiddlewares({
responseSchema: GetTraceV1Response,
fn: async ({ query, auth }) => {
const { traceId } = query;
+ const trace = await getTraceById(traceId, auth.scope.projectId);
+ const [observations, scores] = await Promise.all([
+ getObservationsViewForTrace(
+ traceId,
+ auth.scope.projectId,
+ trace?.timestamp,
+ true,
+ ),
+ getScoresForTraces({
+ projectId: auth.scope.projectId,
+ traceIds: [traceId],
+ timestamp: trace?.timestamp,
+ }),
+ ]);
- return await measureAndReturnApi({
- input: { projectId: auth.scope.projectId, queryClickhouse: false },
- operation: "api/public/traces/[traceId]",
- user: null,
- pgExecution: async () => {
- const trace = await prisma.traceView.findFirst({
- where: {
- id: traceId,
- projectId: auth.scope.projectId,
- },
- });
+ const uniqueModels: string[] = Array.from(
+ new Set(
+ observations
+ .map((r) => r.modelId)
+ .filter((r): r is string => Boolean(r)),
+ ),
+ );
- if (!trace) {
- throw new LangfuseNotFoundError(
- "Trace not found within authorized project",
- );
- }
-
- const [scores, observations] = await Promise.all([
- prisma.score.findMany({
+ const models =
+ uniqueModels.length > 0
+ ? await prisma.model.findMany({
where: {
- traceId: traceId,
- projectId: auth.scope.projectId,
+ id: {
+ in: uniqueModels,
+ },
+ OR: [{ projectId: auth.scope.projectId }, { projectId: null }],
},
- orderBy: { timestamp: "desc" },
- }),
- prisma.observationView.findMany({
- where: {
- traceId: traceId,
- projectId: auth.scope.projectId,
+ include: {
+ Price: true,
},
- orderBy: { startTime: "asc" },
- }),
- ]);
-
- const outObservations = observations.map(transformDbToApiObservation);
- const validatedScores = filterAndValidateDbScoreList(
- scores,
- traceException,
- );
-
- const { duration, ...restOfTrace } = trace;
-
- return {
- ...restOfTrace,
- scores: validatedScores,
- htmlPath: `/project/${auth.scope.projectId}/traces/${traceId}`,
- totalCost: outObservations.reduce(
- (acc, obs) => acc + (obs.calculatedTotalCost ?? 0),
- 0,
- ),
- latency: duration ?? 0,
- observations: outObservations,
- };
- },
- clickhouseExecution: async () => {
- const trace = await getTraceById(traceId, auth.scope.projectId);
- const [observations, scores] = await Promise.all([
- getObservationsViewForTrace(
- traceId,
- auth.scope.projectId,
- trace?.timestamp,
- true,
- ),
- getScoresForTraces({
- projectId: auth.scope.projectId,
- traceIds: [traceId],
- timestamp: trace?.timestamp,
- }),
- ]);
+ })
+ : [];
- const uniqueModels: string[] = Array.from(
- new Set(
- observations
- .map((r) => r.modelId)
- .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 observationsView = observations.map((o) => {
- const model = models.find((m) => m.id === o.modelId);
- 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.modelId);
+ 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,
+ };
+ });
- 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 outObservations = observationsView.map(
- transformDbToApiObservation,
- );
- const validatedScores = filterAndValidateDbScoreList(
- scores,
- traceException,
- );
+ const outObservations = observationsView.map(transformDbToApiObservation);
+ 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 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 : 0,
- observations: outObservations,
- htmlPath: `/project/${auth.scope.projectId}/traces/${traceId}`,
- totalCost: observations
- .reduce(
- (acc, obs) =>
- acc.add(obs.calculatedTotalCost ?? new Decimal(0)),
- new Decimal(0),
- )
- .toNumber(),
- };
- },
- });
+ 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 : 0,
+ observations: outObservations,
+ htmlPath: `/project/${auth.scope.projectId}/traces/${traceId}`,
+ totalCost: observations
+ .reduce(
+ (acc, obs) => acc.add(obs.calculatedTotalCost ?? new Decimal(0)),
+ new Decimal(0),
+ )
+ .toNumber(),
+ };
},
}),
});
diff --git a/web/src/pages/api/public/traces/index.ts b/web/src/pages/api/public/traces/index.ts
index 9483ea9247..948dec3a9d 100644
--- a/web/src/pages/api/public/traces/index.ts
+++ b/web/src/pages/api/public/traces/index.ts
@@ -1,4 +1,3 @@
-import { prisma } from "@langfuse/shared/src/db";
import {
PostTracesV1Body,
GetTracesV1Query,
@@ -7,21 +6,13 @@ import {
} from "@/src/features/public-api/types/traces";
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 "@langfuse/shared/src/server";
import { tokenCount } from "@/src/features/ingest/usage";
-import { type Trace } from "@langfuse/shared";
-import {
- eventTypes,
- logger,
- orderByToPrismaSql,
-} from "@langfuse/shared/src/server";
+import { eventTypes, logger } from "@langfuse/shared/src/server";
import { v4 } from "uuid";
import { telemetry } from "@/src/features/telemetry";
-import { tracesTableCols } from "@langfuse/shared";
-import { measureAndReturnApi } from "@/src/server/utils/checkClickhouseAccess";
import {
generateTracesForPublicApi,
getTracesCountForPublicApi,
@@ -65,179 +56,35 @@ export default withMiddlewares({
querySchema: GetTracesV1Query,
responseSchema: GetTracesV1Response,
fn: async ({ query, auth }) => {
- return await measureAndReturnApi({
- input: { projectId: auth.scope.projectId, queryClickhouse: false },
- operation: "api/public/traces",
- user: null,
- pgExecution: async () => {
- const skipValue = (query.page - 1) * query.limit;
- const userCondition = query.userId
- ? Prisma.sql`AND t."user_id" = ${query.userId}`
- : Prisma.empty;
- const nameCondition = query.name
- ? Prisma.sql`AND t."name" = ${query.name}`
- : Prisma.empty;
- const tagsCondition = query.tags
- ? Prisma.sql`AND ARRAY[${Prisma.join(
- (Array.isArray(query.tags)
- ? query.tags
- : query.tags.split(",")
- ).map((v) => Prisma.sql`${v}`),
- ", ",
- )}] <@ t."tags"`
- : Prisma.empty;
- const sessionCondition = query.sessionId
- ? Prisma.sql`AND t."session_id" = ${query.sessionId}`
- : Prisma.empty;
- const fromTimestampCondition = query.fromTimestamp
- ? Prisma.sql`AND t."timestamp" >= ${query.fromTimestamp}::timestamp with time zone at time zone 'UTC'`
- : Prisma.empty;
- const toTimestampCondition = query.toTimestamp
- ? Prisma.sql`AND t."timestamp" < ${query.toTimestamp}::timestamp with time zone at time zone 'UTC'`
- : Prisma.empty;
- const versionCondition = query.version
- ? Prisma.sql`AND t."version" = ${query.version}`
- : Prisma.empty;
- const releaseCondition = query.release
- ? Prisma.sql`AND t."release" = ${query.release}`
- : Prisma.empty;
-
- const orderByCondition = orderByToPrismaSql(
- query.orderBy ?? null,
- tracesTableCols,
- );
-
- const traces = await prisma.$queryRaw<
- Array<
- Trace & {
- observations: string[];
- scores: string[];
- totalCost: number;
- latency: number;
- htmlPath: string;
- }
- >
- >(Prisma.sql`
- SELECT
- t.id,
- CONCAT('/project/', t.project_id,'/traces/',t.id) as "htmlPath",
- t.timestamp,
- t.name,
- t.input,
- t.output,
- t.project_id as "projectId",
- t.session_id as "sessionId",
- t.metadata,
- t.external_id as "externalId",
- t.user_id as "userId",
- t.release,
- t.version,
- t.bookmarked,
- t.created_at as "createdAt",
- t.updated_at as "updatedAt",
- t.public,
- t.tags,
- COALESCE(o."totalCost", 0)::DOUBLE PRECISION AS "totalCost",
- COALESCE(o."latency", 0)::double precision AS "latency",
- COALESCE(o."observations", ARRAY[]::text[]) AS "observations",
- COALESCE(s."scores", ARRAY[]::text[]) AS "scores"
- FROM (
- SELECT *
- FROM "traces" t
- WHERE project_id = ${auth.scope.projectId}
- ${fromTimestampCondition}
- ${toTimestampCondition}
- ${userCondition}
- ${nameCondition}
- ${tagsCondition}
- ${versionCondition}
- ${releaseCondition}
- ${sessionCondition}
- ${orderByCondition}
- LIMIT ${query.limit} OFFSET ${skipValue}
- ) AS t
- LEFT JOIN LATERAL (
- SELECT
- SUM(o.calculated_total_cost)::DOUBLE PRECISION AS "totalCost",
- EXTRACT(EPOCH FROM COALESCE(MAX(o."end_time"), MAX(o."start_time"))) - EXTRACT(EPOCH FROM MIN(o."start_time"))::DOUBLE PRECISION AS "latency",
- ARRAY_AGG(DISTINCT o.id) FILTER (WHERE o.id IS NOT NULL) AS "observations"
- FROM "observations_view" AS o
- WHERE o.trace_id = t.id AND o.project_id = ${auth.scope.projectId}
- ) AS o ON true
- LEFT JOIN LATERAL (
- SELECT
- ARRAY_AGG(DISTINCT s.id) FILTER (WHERE s.id IS NOT NULL) AS "scores"
- FROM "scores" AS s
- WHERE s.trace_id = t.id AND s.project_id = ${auth.scope.projectId}
- ) AS s ON true
- `);
-
- const totalItems = await prisma.trace.count({
- where: {
- projectId: auth.scope.projectId,
- name: query.name ? query.name : undefined,
- userId: query.userId ? query.userId : undefined,
- sessionId: query.sessionId ? query.sessionId : undefined,
- version: query.version ? query.version : undefined,
- release: query.release ? query.release : undefined,
- timestamp: {
- gte: query.fromTimestamp
- ? new Date(query.fromTimestamp)
- : undefined,
- lt: query.toTimestamp ? new Date(query.toTimestamp) : undefined,
- },
- tags: query.tags
- ? {
- hasEvery: Array.isArray(query.tags)
- ? query.tags
- : query.tags.split(","),
- }
- : undefined,
- },
- });
-
- return {
- data: traces,
- meta: {
- page: query.page,
- limit: query.limit,
- totalItems,
- totalPages: Math.ceil(totalItems / query.limit),
- },
- };
- },
- clickhouseExecution: async () => {
- const filterProps = {
- projectId: auth.scope.projectId,
- page: query.page ?? undefined,
- limit: query.limit ?? undefined,
- userId: query.userId ?? undefined,
- name: query.name ?? undefined,
- tags: query.tags ?? undefined,
- sessionId: query.sessionId ?? undefined,
- version: query.version ?? undefined,
- release: query.release ?? undefined,
- fromTimestamp: query.fromTimestamp ?? undefined,
- toTimestamp: query.toTimestamp ?? undefined,
- };
+ const filterProps = {
+ projectId: auth.scope.projectId,
+ page: query.page ?? undefined,
+ limit: query.limit ?? undefined,
+ userId: query.userId ?? undefined,
+ name: query.name ?? undefined,
+ tags: query.tags ?? undefined,
+ sessionId: query.sessionId ?? undefined,
+ version: query.version ?? undefined,
+ release: query.release ?? undefined,
+ fromTimestamp: query.fromTimestamp ?? undefined,
+ toTimestamp: query.toTimestamp ?? undefined,
+ };
- const [items, count] = await Promise.all([
- generateTracesForPublicApi(filterProps, query.orderBy ?? null),
- getTracesCountForPublicApi(filterProps),
- ]);
+ const [items, count] = await Promise.all([
+ generateTracesForPublicApi(filterProps, query.orderBy ?? null),
+ getTracesCountForPublicApi(filterProps),
+ ]);
- const finalCount = count || 0;
- return {
- data: items,
- meta: {
- page: query.page,
- limit: query.limit,
- totalItems: finalCount,
- totalPages: Math.ceil(finalCount / query.limit),
- },
- };
+ const finalCount = count || 0;
+ return {
+ data: items,
+ meta: {
+ page: query.page,
+ limit: query.limit,
+ totalItems: finalCount,
+ totalPages: Math.ceil(finalCount / query.limit),
},
- });
+ };
},
}),
});
diff --git a/web/src/server/api/routers/comments.ts b/web/src/server/api/routers/comments.ts
index 7458d074d1..c56b089ca0 100644
--- a/web/src/server/api/routers/comments.ts
+++ b/web/src/server/api/routers/comments.ts
@@ -10,7 +10,6 @@ import { Prisma, CreateCommentData, DeleteCommentData } from "@langfuse/shared";
import { auditLog } from "@/src/features/audit-logs/auditLog";
import { TRPCError } from "@trpc/server";
import { validateCommentReferenceObject } from "@/src/features/comments/validateCommentReferenceObject";
-import { measureAndReturnApi } from "@/src/server/utils/checkClickhouseAccess";
import {
getTracesIdentifierForSession,
logger,
@@ -274,40 +273,27 @@ export const commentsRouter = createTRPCRouter({
)
.query(async ({ input, ctx }) => {
try {
- return await measureAndReturnApi({
- input,
- operation: "comments.getTraceCommentCountsBySessionId",
- user: ctx.session.user ?? undefined,
- pgExecution: async () => {
- throw new TRPCError({
- code: "NOT_FOUND",
- message: "Session not found in project",
- });
- },
- clickhouseExecution: async () => {
- const clickhouseTraces = await getTracesIdentifierForSession(
- input.projectId,
- input.sessionId,
- );
+ const clickhouseTraces = await getTracesIdentifierForSession(
+ input.projectId,
+ input.sessionId,
+ );
- const allTraceCommentCounts = await ctx.prisma.$queryRaw<
- Array<{ objectId: string; count: bigint }>
- >`
- SELECT object_id as "objectId", COUNT(*) as count
- FROM comments
- WHERE project_id = ${input.projectId}
- AND object_type = 'TRACE'
- GROUP BY object_id
- `;
+ const allTraceCommentCounts = await ctx.prisma.$queryRaw<
+ Array<{ objectId: string; count: bigint }>
+ >`
+ SELECT object_id as "objectId", COUNT(*) as count
+ FROM comments
+ WHERE project_id = ${input.projectId}
+ AND object_type = 'TRACE'
+ GROUP BY object_id
+ `;
- const traceIds = new Set(clickhouseTraces.map((t) => t.id));
- return new Map(
- allTraceCommentCounts
- .filter((c) => traceIds.has(c.objectId))
- .map(({ objectId, count }) => [objectId, Number(count)]),
- );
- },
- });
+ const traceIds = new Set(clickhouseTraces.map((t) => t.id));
+ return new Map(
+ allTraceCommentCounts
+ .filter((c) => traceIds.has(c.objectId))
+ .map(({ objectId, count }) => [objectId, Number(count)]),
+ );
} catch (error) {
logger.error(
"Failed to call comments.getTraceCommentCountBySessionId",
diff --git a/web/src/server/api/routers/generations/filterOptionsQuery.ts b/web/src/server/api/routers/generations/filterOptionsQuery.ts
index f5d697ea28..ecf8247fcb 100644
--- a/web/src/server/api/routers/generations/filterOptionsQuery.ts
+++ b/web/src/server/api/routers/generations/filterOptionsQuery.ts
@@ -6,10 +6,7 @@ import {
type ObservationOptions,
} from "@langfuse/shared";
import { protectedProjectProcedure } from "@/src/server/api/trpc";
-import { Prisma } from "@langfuse/shared/src/db";
import {
- datetimeFilterToPrisma,
- datetimeFilterToPrismaSql,
getObservationsGroupedByModel,
getObservationsGroupedByModelId,
getObservationsGroupedByName,
@@ -18,7 +15,6 @@ import {
getTracesGroupedByName,
getTracesGroupedByTags,
} from "@langfuse/shared/src/server";
-import { measureAndReturnApi } from "@/src/server/utils/checkClickhouseAccess";
export const filterOptionsQuery = protectedProjectProcedure
.input(
@@ -28,25 +24,8 @@ export const filterOptionsQuery = protectedProjectProcedure
queryClickhouse: z.boolean().default(false),
}),
)
- .query(async ({ input, ctx }) => {
+ .query(async ({ input }) => {
const { startTimeFilter } = input;
- const prismaStartTimeFilter = startTimeFilter
- ? datetimeFilterToPrisma(startTimeFilter)
- : {};
-
- const queryFilter = {
- projectId: input.projectId,
- type: "GENERATION",
- } as const;
-
- const rawStartTimeFilter =
- startTimeFilter && startTimeFilter.type === "datetime"
- ? datetimeFilterToPrismaSql(
- "start_time",
- startTimeFilter.operator,
- startTimeFilter.value,
- )
- : Prisma.empty;
const getClickhouseTraceName = async (): Promise<
Array<{ traceName: string }>
@@ -87,142 +66,47 @@ export const filterOptionsQuery = protectedProjectProcedure
return traces.map((i) => ({ tag: i.value }));
};
- // Score names
const [scores, model, name, promptNames, traceNames, tags, modelId] =
- await measureAndReturnApi({
- input,
- operation: "traces.all",
- user: ctx.session.user,
- pgExecution: async () => {
- return await Promise.all([
- // scores
- ctx.prisma.score.groupBy({
- where: {
- projectId: input.projectId,
- timestamp: prismaStartTimeFilter,
- dataType: { in: ["NUMERIC", "BOOLEAN"] },
- },
- take: 1000,
- orderBy: {
- name: "asc",
- },
- by: ["name"],
- }),
- // model
- ctx.prisma.observation.groupBy({
- by: ["model"],
- where: { ...queryFilter, startTime: prismaStartTimeFilter },
- take: 1000,
- orderBy: { model: "asc" },
- }),
- // name
- ctx.prisma.observation.groupBy({
- by: ["name"],
- where: { ...queryFilter, startTime: prismaStartTimeFilter },
- take: 1000,
- orderBy: { name: "asc" },
- }),
- // promptNames
- ctx.prisma.$queryRaw<
- Array<{
- promptName: string | null;
- }>
- >(Prisma.sql`
- SELECT
- p.name "promptName"
- FROM prompts p
- JOIN observations o ON o.prompt_id = p.id
- WHERE o.type = 'GENERATION'
- AND o.project_id = ${input.projectId}
- AND o.prompt_id IS NOT NULL
- AND p.project_id = ${input.projectId}
- ${rawStartTimeFilter}
- GROUP BY p.name
- ORDER BY p.name ASC
- LIMIT 1000;
- `),
- // traceNames
- ctx.prisma.$queryRaw<
- Array<{
- traceName: string | null;
- }>
- >(Prisma.sql`
- SELECT
- t.name "traceName"
- FROM traces t
- JOIN observations o ON o.trace_id = t.id
- WHERE o.type = 'GENERATION'
- AND o.project_id = ${input.projectId}
- AND t.project_id = ${input.projectId}
- ${rawStartTimeFilter}
- GROUP BY t.name
- ORDER BY t.name ASC
- LIMIT 1000;
- `),
- // traceTags
- ctx.prisma.$queryRaw<
- Array<{
- tag: string | null;
- }>
- >(Prisma.sql`
- SELECT
- DISTINCT tag
- FROM traces t
- JOIN observations o ON o.trace_id = t.id,
- UNNEST(t.tags) AS tag
- WHERE o.type = 'GENERATION'
- AND o.project_id = ${input.projectId}
- AND t.project_id = ${input.projectId}
- ${rawStartTimeFilter}
- LIMIT 1000;
- `),
- // modelId
- [] as any[],
- ]);
- },
- clickhouseExecution: async () => {
- return await Promise.all([
- //scores
- getScoresGroupedByName(
- input.projectId,
- startTimeFilter
- ? [
- {
- column: "Timestamp",
- operator: startTimeFilter.operator,
- value: startTimeFilter.value,
- type: "datetime",
- },
- ]
- : [],
- ),
- //model
- getObservationsGroupedByModel(
- input.projectId,
- startTimeFilter ? [startTimeFilter] : [],
- ),
- //name
- getObservationsGroupedByName(
- input.projectId,
- startTimeFilter ? [startTimeFilter] : [],
- ),
- //prompt name
- getObservationsGroupedByPromptName(
- input.projectId,
- startTimeFilter ? [startTimeFilter] : [],
- ),
- //trace name
- getClickhouseTraceName(),
- // trace tags
- getClickhouseTraceTags(),
- // modelId
- getObservationsGroupedByModelId(
- input.projectId,
- startTimeFilter ? [startTimeFilter] : [],
- ),
- ]);
- },
- });
+ await Promise.all([
+ //scores
+ getScoresGroupedByName(
+ input.projectId,
+ startTimeFilter
+ ? [
+ {
+ column: "Timestamp",
+ operator: startTimeFilter.operator,
+ value: startTimeFilter.value,
+ type: "datetime",
+ },
+ ]
+ : [],
+ ),
+ //model
+ getObservationsGroupedByModel(
+ input.projectId,
+ startTimeFilter ? [startTimeFilter] : [],
+ ),
+ //name
+ getObservationsGroupedByName(
+ input.projectId,
+ startTimeFilter ? [startTimeFilter] : [],
+ ),
+ //prompt name
+ getObservationsGroupedByPromptName(
+ input.projectId,
+ startTimeFilter ? [startTimeFilter] : [],
+ ),
+ //trace name
+ getClickhouseTraceName(),
+ // trace tags
+ getClickhouseTraceTags(),
+ // modelId
+ getObservationsGroupedByModelId(
+ input.projectId,
+ startTimeFilter ? [startTimeFilter] : [],
+ ),
+ ]);
// typecheck filter options, needs to include all columns with options
const res: ObservationOptions = {
diff --git a/web/src/server/api/routers/generations/getAllQueries.ts b/web/src/server/api/routers/generations/getAllQueries.ts
index ef86b74209..52638be959 100644
--- a/web/src/server/api/routers/generations/getAllQueries.ts
+++ b/web/src/server/api/routers/generations/getAllQueries.ts
@@ -1,14 +1,9 @@
import { z } from "zod";
import { protectedProjectProcedure } from "@/src/server/api/trpc";
import { paginationZod } from "@langfuse/shared";
-import { Prisma } from "@langfuse/shared/src/db";
import { GenerationTableOptions } from "./utils/GenerationTableOptions";
import { getAllGenerations } from "@/src/server/api/routers/generations/db/getAllGenerationsSqlQuery";
-import {
- getObservationsTableCount,
- parseGetAllGenerationsInput,
-} from "@langfuse/shared/src/server";
-import { measureAndReturnApi } from "@/src/server/utils/checkClickhouseAccess";
+import { getObservationsTableCount } from "@langfuse/shared/src/server";
const GetAllGenerationsInput = GenerationTableOptions.extend({
...paginationZod,
@@ -23,33 +18,13 @@ export const getAllQueries = {
queryClickhouse: z.boolean().default(false),
}),
)
- .query(async ({ input, ctx }) => {
- return await measureAndReturnApi({
+ .query(async ({ input }) => {
+ const { generations } = await getAllGenerations({
input,
- operation: "generations.all",
- user: ctx.session.user,
- pgExecution: async () => {
- const { generations } = await getAllGenerations({
- input,
- selectIOAndMetadata: false,
- });
-
- return {
- generations: generations,
- };
- },
- clickhouseExecution: async () => {
- const { generations } = await getAllGenerations({
- input,
- selectIOAndMetadata: false,
- queryClickhouse: true,
- });
-
- return {
- generations: generations,
- };
- },
+ selectIOAndMetadata: false,
+ queryClickhouse: true,
});
+ return { generations };
}),
countAll: protectedProjectProcedure
.input(
@@ -58,67 +33,14 @@ export const getAllQueries = {
}),
)
.query(async ({ input, ctx }) => {
- return await measureAndReturnApi({
- input,
- operation: "generations.countAll",
- user: ctx.session.user,
- pgExecution: async () => {
- const { searchCondition, filterCondition, datetimeFilter } =
- parseGetAllGenerationsInput(input);
-
- const totalGenerations = await ctx.prisma.$queryRaw<
- Array<{ count: bigint }>
- >(
- Prisma.sql`
- SELECT
- count(*)
- FROM observations_view o
- JOIN traces t ON t.id = o.trace_id AND t.project_id = ${input.projectId}
- LEFT JOIN prompts p ON p.id = o.prompt_id AND p.project_id = ${input.projectId}
- LEFT JOIN LATERAL (
- SELECT
- jsonb_object_agg(name::text, avg_value::double precision) AS "scores_avg"
- FROM (
- SELECT
- name,
- avg(value) avg_value
- FROM
- scores
- WHERE
- scores."project_id" = ${input.projectId}
- AND scores."trace_id" = t.id
- AND scores."observation_id" = o.id
- AND scores."data_type" IN ('NUMERIC', 'BOOLEAN')
- GROUP BY
- name
- ) tmp
- ) AS s_avg ON true
- WHERE
- o.type = 'GENERATION'
- AND o.project_id = ${input.projectId}
- ${datetimeFilter}
- ${searchCondition}
- ${filterCondition}
- `,
- );
-
- const count = totalGenerations[0]?.count;
- return {
- totalCount: count ? Number(count) : undefined,
- };
- },
- clickhouseExecution: async () => {
- const countQuery = await getObservationsTableCount({
- projectId: ctx.session.projectId,
- filter: input.filter ?? [],
- limit: 1,
- offset: 0,
- });
-
- return {
- totalCount: countQuery.shift()?.count,
- };
- },
+ const countQuery = await getObservationsTableCount({
+ projectId: ctx.session.projectId,
+ filter: input.filter ?? [],
+ limit: 1,
+ offset: 0,
});
+ return {
+ totalCount: countQuery.shift()?.count,
+ };
}),
};
diff --git a/web/src/server/api/routers/observations.ts b/web/src/server/api/routers/observations.ts
index 1662f5107b..a879c8ca94 100644
--- a/web/src/server/api/routers/observations.ts
+++ b/web/src/server/api/routers/observations.ts
@@ -2,7 +2,6 @@ import {
createTRPCRouter,
protectedGetTraceProcedure,
} from "@/src/server/api/trpc";
-import { measureAndReturnApi } from "@/src/server/utils/checkClickhouseAccess";
import { getObservationById } from "@langfuse/shared/src/server";
import { TRPCError } from "@trpc/server";
import { z } from "zod";
@@ -18,38 +17,22 @@ export const observationsRouter = createTRPCRouter({
queryClickhouse: z.boolean().default(false),
}),
)
- .query(async ({ input, ctx }) => {
- return measureAndReturnApi({
- input,
- operation: "observations.byId",
- user: ctx.session.user,
- pgExecution: async () => {
- return await ctx.prisma.observation.findFirstOrThrow({
- where: {
- id: input.observationId,
- traceId: input.traceId,
- projectId: input.projectId,
- },
- });
- },
- clickhouseExecution: async () => {
- const obs = await getObservationById(
- input.observationId,
- input.projectId,
- true,
- input.startTime ?? undefined,
- );
- if (!obs) {
- throw new TRPCError({
- code: "NOT_FOUND",
- message: "Observation not found within authorized project",
- });
- }
- return {
- ...obs,
- internalModel: obs?.internalModelId,
- };
- },
- });
+ .query(async ({ input }) => {
+ const obs = await getObservationById(
+ input.observationId,
+ input.projectId,
+ true,
+ input.startTime ?? undefined,
+ );
+ if (!obs) {
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message: "Observation not found within authorized project",
+ });
+ }
+ return {
+ ...obs,
+ internalModel: obs?.internalModelId,
+ };
}),
});
diff --git a/web/src/server/api/routers/scores.ts b/web/src/server/api/routers/scores.ts
index c52f06b955..3549cffe90 100644
--- a/web/src/server/api/routers/scores.ts
+++ b/web/src/server/api/routers/scores.ts
@@ -1,10 +1,6 @@
import { z } from "zod";
import { throwIfNoProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
-import {
- type ScoreOptions,
- scoresTableCols,
-} from "@/src/server/api/definitions/scoresTable";
import { auditLog } from "@/src/features/audit-logs/auditLog";
import { composeAggregateScoreKey } from "@/src/features/scores/lib/aggregateScores";
import {
@@ -28,15 +24,11 @@ import {
InvalidRequestError,
InternalServerError,
} from "@langfuse/shared";
-import { Prisma, type Score } from "@langfuse/shared/src/db";
+import { type Score } from "@langfuse/shared/src/db";
import {
- datetimeFilterToPrisma,
- datetimeFilterToPrismaSql,
getScoresGroupedByNameSourceType,
getScoresUiCount,
getScoresUiTable,
- orderByToPrismaSql,
- tableColumnsToSqlFilterAndPrefix,
getScoreNames,
getTracesGroupedByTags,
deleteScore,
@@ -47,7 +39,6 @@ import {
convertDateToClickhouseDateTime,
searchExistingAnnotationScore,
} from "@langfuse/shared/src/server";
-import { measureAndReturnApi } from "@/src/server/utils/checkClickhouseAccess";
import { env } from "@/src/env.mjs";
import { v4 } from "uuid";
@@ -75,151 +66,75 @@ export const scoresRouter = createTRPCRouter({
ScoreAllOptions.extend({ queryClickhouse: z.boolean().default(false) }),
)
.query(async ({ input, ctx }) => {
- return await measureAndReturnApi({
- input,
- operation: "scores.all",
- user: ctx.session.user,
- pgExecution: async () => {
- const { filterCondition, orderByCondition } =
- parseScoresGetAllOptions(input);
-
- const scores = await ctx.prisma.$queryRaw<Array<AllScoresReturnType>>(
- generateScoresQuery(
- Prisma.sql`
- s.id,
- s.name,
- s.value,
- s.string_value AS "stringValue",
- s.timestamp,
- s.source,
- s.data_type AS "dataType",
- s.comment,
- s.trace_id AS "traceId",
- s.observation_id AS "observationId",
- s.author_user_id AS "authorUserId",
- t.user_id AS "traceUserId",
- t.name AS "traceName",
- t.tags AS "traceTags",
- je.job_configuration_id AS "jobConfigurationId",
- u.image AS "authorUserImage",
- u.name AS "authorUserName"
- `,
- input.projectId,
- ctx.session.orgId,
- filterCondition,
- orderByCondition,
- input.limit,
- input.page,
- ),
- );
+ const clickhouseScoreData = await getScoresUiTable({
+ projectId: input.projectId,
+ filter: input.filter ?? [],
+ orderBy: input.orderBy,
+ limit: input.limit,
+ offset: input.page * input.limit,
+ });
- return {
- scores,
- };
- },
- clickhouseExecution: async () => {
- const clickhouseScoreData = await getScoresUiTable({
+ const [jobExecutions, users] = await Promise.all([
+ ctx.prisma.jobExecution.findMany({
+ where: {
projectId: input.projectId,
- filter: input.filter ?? [],
- orderBy: input.orderBy,
- limit: input.limit,
- offset: input.page * input.limit,
- });
-
- const [jobExecutions, users] = await Promise.all([
- ctx.prisma.jobExecution.findMany({
- where: {
- projectId: input.projectId,
- jobOutputScoreId: {
- in: clickhouseScoreData.map((score) => score.id),
- },
- },
- select: {
- id: true,
- jobConfigurationId: true,
- jobOutputScoreId: true,
- },
- }),
- ctx.prisma.user.findMany({
- where: {
- id: {
- in: clickhouseScoreData
- .map((score) => score.authorUserId)
- .filter((s): s is string => Boolean(s)),
- },
- },
- select: {
- id: true,
- name: true,
- image: true,
- },
- }),
- ]);
-
+ jobOutputScoreId: {
+ in: clickhouseScoreData.map((score) => score.id),
+ },
+ },
+ select: {
+ id: true,
+ jobConfigurationId: true,
+ jobOutputScoreId: true,
+ },
+ }),
+ ctx.prisma.user.findMany({
+ where: {
+ id: {
+ in: clickhouseScoreData
+ .map((score) => score.authorUserId)
+ .filter((s): s is string => Boolean(s)),
+ },
+ },
+ select: {
+ id: true,
+ name: true,
+ image: true,
+ },
+ }),
+ ]);
+
+ return {
+ scores: clickhouseScoreData.map<AllScoresReturnType>((score) => {
+ const jobExecution = jobExecutions.find(
+ (je) => je.jobOutputScoreId === score.id,
+ );
+ const user = users.find((u) => u.id === score.authorUserId);
return {
- scores: clickhouseScoreData.map<AllScoresReturnType>((score) => {
- const jobExecution = jobExecutions.find(
- (je) => je.jobOutputScoreId === score.id,
- );
-
- const user = users.find((u) => u.id === score.authorUserId);
-
- return {
- ...score,
- jobConfigurationId: jobExecution?.jobConfigurationId ?? null,
- authorUserImage: user?.image ?? null,
- authorUserName: user?.name ?? null,
- };
- }),
+ ...score,
+ jobConfigurationId: jobExecution?.jobConfigurationId ?? null,
+ authorUserImage: user?.image ?? null,
+ authorUserName: user?.name ?? null,
};
- },
- });
+ }),
+ };
}),
countAll: protectedProjectProcedure
.input(
ScoreAllOptions.extend({ queryClickhouse: z.boolean().default(false) }),
)
- .query(async ({ input, ctx }) => {
- return await measureAndReturnApi({
- input,
- operation: "scores.countAll",
- user: ctx.session.user,
- pgExecution: async () => {
- const { filterCondition } = parseScoresGetAllOptions(input);
-
- const scoresCount = await ctx.prisma.$queryRaw<
- Array<{ totalCount: bigint }>
- >(
- generateScoresQuery(
- Prisma.sql` count(*) AS "totalCount"`,
- input.projectId,
- ctx.session.orgId,
- filterCondition,
- Prisma.empty,
- 1, // limit
- 0, // page
- ),
- );
-
- return {
- totalCount:
- scoresCount.length > 0 ? Number(scoresCount[0]?.totalCount) : 0,
- };
- },
- clickhouseExecution: async () => {
- const clickhouseScoreData = await getScoresUiCount({
- projectId: input.projectId,
- filter: input.filter ?? [],
- orderBy: input.orderBy,
- limit: 1,
- offset: 0,
- });
-
- return {
- totalCount: clickhouseScoreData,
- };
- },
+ .query(async ({ input }) => {
+ const clickhouseScoreData = await getScoresUiCount({
+ projectId: input.projectId,
+ filter: input.filter ?? [],
+ orderBy: input.orderBy,
+ limit: 1,
+ offset: 0,
});
+
+ return {
+ totalCount: clickhouseScoreData,
+ };
}),
filterOptions: protectedProjectProcedure
.input(
@@ -229,78 +144,23 @@ export const scoresRouter = createTRPCRouter({
queryClickhouse: z.boolean().default(false),
}),
)
- .query(async ({ input, ctx }) => {
+ .query(async ({ input }) => {
const { timestampFilter } = input;
- return await measureAndReturnApi({
- input,
- operation: "scores.filterOptions",
- user: ctx.session.user,
- pgExecution: async () => {
- const prismaTimestampFilter = timestampFilter
- ? datetimeFilterToPrisma(timestampFilter)
- : {};
-
- const rawTimestampFilter =
- timestampFilter && timestampFilter.type === "datetime"
- ? datetimeFilterToPrismaSql(
- "timestamp",
- timestampFilter.operator,
- timestampFilter.value,
- )
- : Prisma.empty;
- const [names, tags] = await Promise.all([
- ctx.prisma.score.groupBy({
- where: {
- projectId: input.projectId,
- timestamp: prismaTimestampFilter,
- },
- by: ["name"],
- _count: {
- _all: true,
- },
- take: 1000,
- orderBy: {
- _count: {
- id: "desc",
- },
- },
- }),
- 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}
- GROUP BY tags.tag
- ORDER BY tags.tag ASC
- LIMIT 1000
- `,
- ]);
-
- const res: ScoreOptions = {
- name: names.map((i) => ({ value: i.name, count: i._count._all })),
- tags: tags,
- };
-
- return res;
- },
- clickhouseExecution: async () => {
- const [names, tags] = await Promise.all([
- getScoreNames(
- input.projectId,
- timestampFilter ? [timestampFilter] : [],
- ),
- getTracesGroupedByTags({
- projectId: input.projectId,
- filter: timestampFilter ? [timestampFilter] : [],
- }),
- ]);
-
- const res: ScoreOptions = {
- name: names.map((i) => ({ value: i.name, count: i.count })),
- tags: tags,
- };
- return res;
- },
- });
+ const [names, tags] = await Promise.all([
+ getScoreNames(
+ input.projectId,
+ timestampFilter ? [timestampFilter] : [],
+ ),
+ getTracesGroupedByTags({
+ projectId: input.projectId,
+ filter: timestampFilter ? [timestampFilter] : [],
+ }),
+ ]);
+
+ return {
+ name: names.map((i) => ({ value: i.name, count: i.count })),
+ tags: tags,
+ };
}),
createAnnotationScore: protectedProjectProcedure
.input(CreateAnnotationScoreData)
@@ -515,81 +375,14 @@ export const scoresRouter = createTRPCRouter({
queryClickhouse: z.boolean().default(false),
}),
)
- .query(async ({ input, ctx }) => {
+ .query(async ({ input }) => {
const date = getDateFromOption(input.selectedTimeOption);
-
- return await measureAndReturnApi({
- input,
- operation: "scores.getScoreKeysAndProps",
- user: ctx.session.user,
- pgExecution: async () => {
- const scores = await ctx.prisma.score.groupBy({
- where: {
- projectId: input.projectId,
- ...(date ? { timestamp: { gte: date } } : {}),
- },
- take: 1000,
- orderBy: {
- _count: {
- id: "desc",
- },
- },
- by: ["name", "source", "dataType"],
- });
-
- if (scores.length === 0) return [];
- return scores.map(({ name, source, dataType }) => ({
- key: composeAggregateScoreKey({ name, source, dataType }),
- name: name,
- source: source,
- dataType: dataType,
- }));
- },
- clickhouseExecution: async () => {
- const res = await getScoresGroupedByNameSourceType(input.projectId);
-
- return res.map(({ name, source, dataType }) => ({
- key: composeAggregateScoreKey({ name, source, dataType }),
- name: name,
- source: source,
- dataType: dataType,
- }));
- },
- });
+ const res = await getScoresGroupedByNameSourceType(input.projectId, date);
+ return res.map(({ name, source, dataType }) => ({
+ key: composeAggregateScoreKey({ name, source, dataType }),
+ name: name,
+ source: source,
+ dataType: dataType,
+ }));
}),
});
-
-const parseScoresGetAllOptions = (input: z.infer<typeof ScoreAllOptions>) => {
- const filterCondition = tableColumnsToSqlFilterAndPrefix(
- input.filter,
- scoresTableCols,
- "traces_scores",
- );
-
- const orderByCondition = orderByToPrismaSql(input.orderBy, scoresTableCols);
- return { filterCondition, orderByCondition };
-};
-
-const generateScoresQuery = (
- select: Prisma.Sql,
- projectId: string,
- orgId: string,
- filterCondition: Prisma.Sql,
- orderCondition: Prisma.Sql,
- limit: number,
- page: number,
-) => {
- return Prisma.sql`
- SELECT
- ${select}
- FROM scores s
- LEFT JOIN traces t ON t.id = s.trace_id AND t.project_id = ${projectId}
- LEFT JOIN job_executions je ON je.job_output_score_id = s.id AND je.project_id = ${projectId}
- LEFT JOIN users u ON u.id = s.author_user_id AND u.id in (SELECT user_id FROM organization_memberships WHERE org_id = ${orgId})
- WHERE s.project_id = ${projectId}
- ${filterCondition}
- ${orderCondition}
- LIMIT ${limit}
- OFFSET ${page * limit}
-`;
-};
diff --git a/web/src/server/api/routers/sessions.ts b/web/src/server/api/routers/sessions.ts
index cfafc87603..d728adf6e1 100644
--- a/web/src/server/api/routers/sessions.ts
+++ b/web/src/server/api/routers/sessions.ts
@@ -11,18 +11,14 @@ import {
type FilterState,
orderBy,
paginationZod,
- type SessionOptions,
singleFilter,
timeFilter,
tracesTableUiColumnDefinitions,
} from "@langfuse/shared";
import { Prisma } from "@langfuse/shared/src/db";
import { TRPCError } from "@trpc/server";
-import { measureAndReturnApi } from "@/src/server/utils/checkClickhouseAccess";
import Decimal from "decimal.js";
import {
- createSessionsAllQuery,
- datetimeFilterToPrismaSql,
traceException,
getSessionsTable,
getSessionsTableCount,
@@ -52,77 +48,46 @@ export const sessionRouter = createTRPCRouter({
)
.query(async ({ input, ctx }) => {
try {
- return await measureAndReturnApi({
- input,
- operation: "sessions.all",
- user: ctx.session.user,
- pgExecution: async () => {
- const sessions = await ctx.prisma.$queryRaw<
- Array<{
- id: string;
- createdAt: Date;
- bookmarked: boolean;
- public: boolean;
- }>
- >(
- createSessionsAllQuery(
- Prisma.sql`
- s.id,
- s."created_at" AS "createdAt",
- s.bookmarked,
- s.public
- `,
- input,
- ),
- );
+ const finalFilter = await getPublicSessionsFilter(
+ input.projectId,
+ input.filter ?? [],
+ );
+ const sessions = await getSessionsTable({
+ projectId: input.projectId,
+ filter: finalFilter,
+ orderBy: input.orderBy,
+ page: input.page,
+ limit: input.limit,
+ });
- return {
- sessions,
- };
+ const prismaSessionInfo = await ctx.prisma.traceSession.findMany({
+ where: {
+ id: {
+ in: sessions.map((s) => s.session_id),
+ },
+ projectId: input.projectId,
},
- clickhouseExecution: async () => {
- const finalFilter = await getPublicSessionsFilter(
- input.projectId,
- input.filter ?? [],
- );
- const sessions = await getSessionsTable({
- projectId: input.projectId,
- filter: finalFilter,
- orderBy: input.orderBy,
- page: input.page,
- limit: input.limit,
- });
-
- const prismaSessionInfo = await ctx.prisma.traceSession.findMany({
- where: {
- id: {
- in: sessions.map((s) => s.session_id),
- },
- projectId: input.projectId,
- },
- select: {
- id: true,
- bookmarked: true,
- public: true,
- },
- });
- return {
- sessions: sessions.map((s) => ({
- id: s.session_id,
- userIds: s.user_ids,
- countTraces: s.trace_count,
- traceTags: s.trace_tags,
- createdAt: new Date(s.min_timestamp),
- bookmarked:
- prismaSessionInfo.find((p) => p.id === s.session_id)
- ?.bookmarked ?? false,
- public:
- prismaSessionInfo.find((p) => p.id === s.session_id)
- ?.public ?? false,
- })),
- };
+ select: {
+ id: true,
+ bookmarked: true,
+ public: true,
},
});
+ return {
+ sessions: sessions.map((s) => ({
+ id: s.session_id,
+ userIds: s.user_ids,
+ countTraces: s.trace_count,
+ traceTags: s.trace_tags,
+ createdAt: new Date(s.min_timestamp),
+ bookmarked:
+ prismaSessionInfo.find((p) => p.id === s.session_id)
+ ?.bookmarked ?? false,
+ public:
+ prismaSessionInfo.find((p) => p.id === s.session_id)?.public ??
+ false,
+ })),
+ };
} catch (e) {
logger.error("Unable to call sessions.all", e);
throw new TRPCError({
@@ -137,59 +102,23 @@ export const sessionRouter = createTRPCRouter({
queryClickhouse: z.boolean().default(false),
}),
)
- .query(async ({ input, ctx }) => {
+ .query(async ({ input }) => {
try {
- return await measureAndReturnApi({
- input,
- operation: "sessions.countAll",
- user: ctx.session.user,
- pgExecution: async () => {
- const inputForTotal: z.infer<typeof SessionFilterOptions> = {
- filter: input.filter,
- projectId: input.projectId,
- orderBy: null,
- limit: 1,
- page: 0,
- };
-
- const totalCount = await ctx.prisma.$queryRaw<
- Array<{
- totalCount: number;
- }>
- >(
- createSessionsAllQuery(
- Prisma.sql`
- count(*)::int as "totalCount"
- `,
- inputForTotal,
- {
- ignoreOrderBy: true,
- },
- ),
- );
-
- return {
- totalCount: totalCount[0].totalCount,
- };
- },
- clickhouseExecution: async () => {
- const finalFilter = await getPublicSessionsFilter(
- input.projectId,
- input.filter ?? [],
- );
- const count = await getSessionsTableCount({
- projectId: input.projectId,
- filter: finalFilter,
- orderBy: input.orderBy,
- page: 0,
- limit: 1,
- });
-
- return {
- totalCount: count,
- };
- },
+ const finalFilter = await getPublicSessionsFilter(
+ input.projectId,
+ input.filter ?? [],
+ );
+ const count = await getSessionsTableCount({
+ projectId: input.projectId,
+ filter: finalFilter,
+ orderBy: input.orderBy,
+ page: 0,
+ limit: 1,
});
+
+ return {
+ totalCount: count,
+ };
} catch (e) {
logger.error("Error in sessions.countAll", e);
throw new TRPCError({
@@ -209,116 +138,55 @@ export const sessionRouter = createTRPCRouter({
.query(async ({ input, ctx }) => {
try {
if (input.sessionIds.length === 0) return [];
- return await measureAndReturnApi({
- input,
- operation: "traces.metrics",
- user: ctx.session.user,
- pgExecution: async () => {
- const inputForMetrics: z.infer<typeof SessionFilterOptions> = {
- filter: [],
- projectId: input.projectId,
- orderBy: null,
- limit: 10000, // no limit
- page: 0,
- };
-
- const metrics = await ctx.prisma.$queryRaw<
- Array<{
- id: string;
- countTraces: number;
- userIds: (string | null)[] | null;
- sessionDuration: number | null;
- inputCost: Decimal;
- outputCost: Decimal;
- totalCost: Decimal;
- promptTokens: number;
- completionTokens: number;
- totalTokens: number;
- traceTags: string[];
- }>
- >(
- createSessionsAllQuery(
- Prisma.sql`
- s.id,
- t."userIds",
- t."countTraces",
- o."sessionDuration",
- o."totalCost" AS "totalCost",
- o."inputCost" AS "inputCost",
- o."outputCost" AS "outputCost",
- o."promptTokens" AS "promptTokens",
- o."completionTokens" AS "completionTokens",
- o."totalTokens" AS "totalTokens",
- t."tags" AS "traceTags"
- `,
- inputForMetrics,
- {
- ignoreOrderBy: true,
- sessionIdList: input.sessionIds,
- },
- ),
- );
-
- return metrics.map((row) => ({
- ...row,
- userIds: (row.userIds?.filter((t) => t !== null) ??
- []) as string[],
- traceTags: (row.traceTags?.filter((t) => t !== null) ??
- []) as string[],
- }));
+ const finalFilter = await getPublicSessionsFilter(input.projectId, [
+ {
+ column: "id",
+ type: "stringOptions",
+ operator: "any of",
+ value: input.sessionIds,
},
- clickhouseExecution: async () => {
- const finalFilter = await getPublicSessionsFilter(input.projectId, [
- {
- column: "id",
- type: "stringOptions",
- operator: "any of",
- value: input.sessionIds,
- },
- ]);
- const sessions = await getSessionsWithMetrics({
- projectId: input.projectId,
- filter: finalFilter,
- });
-
- const prismaSessionInfo = await ctx.prisma.traceSession.findMany({
- where: {
- id: {
- in: sessions.map((s) => s.session_id),
- },
- projectId: input.projectId,
- },
- select: {
- id: true,
- bookmarked: true,
- public: true,
- },
- });
+ ]);
+ const sessions = await getSessionsWithMetrics({
+ projectId: input.projectId,
+ filter: finalFilter,
+ });
- return sessions.map((s) => ({
- id: s.session_id,
- userIds: s.user_ids,
- countTraces: s.trace_count,
- traceTags: s.trace_tags,
- createdAt: new Date(s.min_timestamp),
- bookmarked:
- prismaSessionInfo.find((p) => p.id === s.session_id)
- ?.bookmarked ?? false,
- public:
- prismaSessionInfo.find((p) => p.id === s.session_id)?.public ??
- false,
- trace_count: Number(s.trace_count),
- total_observations: Number(s.total_observations),
- sessionDuration: Number(s.duration) / 1000,
- inputCost: new Decimal(s.session_input_cost),
- outputCost: new Decimal(s.session_output_cost),
- totalCost: new Decimal(s.session_total_cost),
- promptTokens: Number(s.session_input_usage),
- completionTokens: Number(s.session_output_usage),
- totalTokens: Number(s.session_total_usage),
- }));
+ const prismaSessionInfo = await ctx.prisma.traceSession.findMany({
+ where: {
+ id: {
+ in: sessions.map((s) => s.session_id),
+ },
+ projectId: input.projectId,
+ },
+ select: {
+ id: true,
+ bookmarked: true,
+ public: true,
},
});
+
+ return sessions.map((s) => ({
+ id: s.session_id,
+ userIds: s.user_ids,
+ countTraces: s.trace_count,
+ traceTags: s.trace_tags,
+ createdAt: new Date(s.min_timestamp),
+ bookmarked:
+ prismaSessionInfo.find((p) => p.id === s.session_id)?.bookmarked ??
+ false,
+ public:
+ prismaSessionInfo.find((p) => p.id === s.session_id)?.public ??
+ false,
+ trace_count: Number(s.trace_count),
+ total_observations: Number(s.total_observations),
+ sessionDuration: Number(s.duration) / 1000,
+ inputCost: new Decimal(s.session_input_cost),
+ outputCost: new Decimal(s.session_output_cost),
+ totalCost: new Decimal(s.session_total_cost),
+ promptTokens: Number(s.session_input_usage),
+ completionTokens: Number(s.session_output_usage),
+ totalTokens: Number(s.session_total_usage),
+ }));
} catch (e) {
logger.error("Error in sessions.metrics", e);
throw new TRPCError({
@@ -335,104 +203,53 @@ export const sessionRouter = createTRPCRouter({
queryClickhouse: z.boolean().default(false),
}),
)
- .query(async ({ input, ctx }) => {
+ .query(async ({ input }) => {
try {
const { timestampFilter } = input;
- return await measureAndReturnApi({
- input,
- operation: "sessions.filterOptions",
- user: ctx.session.user,
- pgExecution: async () => {
- const rawTimestampFilter =
- timestampFilter && timestampFilter.type === "datetime"
- ? datetimeFilterToPrismaSql(
- "timestamp",
- timestampFilter.operator,
- timestampFilter.value,
- )
- : Prisma.empty;
- const [userIds, tags] = await Promise.all([
- ctx.prisma.$queryRaw<Array<{ value: string }>>(Prisma.sql`
- SELECT
- traces.user_id AS value
- FROM traces
- WHERE
- traces.session_id IS NOT NULL
- AND traces.user_id IS NOT NULL
- AND traces.project_id = ${input.projectId} ${rawTimestampFilter}
- GROUP BY traces.user_id
- ORDER BY traces.user_id ASC
- LIMIT 1000;
- `),
- ctx.prisma.$queryRaw<
- Array<{
- value: string;
- }>
- >(Prisma.sql`
- SELECT DISTINCT tag AS value
- FROM traces t
- JOIN observations o ON o.trace_id = t.id,
- UNNEST(t.tags) AS tag
- WHERE o.type = 'GENERATION'
- AND o.project_id = ${input.projectId}
- AND t.project_id = ${input.projectId} ${rawTimestampFilter}
- LIMIT 1000;
- `),
- ]);
-
- const res: SessionOptions = {
- userIds: userIds,
- tags: tags,
- };
- return res;
+ const columns = [
+ ...tracesTableUiColumnDefinitions,
+ {
+ uiTableName: "Created At",
+ uiTableId: "createdAt",
+ clickhouseTableName: "traces",
+ clickhouseSelect: "timestamp",
},
- clickhouseExecution: async () => {
- const columns = [
- ...tracesTableUiColumnDefinitions,
- {
- uiTableName: "Created At",
- uiTableId: "createdAt",
- clickhouseTableName: "traces",
- clickhouseSelect: "timestamp",
- },
- ];
- const filter: FilterState = [
- {
- column: "sessionId",
- operator: "is not null",
- type: "null",
- value: "",
- },
- ];
- if (timestampFilter) {
- filter.push(timestampFilter);
- }
- const [userIds, tags] = await Promise.all([
- getTracesGroupedByUsers(
- input.projectId,
- filter,
- undefined,
- 1000,
- 0,
- columns,
- ),
- getTracesGroupedByTags({
- projectId: input.projectId,
- filter,
- columns,
- }),
- ]);
-
- return {
- userIds: userIds.map((row) => ({
- value: row.user,
- })),
- tags: tags.map((row) => ({
- value: row.value,
- })),
- };
+ ];
+ const filter: FilterState = [
+ {
+ column: "sessionId",
+ operator: "is not null",
+ type: "null",
+ value: "",
},
- });
+ ];
+ if (timestampFilter) {
+ filter.push(timestampFilter);
+ }
+ const [userIds, tags] = await Promise.all([
+ getTracesGroupedByUsers(
+ input.projectId,
+ filter,
+ undefined,
+ 1000,
+ 0,
+ columns,
+ ),
+ getTracesGroupedByTags({
+ projectId: input.projectId,
+ filter,
+ columns,
+ }),
+ ]);
+
+ return {
+ userIds: userIds.map((row) => ({
+ value: row.user,
+ })),
+ tags: tags.map((row) => ({
+ value: row.value,
+ })),
+ };
} catch (e) {
logger.error("Unable to get sessions.filterOptions", e);
throw new TRPCError({
@@ -451,84 +268,69 @@ export const sessionRouter = createTRPCRouter({
)
.query(async ({ input, ctx }) => {
try {
- return await measureAndReturnApi({
- input,
- operation: "sessions.byId",
- user: ctx.session.user ?? undefined,
- pgExecution: async () => {
- throw new TRPCError({
- code: "NOT_FOUND",
- message: "Session not found in project",
- });
+ const postgresSession = await ctx.prisma.traceSession.findFirst({
+ where: {
+ id: input.sessionId,
+ projectId: input.projectId,
},
- clickhouseExecution: async () => {
- const postgresSession = await ctx.prisma.traceSession.findFirst({
- where: {
- id: input.sessionId,
- projectId: input.projectId,
- },
- });
+ });
- if (!postgresSession) {
- throw new TRPCError({
- code: "NOT_FOUND",
- message: "Session not found in project",
- });
- }
+ if (!postgresSession) {
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message: "Session not found in project",
+ });
+ }
- const clickhouseTraces = await getTracesIdentifierForSession(
- input.projectId,
- input.sessionId,
- );
+ const clickhouseTraces = await getTracesIdentifierForSession(
+ input.projectId,
+ input.sessionId,
+ );
- const traceIds = clickhouseTraces.map((t) => t.id);
- const chunkSize = 500;
- const chunks = [];
+ const traceIds = clickhouseTraces.map((t) => t.id);
+ const chunkSize = 500;
+ const chunks = [];
- for (let i = 0; i < traceIds.length; i += chunkSize) {
- chunks.push(traceIds.slice(i, i + chunkSize));
- }
+ for (let i = 0; i < traceIds.length; i += chunkSize) {
+ chunks.push(traceIds.slice(i, i + chunkSize));
+ }
- const [scores, costs] = await Promise.all([
- Promise.all(
- chunks.map((chunk) =>
- getScoresForTraces({
- projectId: input.projectId,
- traceIds: chunk,
- }),
- ),
- ).then((results) => results.flat()),
- Promise.all(
- chunks.map((chunk) => getCostForTraces(input.projectId, chunk)),
- ).then((results) =>
- results.reduce((sum, cost) => (sum ?? 0) + (cost ?? 0), 0),
- ),
- ]);
+ const [scores, costs] = await Promise.all([
+ Promise.all(
+ chunks.map((chunk) =>
+ getScoresForTraces({
+ projectId: input.projectId,
+ traceIds: chunk,
+ }),
+ ),
+ ).then((results) => results.flat()),
+ Promise.all(
+ chunks.map((chunk) => getCostForTraces(input.projectId, chunk)),
+ ).then((results) =>
+ results.reduce((sum, cost) => (sum ?? 0) + (cost ?? 0), 0),
+ ),
+ ]);
- const costData = costs;
+ const costData = costs;
- const validatedScores = filterAndValidateDbScoreList(
- scores,
- traceException,
- );
+ const validatedScores = filterAndValidateDbScoreList(
+ scores,
+ traceException,
+ );
- return {
- ...postgresSession,
- traces: clickhouseTraces.map((t) => ({
- ...t,
- scores: validatedScores.filter((s) => s.traceId === t.id),
- })),
- totalCost: costData ?? 0,
- users: [
- ...new Set(
- clickhouseTraces
- .map((t) => t.userId)
- .filter((t) => t !== null),
- ),
- ],
- };
- },
- });
+ return {
+ ...postgresSession,
+ traces: clickhouseTraces.map((t) => ({
+ ...t,
+ scores: validatedScores.filter((s) => s.traceId === t.id),
+ })),
+ totalCost: costData ?? 0,
+ users: [
+ ...new Set(
+ clickhouseTraces.map((t) => t.userId).filter((t) => t !== null),
+ ),
+ ],
+ };
} catch (e) {
logger.error("Unable to get sessions.byId", e);
throw new TRPCError({
diff --git a/web/src/server/api/routers/traces.ts b/web/src/server/api/routers/traces.ts
index ba37cef2d8..eb28140495 100644
--- a/web/src/server/api/routers/traces.ts
+++ b/web/src/server/api/routers/traces.ts
@@ -14,20 +14,11 @@ import {
paginationZod,
singleFilter,
timeFilter,
- type TraceOptions,
tracesTableUiColumnDefinitions,
} from "@langfuse/shared";
+import { type ObservationView } from "@langfuse/shared/src/db";
import {
- type ObservationView,
- Prisma,
- type Trace,
-} from "@langfuse/shared/src/db";
-import {
- datetimeFilterToPrisma,
- datetimeFilterToPrismaSql,
traceException,
- createTracesQuery,
- parseTraceAllFilters,
getTracesTable,
getTracesTableCount,
getScoresForTraces,
@@ -46,11 +37,8 @@ import {
QueueJobs,
TraceDeleteQueue,
getTracesTableMetrics,
- type TracesAllUiReturnType,
- type TracesMetricsUiReturnType,
} from "@langfuse/shared/src/server";
import { TRPCError } from "@trpc/server";
-import { measureAndReturnApi } from "@/src/server/utils/checkClickhouseAccess";
import { randomUUID } from "crypto";
const TraceFilterOptions = z.object({
@@ -79,26 +67,8 @@ export const traceRouter = createTRPCRouter({
queryClickhouse: z.boolean().default(false),
}),
)
- .query(async ({ input, ctx }) => {
- return await measureAndReturnApi({
- input,
- operation: "traces.hasAny",
- user: ctx.session.user,
- pgExecution: async () => {
- const hasAny = await ctx.prisma.trace.findFirst({
- where: {
- projectId: input.projectId,
- },
- select: {
- id: true,
- },
- });
- return hasAny !== null;
- },
- clickhouseExecution: async () => {
- return await hasAnyTrace(input.projectId);
- },
- });
+ .query(async ({ input }) => {
+ return hasAnyTrace(input.projectId);
}),
all: protectedProjectProcedure
.input(
@@ -107,65 +77,15 @@ export const traceRouter = createTRPCRouter({
}),
)
.query(async ({ input, ctx }) => {
- return await measureAndReturnApi({
- input,
- operation: "traces.all",
- user: ctx.session.user,
- pgExecution: async () => {
- const {
- filterCondition,
- orderByCondition,
- observationTimeseriesFilter,
- searchCondition,
- } = parseTraceAllFilters(input);
-
- const tracesQuery = createTracesQuery({
- select: Prisma.sql`
- t.*,
- t."user_id" AS "userId",
- t.session_id AS "sessionId"
- `,
- projectId: input.projectId,
- observationTimeseriesFilter,
- page: input.page,
- limit: input.limit,
- searchCondition,
- filterCondition,
- orderByCondition,
- });
-
- const traces = await ctx.prisma.$queryRaw<Array<Trace>>(tracesQuery);
-
- return {
- traces: traces.map<TracesAllUiReturnType>(
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
- ({ input, output, metadata, ...trace }) => ({
- ...trace,
- name: trace.name,
- release: trace.release,
- version: trace.version,
- externalId: trace.externalId,
- userId: trace.userId,
- sessionId: trace.sessionId,
- }),
- ),
- };
- },
- clickhouseExecution: async () => {
- const res = await getTracesTable(
- ctx.session.projectId,
- input.filter ?? [],
- input.searchQuery ?? undefined,
- input.orderBy,
- input.limit,
- input.page,
- );
-
- return {
- traces: res,
- };
- },
- });
+ const traces = await getTracesTable(
+ ctx.session.projectId,
+ input.filter ?? [],
+ input.searchQuery ?? undefined,
+ input.orderBy,
+ input.limit,
+ input.page,
+ );
+ return { traces };
}),
countAll: protectedProjectProcedure
.input(
@@ -174,49 +94,14 @@ export const traceRouter = createTRPCRouter({
}),
)
.query(async ({ input, ctx }) => {
- return await measureAndReturnApi({
- input,
- operation: "traces.countAll",
- user: ctx.session.user,
- pgExecution: async () => {
- const {
- filterCondition,
- observationTimeseriesFilter,
- searchCondition,
- } = parseTraceAllFilters(input);
-
- 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);
-
- const totalTraceCount = totalTraces[0]?.count;
- return {
- totalCount: totalTraceCount ? Number(totalTraceCount) : undefined,
- };
- },
- clickhouseExecution: async () => {
- const countQuery = await getTracesTableCount({
- projectId: ctx.session.projectId,
- filter: input.filter ?? [],
- searchQuery: input.searchQuery ?? undefined,
- limit: 1,
- page: 0,
- });
-
- return {
- totalCount: countQuery,
- };
- },
+ const totalCount = await getTracesTableCount({
+ projectId: ctx.session.projectId,
+ filter: input.filter ?? [],
+ searchQuery: input.searchQuery ?? undefined,
+ limit: 1,
+ page: 0,
});
+ return { totalCount };
}),
metrics: protectedProjectProcedure
.input(
@@ -229,88 +114,37 @@ export const traceRouter = createTRPCRouter({
)
.query(async ({ input, ctx }) => {
if (input.traceIds.length === 0) return [];
- 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",
- COALESCE(generation_metrics."totalTokens", 0)::bigint AS "totalTokens",
- observation_metrics.latency AS "latency",
- observation_metrics."observationCount" AS "observationCount",
- COALESCE(generation_metrics."calculatedTotalCost", 0)::numeric AS "calculatedTotalCost",
- COALESCE(generation_metrics."calculatedInputCost", 0)::numeric AS "calculatedInputCost",
- 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)})`,
- });
-
- const [traceMetrics, scores] = await Promise.all([
- // traceMetrics
- ctx.prisma.$queryRaw<Array<TracesMetricsUiReturnType>>(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),
- ),
- }));
- },
- clickhouseExecution: async () => {
- const res = await getTracesTableMetrics({
- projectId: ctx.session.projectId,
- filter: [
- ...(input.filter ?? []),
- {
- type: "stringOptions",
- operator: "any of",
- column: "ID",
- value: input.traceIds,
- },
- ],
- });
-
- const scores = await getScoresForTraces({
- projectId: ctx.session.projectId,
- traceIds: res.map((r) => r.id),
- limit: 1000,
- offset: 0,
- });
-
- const validatedScores = filterAndValidateDbScoreList(
- scores,
- traceException,
- );
+ const res = await getTracesTableMetrics({
+ projectId: ctx.session.projectId,
+ filter: [
+ ...(input.filter ?? []),
+ {
+ type: "stringOptions",
+ operator: "any of",
+ column: "ID",
+ value: input.traceIds,
+ },
+ ],
+ });
- return res.map((row) => ({
- ...row,
- scores: aggregateScores(
- validatedScores.filter((s) => s.traceId === row.id),
- ),
- }));
- },
+ const scores = await getScoresForTraces({
+ projectId: ctx.session.projectId,
+ traceIds: res.map((r) => r.id),
+ limit: 1000,
+ offset: 0,
});
+
+ const validatedScores = filterAndValidateDbScoreList(
+ scores,
+ traceException,
+ );
+
+ return res.map((row) => ({
+ ...row,
+ scores: aggregateScores(
+ validatedScores.filter((s) => s.traceId === row.id),
+ ),
+ }));
}),
filterOptions: protectedProjectProcedure
.input(
@@ -320,96 +154,30 @@ export const traceRouter = createTRPCRouter({
queryClickhouse: z.boolean().default(false),
}),
)
- .query(async ({ input, ctx }) => {
- 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}
- GROUP BY tags.tag
- 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;
- },
- clickhouseExecution: async () => {
- const { timestampFilter } = input;
+ .query(async ({ input }) => {
+ const { timestampFilter } = input;
- 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;
- },
- });
+ 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] : [],
+ }),
+ ]);
+
+ return {
+ name: traceNames.map((n) => ({ value: n.name })),
+ scores_avg: scoreNames.map((s) => s.name),
+ tags: tags,
+ };
}),
byId: protectedGetTraceProcedure
.input(
@@ -420,34 +188,19 @@ export const traceRouter = createTRPCRouter({
queryClickhouse: z.boolean().default(false),
}),
)
- .query(async ({ input, ctx }) => {
- return await measureAndReturnApi({
- input,
- operation: "traces.byId",
- user: ctx.session.user ?? undefined,
- pgExecution: async () => {
- return ctx.prisma.trace.findFirstOrThrow({
- where: {
- id: input.traceId,
- projectId: input.projectId,
- },
- });
- },
- clickhouseExecution: async () => {
- const trace = getTraceById(
- input.traceId,
- input.projectId,
- input.timestamp ?? undefined,
- );
- if (!trace) {
- throw new TRPCError({
- code: "NOT_FOUND",
- message: "Trace not found",
- });
- }
- return trace;
- },
- });
+ .query(async ({ input }) => {
+ const trace = await getTraceById(
+ input.traceId,
+ input.projectId,
+ input.timestamp ?? undefined,
+ );
+ if (!trace) {
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message: "Trace not found",
+ });
+ }
+ return trace;
}),
byIdWithObservationsAndScores: protectedGetTraceProcedure
.input(
@@ -458,168 +211,61 @@ export const traceRouter = createTRPCRouter({
queryClickhouse: z.boolean().default(false),
}),
)
- .query(async ({ input, ctx }) => {
- return await measureAndReturnApi({
- input,
- operation: "traces.byIdWithObservationsAndScores",
- user: ctx.session.user ?? undefined,
- pgExecution: async () => {
- const [trace, observations, scores] = await Promise.all([
- ctx.prisma.trace.findFirst({
- 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,
- promptName: true,
- promptVersion: true,
- latency: true,
- updatedAt: true,
- },
- where: {
- traceId: {
- equals: input.traceId,
- not: null,
- },
- projectId: input.projectId,
- },
- }),
- ctx.prisma.score.findMany({
- where: {
- traceId: input.traceId,
- projectId: input.projectId,
- },
- }),
- ]);
-
- if (!trace) {
- throw new TRPCError({
- code: "NOT_FOUND",
- message: "Trace not found",
- });
- }
-
- 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.map((o) => ({
- ...o,
- usageDetails: {}, // no usageDetails in legacy postgres
- costDetails: {}, // no costDetails in legacy postgres
- })) as ObservationReturnType[],
- };
- },
- clickhouseExecution: async () => {
- const [trace, observations, scores] = await Promise.all([
- getTraceById(
- input.traceId,
- input.projectId,
- input.timestamp ?? undefined,
- ),
- getObservationsViewForTrace(
- input.traceId,
- input.projectId,
- input.timestamp ?? undefined,
- ),
- getScoresForTraces({
- projectId: input.projectId,
- traceIds: [input.traceId],
- timestamp: input.timestamp ?? undefined,
- }),
- ]);
-
- if (!trace) {
- throw new TRPCError({
- code: "NOT_FOUND",
- message: "Trace not found",
- });
- }
-
- const validatedScores = filterAndValidateDbScoreList(
- scores,
- traceException,
- );
+ .query(async ({ input }) => {
+ const [trace, observations, scores] = await Promise.all([
+ getTraceById(
+ input.traceId,
+ input.projectId,
+ input.timestamp ?? undefined,
+ ),
+ getObservationsViewForTrace(
+ input.traceId,
+ input.projectId,
+ input.timestamp ?? undefined,
+ ),
+ getScoresForTraces({
+ projectId: input.projectId,
+ traceIds: [input.traceId],
+ timestamp: input.timestamp ?? undefined,
+ }),
+ ]);
- 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;
+ if (!trace) {
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message: "Trace not found",
+ });
+ }
- return {
- ...trace,
- scores: validatedScores,
- latency: latencyMs !== undefined ? latencyMs / 1000 : undefined,
- observations: observations as ObservationReturnType[],
- };
- },
- });
+ 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[],
+ };
}),
deleteMany: protectedProjectProcedure
.input(
diff --git a/web/src/server/api/routers/users.ts b/web/src/server/api/routers/users.ts
index d656720368..88adaa9cfd 100644
--- a/web/src/server/api/routers/users.ts
+++ b/web/src/server/api/routers/users.ts
@@ -5,15 +5,11 @@ import {
protectedProjectProcedure,
} from "@/src/server/api/trpc";
import { paginationZod, singleFilter } from "@langfuse/shared";
-import { Prisma } from "@langfuse/shared/src/db";
-import { usersTableCols } from "@/src/server/api/definitions/usersTable";
import {
getTotalUserCount,
getTracesGroupedByUsers,
getUserMetrics,
- tableColumnsToSqlFilterAndPrefix,
} from "@langfuse/shared/src/server";
-import { measureAndReturnApi } from "@/src/server/utils/checkClickhouseAccess";
const UserFilterOptions = z.object({
projectId: z.string(), // Required for protectedProjectProcedure
@@ -36,83 +32,29 @@ export const userRouter = createTRPCRouter({
}),
)
.query(async ({ input, ctx }) => {
- return measureAndReturnApi({
- input,
- operation: "users.all",
- user: ctx.session.user,
- pgExecution: async () => {
- const filterCondition = tableColumnsToSqlFilterAndPrefix(
- input.filter ?? [],
- usersTableCols,
- "users",
- );
+ const [users, totalUsers] = await Promise.all([
+ getTracesGroupedByUsers(
+ ctx.session.projectId,
+ input.filter ?? [],
+ input.searchQuery ?? undefined,
+ input.limit,
+ input.page,
+ undefined,
+ ),
+ getTotalUserCount(
+ ctx.session.projectId,
+ input.filter ?? [],
+ input.searchQuery ?? undefined,
+ ),
+ ]);
- const searchCondition = input.searchQuery
- ? Prisma.sql`AND t.user_id ILIKE ${`%${input.searchQuery}%`}`
- : Prisma.empty;
-
- const [users, totalUsers] = await Promise.all([
- ctx.prisma.$queryRaw<
- Array<{ userId: string; totalTraces: bigint }>
- >`
- SELECT
- t.user_id AS "userId",
- COUNT(t.id)::bigint AS "totalTraces"
- FROM
- traces t
- WHERE
- t.user_id IS NOT NULL
- AND t.user_id != ''
- AND t.project_id = ${input.projectId}
- ${filterCondition}
- ${searchCondition}
- GROUP BY
- t.user_id
- ORDER BY
- "totalTraces" DESC
- LIMIT
- ${input.limit} OFFSET ${input.page * input.limit};
- `,
- ctx.prisma.$queryRaw<Array<{ totalCount: bigint }>>`
- SELECT COUNT(DISTINCT t.user_id)::bigint AS "totalCount"
- FROM traces t
- WHERE t.project_id = ${input.projectId}
- ${filterCondition}
- ${searchCondition}
- `,
- ]);
-
- return {
- totalUsers: totalUsers[0].totalCount,
- users,
- };
- },
- clickhouseExecution: async () => {
- const [users, totalUsers] = await Promise.all([
- getTracesGroupedByUsers(
- ctx.session.projectId,
- input.filter ?? [],
- input.searchQuery ?? undefined,
- input.limit,
- input.page,
- undefined,
- ),
- getTotalUserCount(
- ctx.session.projectId,
- input.filter ?? [],
- input.searchQuery ?? undefined,
- ),
- ]);
-
- return {
- totalUsers: totalUsers.shift()?.totalCount ?? 0,
- users: users.map((user) => ({
- userId: user.user,
- totalTraces: BigInt(user.count),
- })),
- };
- },
- });
+ return {
+ totalUsers: totalUsers.shift()?.totalCount ?? 0,
+ users: users.map((user) => ({
+ userId: user.user,
+ totalTraces: BigInt(user.count),
+ })),
+ };
}),
metrics: protectedProjectProcedure
@@ -124,84 +66,27 @@ export const userRouter = createTRPCRouter({
filter: z.array(singleFilter).nullable(),
}),
)
- .query(async ({ input, ctx }) => {
- return measureAndReturnApi({
- input,
- operation: "users.metrics",
- user: ctx.session.user,
- pgExecution: async () => {
- if (input.userIds.length === 0) {
- return [];
- }
- return ctx.prisma.$queryRaw<
- Array<{
- userId: string;
- firstTrace: Date | null;
- lastTrace: Date | null;
- totalPromptTokens: bigint;
- totalCompletionTokens: bigint;
- totalTokens: bigint;
- totalObservations: bigint;
- totalTraces: bigint;
- sumCalculatedTotalCost: number;
- }>
- >`
- SELECT t.user_id AS "userId",
- MIN(t."timestamp") AS "firstTrace",
- MAX(t."timestamp") AS "lastTrace",
- COALESCE(SUM(o.prompt_tokens), 0)::bigint AS "totalPromptTokens",
- COALESCE(SUM(o.completion_tokens), 0)::bigint AS "totalCompletionTokens",
- COALESCE(SUM(o.total_tokens), 0)::bigint AS "totalTokens",
- COUNT(o."totalObservations")::bigint AS "totalObservations",
- (COUNT(*) OVER ())::bigint AS "totalTraces",
- SUM(COALESCE(ov.calculated_total_cost, 0)) AS "sumCalculatedTotalCost"
- FROM traces t
- LEFT JOIN LATERAL (
- SELECT COALESCE(SUM(o.prompt_tokens), 0)::bigint AS "prompt_tokens",
- COALESCE(SUM(o.completion_tokens), 0)::bigint AS "completion_tokens",
- COALESCE(SUM(o.total_tokens), 0)::bigint AS "total_tokens",
- COUNT(DISTINCT o.id)::bigint AS "totalObservations"
- FROM observations o
- WHERE o.trace_id = t.id
- AND o.project_id = ${input.projectId}
- GROUP BY t.user_id
- ) o ON TRUE
- LEFT JOIN LATERAL (
- SELECT SUM(COALESCE(ov.calculated_total_cost, 0)) AS "calculated_total_cost"
- FROM observations_view ov
- WHERE ov.trace_id = t.id
- AND ov."type" = 'GENERATION'
- AND ov.project_id = ${input.projectId}
- GROUP BY t.user_id
- ) ov ON TRUE
- WHERE t.user_id IN (${Prisma.join(input.userIds)})
- AND t.project_id = ${input.projectId}
- GROUP BY 1;
- `;
- },
- clickhouseExecution: async () => {
- if (input.userIds.length === 0) {
- return [];
- }
- const metrics = await getUserMetrics(
- input.projectId,
- input.userIds,
- input.filter ?? [],
- );
+ .query(async ({ input }) => {
+ if (input.userIds.length === 0) {
+ return [];
+ }
+ const metrics = await getUserMetrics(
+ input.projectId,
+ input.userIds,
+ input.filter ?? [],
+ );
- return metrics.map((metric) => ({
- userId: metric.userId,
- firstTrace: metric.minTimestamp,
- lastTrace: metric.maxTimestamp,
- totalPromptTokens: BigInt(metric.inputUsage),
- totalCompletionTokens: BigInt(metric.outputUsage),
- totalTokens: BigInt(metric.totalUsage),
- totalObservations: BigInt(metric.observationCount),
- totalTraces: BigInt(metric.traceCount),
- sumCalculatedTotalCost: metric.totalCost,
- }));
- },
- });
+ return metrics.map((metric) => ({
+ userId: metric.userId,
+ firstTrace: metric.minTimestamp,
+ lastTrace: metric.maxTimestamp,
+ totalPromptTokens: BigInt(metric.inputUsage),
+ totalCompletionTokens: BigInt(metric.outputUsage),
+ totalTokens: BigInt(metric.totalUsage),
+ totalObservations: BigInt(metric.observationCount),
+ totalTraces: BigInt(metric.traceCount),
+ sumCalculatedTotalCost: metric.totalCost,
+ }));
}),
byId: protectedProjectProcedure
@@ -212,76 +97,21 @@ export const userRouter = createTRPCRouter({
queryClickhouse: z.boolean().default(false),
}),
)
- .query(async ({ input, ctx }) => {
- return measureAndReturnApi({
- input,
- operation: "users.byId",
- user: ctx.session.user,
- pgExecution: async () => {
- const result = await ctx.prisma.$queryRaw<
- {
- userId: string;
- firstTrace: Date;
- lastTrace: Date;
- totalTraces: bigint;
- totalPromptTokens: bigint;
- totalCompletionTokens: bigint;
- totalTokens: bigint;
- totalObservations: bigint;
- sumCalculatedTotalCost: number;
- }[]
- >`
- SELECT t.user_id "userId",
- min(t."timestamp") "firstTrace",
- max(t."timestamp") "lastTrace",
- COUNT(distinct t.id)::bigint "totalTraces",
- COALESCE(SUM(o.prompt_tokens), 0)::bigint "totalPromptTokens",
- COALESCE(SUM(o.completion_tokens), 0)::bigint "totalCompletionTokens",
- COALESCE(SUM(o.total_tokens), 0)::bigint "totalTokens",
- COUNT(distinct o.id)::bigint "totalObservations",
- SUM(COALESCE(o.calculated_total_cost, 0)) AS "sumCalculatedTotalCost"
- FROM traces t
- LEFT JOIN observations_view o on o.trace_id = t.id
- WHERE t.user_id is not null
- AND t.project_id = ${input.projectId}
- AND o.project_id = ${input.projectId}
- AND t.user_id = ${input.userId}
- GROUP BY 1
- ORDER BY "totalTokens" DESC
- LIMIT 50
- `;
-
- const res = result.shift();
-
- return {
- userId: input.userId,
- firstTrace: res?.firstTrace,
- lastTrace: res?.lastTrace,
- totalTraces: res?.totalTraces ?? 0,
- totalPromptTokens: res?.totalPromptTokens ?? 0,
- totalCompletionTokens: res?.totalCompletionTokens ?? 0,
- totalTokens: res?.totalTokens ?? 0,
- totalObservations: res?.totalObservations ?? 0,
- sumCalculatedTotalCost: res?.sumCalculatedTotalCost ?? 0,
- };
- },
- clickhouseExecution: async () => {
- const result = (
- await getUserMetrics(input.projectId, [input.userId], [])
- ).shift();
+ .query(async ({ input }) => {
+ const result = (
+ await getUserMetrics(input.projectId, [input.userId], [])
+ ).shift();
- return {
- userId: input.userId,
- firstTrace: result?.minTimestamp,
- lastTrace: result?.maxTimestamp,
- totalTraces: result?.traceCount ?? 0,
- totalPromptTokens: result?.inputUsage ?? 0,
- totalCompletionTokens: result?.outputUsage ?? 0,
- totalTokens: result?.totalUsage ?? 0,
- totalObservations: result?.observationCount ?? 0,
- sumCalculatedTotalCost: result?.totalCost ?? 0,
- };
- },
- });
+ return {
+ userId: input.userId,
+ firstTrace: result?.minTimestamp,
+ lastTrace: result?.maxTimestamp,
+ totalTraces: result?.traceCount ?? 0,
+ totalPromptTokens: result?.inputUsage ?? 0,
+ totalCompletionTokens: result?.outputUsage ?? 0,
+ totalTokens: result?.totalUsage ?? 0,
+ totalObservations: result?.observationCount ?? 0,
+ sumCalculatedTotalCost: result?.totalCost ?? 0,
+ };
}),
});
diff --git a/web/src/server/utils/checkClickhouseAccess.ts b/web/src/server/utils/checkClickhouseAccess.ts
deleted file mode 100644
index 1b6db6be95..0000000000
--- a/web/src/server/utils/checkClickhouseAccess.ts
+++ /dev/null
@@ -1,25 +0,0 @@
-import { env } from "@/src/env.mjs";
-import { type User } from "next-auth";
-
-export const isClickhouseAdminEligible = (user?: User | null) => {
- return (
- user &&
- user.admin &&
- user.admin === true &&
- env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION &&
- ["US", "EU", "STAGING", "DEV"].includes(
- env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION,
- )
- );
-};
-
-export const measureAndReturnApi = async <T, Y>(args: {
- input: T & { queryClickhouse: boolean; projectId?: string };
- user: User | undefined | null;
- operation: string;
- pgExecution: (input: T) => Promise<Y>;
- clickhouseExecution: (input: T) => Promise<Y>;
-}) => {
- const { input, clickhouseExecution } = args;
- return await clickhouseExecution(input);
-};