Skip to content

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

feat: build scores table for clickhouse (#4092)

Max Deichmann9481c3b4242a
diff --git a/packages/shared/src/server/repositories/scores.ts b/packages/shared/src/server/repositories/scores.ts
index a6732a2fd0..f25d9a9fdf 100644
--- a/packages/shared/src/server/repositories/scores.ts
+++ b/packages/shared/src/server/repositories/scores.ts
@@ -1,8 +1,18 @@
-import { ScoreDataType, ScoreSource } from "@prisma/client";
-import { queryClickhouse } from "./clickhouse";
+import { Score, ScoreDataType, ScoreSource } from "@prisma/client";
+import {
+ parseClickhouseUTCDateTimeFormat,
+ queryClickhouse,
+} from "./clickhouse";
import { FilterList } from "../queries/clickhouse-filter/clickhouse-filter";
import { FilterState } from "../../types";
-import { createFilterFromFilterState } from "../queries/clickhouse-filter/factory";
+import {
+ createFilterFromFilterState,
+ getProjectIdDefaultFilter,
+} from "../queries/clickhouse-filter/factory";
+import { OrderByState } from "../../interfaces/orderBy";
+import { scoresTableUiColumnDefinitions } from "../../tableDefinitions";
+import { orderByToClickhouseSql } from "../queries/clickhouse-filter/orderby-factory";
+import { string } from "zod";
export type FetchScoresReturnType = {
id: string;
@@ -177,3 +187,193 @@ export const getScoresGroupedByName = async (
return rows;
};
+
+export const getScoresUiCount = async (props: {
+ projectId: string;
+ filter: FilterState;
+ orderBy: OrderByState;
+ limit?: number;
+ offset?: number;
+}) => {
+ const rows = await getScoresUiGeneric<{ count: string }>({
+ select: `
+ count(*) as count
+ `,
+ ...props,
+ });
+
+ return Number(rows[0].count);
+};
+
+export type ScoreUiTableRow = Score & {
+ traceName: string | null;
+ traceUserId: string | null;
+ traceTags: Array<string> | null;
+};
+
+export const getScoresUiTable = async (props: {
+ projectId: string;
+ filter: FilterState;
+ orderBy: OrderByState;
+ limit?: number;
+ offset?: number;
+}): Promise<ScoreUiTableRow[]> => {
+ const rows = await getScoresUiGeneric<{
+ id: string;
+ project_id: string;
+ name: string;
+ value: number;
+ string_value: string | null;
+ timestamp: string;
+ source: string;
+ data_type: string;
+ comment: string | null;
+ trace_id: string;
+ observation_id: string | null;
+ author_user_id: string | null;
+ user_id: string | null;
+ trace_name: string | null;
+ trace_tags: Array<string> | null;
+ job_configuration_id: string | null;
+ author_user_image: string | null;
+ author_user_name: string | null;
+ config_id: string | null;
+ queue_id: string | null;
+ created_at: string;
+ updated_at: string;
+ }>({
+ select: `
+ s.id,
+ s.project_id,
+ s.name,
+ s.value,
+ s.string_value,
+ s.timestamp,
+ s.source,
+ s.data_type,
+ s.comment,
+ s.trace_id,
+ s.observation_id,
+ s.author_user_id,
+ t.user_id,
+ t.name,
+ t.tags,
+ s.created_at,
+ s.updated_at,
+ s.source,
+ s.config_id,
+ s.queue_id,
+ t.user_id,
+ t.name as trace_name,
+ t.tags as trace_tags
+ `,
+ ...props,
+ });
+
+ return rows.map((row) => ({
+ projectId: row.project_id,
+ authorUserId: row.author_user_id,
+ traceId: row.trace_id,
+ observationId: row.observation_id,
+ traceUserId: row.user_id,
+ traceName: row.trace_name,
+ traceTags: row.trace_tags,
+ configId: row.config_id,
+ queueId: row.queue_id,
+ createdAt: parseClickhouseUTCDateTimeFormat(row.created_at),
+ updatedAt: parseClickhouseUTCDateTimeFormat(row.updated_at),
+ stringValue: row.string_value,
+ comment: row.comment,
+ dataType: row.data_type as ScoreDataType,
+ source: row.source as ScoreSource,
+ name: row.name,
+ value: row.value,
+ timestamp: parseClickhouseUTCDateTimeFormat(row.timestamp),
+ id: row.id,
+ }));
+};
+
+export const getScoresUiGeneric = async <T>(props: {
+ select: string;
+ projectId: string;
+ filter: FilterState;
+ orderBy: OrderByState;
+ limit?: number;
+ offset?: number;
+}): Promise<T[]> => {
+ const { select, projectId, filter, orderBy, limit, offset } = props;
+
+ const { tracesFilter, scoresFilter, observationsFilter } =
+ getProjectIdDefaultFilter(projectId, { tracesPrefix: "t" });
+
+ scoresFilter.push(
+ ...createFilterFromFilterState(filter, scoresTableUiColumnDefinitions),
+ );
+
+ const scoresFilterRes = scoresFilter.apply();
+
+ const query = `
+ SELECT
+ ${select}
+ FROM scores s final
+ LEFT JOIN traces t ON s.trace_id = t.id AND t.project_id = s.project_id
+ WHERE s.project_id = {projectId: String}
+ ${scoresFilterRes?.query ? `AND ${scoresFilterRes.query}` : ""}
+ ${orderByToClickhouseSql(orderBy ?? null, scoresTableUiColumnDefinitions)}
+ ${limit !== undefined && offset !== undefined ? `limit {limit: Int32} offset {offset: Int32}` : ""}
+
+ `;
+
+ const rows = await queryClickhouse<T>({
+ query: query,
+ params: {
+ projectId: projectId,
+ ...(scoresFilterRes ? scoresFilterRes.params : {}),
+ limit: limit,
+ offset: offset,
+ },
+ });
+
+ return rows;
+};
+
+export const getScoreNames = async (
+ projectId: string,
+ timestampFilter: FilterState,
+) => {
+ const chFilter = new FilterList(
+ createFilterFromFilterState(
+ timestampFilter,
+ scoresTableUiColumnDefinitions,
+ ),
+ );
+ const timestampFilterRes = chFilter.apply();
+
+ const query = `
+ select
+ name,
+ count(*) as count
+ from scores s final
+ WHERE s.project_id = {projectId: String}
+ ${timestampFilterRes?.query ? `AND ${timestampFilterRes.query}` : ""}
+ GROUP BY name
+ ORDER BY count() desc
+ LIMIT 1000;
+ `;
+
+ const rows = await queryClickhouse<{
+ name: string;
+ count: string;
+ }>({
+ query: query,
+ params: {
+ projectId: projectId,
+ ...(timestampFilterRes ? timestampFilterRes.params : {}),
+ },
+ });
+
+ return rows.map((row) => ({
+ name: row.name,
+ count: Number(row.count),
+ }));
+};
diff --git a/packages/shared/src/tableDefinitions/index.ts b/packages/shared/src/tableDefinitions/index.ts
index 904b8f89a1..5dc2262ed6 100644
--- a/packages/shared/src/tableDefinitions/index.ts
+++ b/packages/shared/src/tableDefinitions/index.ts
@@ -3,3 +3,4 @@ export * from "./types";
export * from "./mapObservationsTable";
export * from "./mapTracesTable";
export * from "./mapDashboards";
+export * from "./mapScoresTable";
diff --git a/packages/shared/src/tableDefinitions/mapScoresTable.ts b/packages/shared/src/tableDefinitions/mapScoresTable.ts
new file mode 100644
index 0000000000..a0a9f5a6e2
--- /dev/null
+++ b/packages/shared/src/tableDefinitions/mapScoresTable.ts
@@ -0,0 +1,88 @@
+import { UiColumnMapping } from "./types";
+
+export const scoresTableUiColumnDefinitions: UiColumnMapping[] = [
+ {
+ uiTableName: "ID",
+ uiTableId: "id",
+ clickhouseTableName: "scores",
+ clickhouseSelect: "id",
+ },
+ {
+ uiTableName: "Timestamp",
+ uiTableId: "timestamp",
+ clickhouseTableName: "scores",
+ clickhouseSelect: "timestamp",
+ },
+ {
+ uiTableName: "Trace ID",
+ uiTableId: "traceId",
+ clickhouseTableName: "scores",
+ clickhouseSelect: "trace_id",
+ },
+ {
+ uiTableName: "Observation ID",
+ uiTableId: "observationId",
+ clickhouseTableName: "scores",
+ clickhouseSelect: "observation_id",
+ },
+ {
+ uiTableName: "Name",
+ uiTableId: "name",
+ clickhouseTableName: "scores",
+ clickhouseSelect: "name",
+ },
+ {
+ uiTableName: "Value",
+ uiTableId: "value",
+ clickhouseTableName: "scores",
+ clickhouseSelect: "value",
+ },
+ {
+ uiTableName: "Source",
+ uiTableId: "source",
+ clickhouseTableName: "scores",
+ clickhouseSelect: "source",
+ },
+ {
+ uiTableName: "Comment",
+ uiTableId: "comment",
+ clickhouseTableName: "scores",
+ clickhouseSelect: "comment",
+ },
+ {
+ uiTableName: "Author User ID",
+ uiTableId: "authorUserId",
+ clickhouseTableName: "scores",
+ clickhouseSelect: "author_user_id",
+ },
+ {
+ uiTableName: "Data Type",
+ uiTableId: "dataType",
+ clickhouseTableName: "scores",
+ clickhouseSelect: "data_type",
+ },
+ {
+ uiTableName: "String Value",
+ uiTableId: "stringValue",
+ clickhouseTableName: "scores",
+ clickhouseSelect: "string_value",
+ },
+ {
+ uiTableName: "Trace Name",
+ uiTableId: "trace_name",
+ clickhouseTableName: "traces",
+ clickhouseSelect: "t.name",
+ },
+ {
+ uiTableName: "User ID",
+ uiTableId: "user_id",
+ clickhouseTableName: "traces",
+ clickhouseSelect: "t.user_id",
+ },
+ {
+ uiTableName: "Trace Tags",
+ uiTableId: "trace_tags",
+ clickhouseTableName: "traces",
+ clickhouseSelect: "t.tags",
+ },
+];
diff --git a/web/src/components/table/use-cases/scores.tsx b/web/src/components/table/use-cases/scores.tsx
index 5254b594da..4524622c74 100644
--- a/web/src/components/table/use-cases/scores.tsx
+++ b/web/src/components/table/use-cases/scores.tsx
@@ -27,6 +27,7 @@ import { useQueryParams, withDefault, NumberParam } from "use-query-params";
import TagList from "@/src/features/tag/components/TagList";
import { cn } from "@/src/utils/tailwind";
import useColumnOrder from "@/src/features/column-visibility/hooks/useColumnOrder";
+import { useClickhouse } from "@/src/components/layouts/ClickhouseAdminToggle";
export type ScoresTableRow = {
id: string;
@@ -131,6 +132,7 @@ export default function ScoresTable({
page: 0,
limit: 1,
orderBy: null,
+ queryClickhouse: useClickhouse(),
};
const getAllPayload = {
@@ -138,6 +140,7 @@ export default function ScoresTable({
page: paginationState.pageIndex,
limit: paginationState.pageSize,
orderBy: orderByState,
+ queryClickhouse: useClickhouse(),
};
const scores = api.scores.all.useQuery(getAllPayload);
@@ -151,6 +154,7 @@ export default function ScoresTable({
dateRangeFilter[0]?.type === "datetime"
? dateRangeFilter[0]
: undefined,
+ queryClickhouse: useClickhouse(),
},
{
trpc: {
diff --git a/web/src/server/api/routers/scores.ts b/web/src/server/api/routers/scores.ts
index d410bedbbf..3aaa63f7b2 100644
--- a/web/src/server/api/routers/scores.ts
+++ b/web/src/server/api/routers/scores.ts
@@ -29,8 +29,12 @@ import {
datetimeFilterToPrisma,
datetimeFilterToPrismaSql,
getScoresGroupedByNameSourceType,
+ getScoresUiCount,
+ getScoresUiTable,
orderByToPrismaSql,
tableColumnsToSqlFilterAndPrefix,
+ getScoreNames,
+ getTracesGroupedByTags,
} from "@langfuse/shared/src/server";
import { isClickhouseEligible } from "@/src/server/utils/checkClickhouseAccess";
import { TRPCError } from "@trpc/server";
@@ -44,26 +48,89 @@ const ScoreFilterOptions = z.object({
const ScoreAllOptions = ScoreFilterOptions.extend({
...paginationZod,
});
+type AllScoresReturnType = Score & {
+ traceName: string | null;
+ traceUserId: string | null;
+ traceTags: Array<string> | null;
+ jobConfigurationId: string | null;
+ authorUserImage: string | null;
+ authorUserName: string | null;
+};
export const scoresRouter = createTRPCRouter({
all: protectedProjectProcedure
- .input(ScoreAllOptions)
+ .input(
+ ScoreAllOptions.extend({ queryClickhouse: z.boolean().default(false) }),
+ )
.query(async ({ input, ctx }) => {
+ if (input.queryClickhouse && !isClickhouseEligible(ctx.session.user)) {
+ throw new TRPCError({
+ code: "FORBIDDEN",
+ message: "Clickhouse access is not enabled",
+ });
+ }
+
+ if (input.queryClickhouse) {
+ const clickhouseScoreData = await getScoresUiTable({
+ 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,
+ },
+ }),
+ ]);
+
+ 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,
+ };
+ }),
+ };
+ }
+
const { filterCondition, orderByCondition } =
parseScoresGetAllOptions(input);
- const scores = await ctx.prisma.$queryRaw<
- Array<
- Score & {
- traceName: string | null;
- traceUserId: string | null;
- traceTags: Array<string> | null;
- jobConfigurationId: string | null;
- authorUserImage: string | null;
- authorUserName: string | null;
- }
- >
- >(
+ const scores = await ctx.prisma.$queryRaw<Array<AllScoresReturnType>>(
generateScoresQuery(
Prisma.sql`
s.id,
@@ -98,8 +165,31 @@ export const scoresRouter = createTRPCRouter({
};
}),
countAll: protectedProjectProcedure
- .input(ScoreAllOptions)
+ .input(
+ ScoreAllOptions.extend({ queryClickhouse: z.boolean().default(false) }),
+ )
.query(async ({ input, ctx }) => {
+ if (input.queryClickhouse && !isClickhouseEligible(ctx.session.user)) {
+ throw new TRPCError({
+ code: "FORBIDDEN",
+ message: "Clickhouse access is not enabled",
+ });
+ }
+
+ if (input.queryClickhouse) {
+ const clickhouseScoreData = await getScoresUiCount({
+ projectId: input.projectId,
+ filter: input.filter ?? [],
+ orderBy: input.orderBy,
+ limit: 1,
+ offset: 0,
+ });
+
+ return {
+ totalCount: clickhouseScoreData,
+ };
+ }
+
const { filterCondition } = parseScoresGetAllOptions(input);
const scoresCount = await ctx.prisma.$queryRaw<
@@ -126,10 +216,37 @@ export const scoresRouter = createTRPCRouter({
z.object({
projectId: z.string(),
timestampFilter: timeFilter.optional(),
+ queryClickhouse: z.boolean().default(false),
}),
)
.query(async ({ input, ctx }) => {
const { timestampFilter } = input;
+
+ if (input.queryClickhouse && !isClickhouseEligible(ctx.session.user)) {
+ throw new TRPCError({
+ code: "FORBIDDEN",
+ message: "Clickhouse access is not enabled",
+ });
+ }
+
+ if (input.queryClickhouse) {
+ const [names, tags] = await Promise.all([
+ getScoreNames(
+ input.projectId,
+ timestampFilter ? [timestampFilter] : [],
+ ),
+ getTracesGroupedByTags(
+ input.projectId,
+ timestampFilter ? [timestampFilter] : [],
+ ),
+ ]);
+
+ const res: ScoreOptions = {
+ name: names.map((i) => ({ value: i.name, count: i.count })),
+ tags: tags,
+ };
+ return res;
+ }
const prismaTimestampFilter = timestampFilter
? datetimeFilterToPrisma(timestampFilter)
: {};