Skip to content

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

chore: migrate score analytics dashboard to clickhouse (#4196)

Steffen Schmitz7a95b1e1da32
diff --git a/packages/shared/src/server/repositories/dashboards.ts b/packages/shared/src/server/repositories/dashboards.ts
index d0a24d66b7..42ebbcfb4d 100644
--- a/packages/shared/src/server/repositories/dashboards.ts
+++ b/packages/shared/src/server/repositories/dashboards.ts
@@ -496,6 +496,82 @@ export const getModelLatenciesOverTime = async (
}));
};
+export const getNumericScoreTimeSeries = async (
+ projectId: string,
+ filter: FilterState,
+ groupBy: DateTrunc,
+) => {
+ const chFilter = new FilterList(
+ createFilterFromFilterState(filter, dashboardColumnDefinitions),
+ );
+ const chFilterRes = chFilter.apply();
+
+ const query = `
+ SELECT
+ ${selectTimeseriesColumn(groupBy, "s.timestamp", "score_timestamp")},
+ s.name as score_name,
+ AVG(s.value) as avg_value
+ FROM scores s final
+ WHERE s.project_id = {projectId: String}
+ ${chFilterRes?.query ? `AND ${chFilterRes.query}` : ""}
+ GROUP BY score_name, score_timestamp
+ ${orderByTimeSeries(groupBy, "score_timestamp")}
+ `;
+
+ return queryClickhouse<{
+ score_timestamp: Date;
+ score_name: string;
+ avg_value: number;
+ }>({
+ query,
+ params: {
+ projectId,
+ ...(chFilterRes ? chFilterRes.params : {}),
+ },
+ });
+};
+
+export const getCategoricalScoreTimeSeries = async (
+ projectId: string,
+ filter: FilterState,
+ groupBy: DateTrunc | undefined,
+) => {
+ const chFilter = new FilterList(
+ createFilterFromFilterState(filter, dashboardColumnDefinitions),
+ );
+ const chFilterRes = chFilter.apply();
+
+ const query = `
+ SELECT
+ ${groupBy ? selectTimeseriesColumn(groupBy, "s.timestamp", "score_timestamp") + ", " : ""}
+ s.name as score_name,
+ s.data_type as score_data_type,
+ s.source as score_source,
+ s.string_value as score_value,
+ count(s.string_value) as count
+ FROM scores s final
+ WHERE s.project_id = {projectId: String}
+ ${chFilterRes?.query ? `AND ${chFilterRes.query}` : ""}
+ GROUP BY score_name, score_data_type, score_source, score_value ${groupBy ? ", score_timestamp" : ""}
+ ${groupBy ? orderByTimeSeries(groupBy, "score_timestamp") : ""}
+ `;
+
+ return queryClickhouse<{
+ score_timestamp?: Date;
+ score_name: string;
+ score_data_type: string;
+ score_source: string;
+ score_value: string;
+ count: number;
+ }>({
+ query,
+ params: {
+ projectId,
+ ...(chFilterRes ? chFilterRes.params : {}),
+ },
+ });
+};
+
const orderByTimeSeries = (dateTrunc: DateTrunc, col: string) => {
let interval;
switch (dateTrunc) {
diff --git a/packages/shared/src/server/repositories/scores.ts b/packages/shared/src/server/repositories/scores.ts
index e098bdd02f..2b7218f9a6 100644
--- a/packages/shared/src/server/repositories/scores.ts
+++ b/packages/shared/src/server/repositories/scores.ts
@@ -12,7 +12,10 @@ import {
getProjectIdDefaultFilter,
} from "../queries/clickhouse-sql/factory";
import { OrderByState } from "../../interfaces/orderBy";
-import { scoresTableUiColumnDefinitions } from "../../tableDefinitions";
+import {
+ dashboardColumnDefinitions,
+ scoresTableUiColumnDefinitions,
+} from "../../tableDefinitions";
import { orderByToClickhouseSql } from "../queries/clickhouse-sql/orderby-factory";
import { convertToScore } from "./scores_converters";
@@ -382,7 +385,6 @@ export const getScoresUiGeneric = async <T>(props: {
${scoresFilterRes?.query ? `AND ${scoresFilterRes.query}` : ""}
${orderByToClickhouseSql(orderBy ?? null, scoresTableUiColumnDefinitions)}
${limit !== undefined && offset !== undefined ? `limit {limit: Int32} offset {offset: Int32}` : ""}
-
`;
const rows = await queryClickhouse<T>({
@@ -471,3 +473,31 @@ export const deleteScoresByTraceIds = async (
},
});
};
+
+export const getNumericScoreHistogram = async (
+ projectId: string,
+ filter: FilterState,
+ limit: number,
+) => {
+ const chFilter = new FilterList(
+ createFilterFromFilterState(filter, dashboardColumnDefinitions),
+ );
+ const chFilterRes = chFilter.apply();
+
+ const query = `
+ select s.value
+ from scores s final
+ WHERE s.project_id = {projectId: String}
+ ${chFilterRes?.query ? `AND ${chFilterRes.query}` : ""}
+ ${limit !== undefined ? `limit {limit: Int32}` : ""}
+ `;
+
+ return queryClickhouse<{ value: number }>({
+ query,
+ params: {
+ projectId,
+ limit,
+ ...(chFilterRes ? chFilterRes.params : {}),
+ },
+ });
+};
diff --git a/packages/shared/src/tableDefinitions/mapDashboards.ts b/packages/shared/src/tableDefinitions/mapDashboards.ts
index a285cc67d8..52520c4e28 100644
--- a/packages/shared/src/tableDefinitions/mapDashboards.ts
+++ b/packages/shared/src/tableDefinitions/mapDashboards.ts
@@ -19,12 +19,24 @@ export const dashboardColumnDefinitions: UiColumnMapping[] = [
clickhouseTableName: "traces",
clickhouseSelect: 't."timestamp"',
},
+ {
+ clickhouseTableName: "scores",
+ clickhouseSelect: "name",
+ uiTableId: "scoreName",
+ uiTableName: "Score Name",
+ },
{
clickhouseTableName: "scores",
clickhouseSelect: "timestamp",
uiTableId: "scoreTimestamp",
uiTableName: "Score Timestamp",
},
+ {
+ clickhouseTableName: "scores",
+ clickhouseSelect: "source",
+ uiTableId: "scoreSource",
+ uiTableName: "Score Source",
+ },
{
clickhouseTableName: "scores",
clickhouseSelect: "data_type",
diff --git a/web/src/features/dashboard/components/score-analytics/CategoricalScoreChart.tsx b/web/src/features/dashboard/components/score-analytics/CategoricalScoreChart.tsx
index f0cf82fd66..58c1253a0f 100644
--- a/web/src/features/dashboard/components/score-analytics/CategoricalScoreChart.tsx
+++ b/web/src/features/dashboard/components/score-analytics/CategoricalScoreChart.tsx
@@ -19,6 +19,7 @@ import {
transformCategoricalScoresToChartData,
} from "@/src/features/dashboard/lib/score-analytics-utils";
import { NoDataOrLoading } from "@/src/components/NoDataOrLoading";
+import { useClickhouse } from "@/src/components/layouts/ClickhouseAdminToggle";
export function CategoricalScoreChart(props: {
projectId: string;
@@ -85,6 +86,8 @@ export function CategoricalScoreChart(props: {
]
: []),
],
+ queryClickhouse: useClickhouse(),
+ queryName: "categorical-score-chart",
},
{
trpc: {
diff --git a/web/src/features/dashboard/components/score-analytics/NumericScoreHistogram.tsx b/web/src/features/dashboard/components/score-analytics/NumericScoreHistogram.tsx
index e6266c1e71..91a5840648 100644
--- a/web/src/features/dashboard/components/score-analytics/NumericScoreHistogram.tsx
+++ b/web/src/features/dashboard/components/score-analytics/NumericScoreHistogram.tsx
@@ -12,6 +12,7 @@ import { Card } from "@/src/components/ui/card";
import { getColorsForCategories } from "@/src/features/dashboard/utils/getColorsForCategories";
import { padChartData } from "@/src/features/dashboard/lib/score-analytics-utils";
import { NoDataOrLoading } from "@/src/components/NoDataOrLoading";
+import { useClickhouse } from "@/src/components/layouts/ClickhouseAdminToggle";
export function NumericScoreHistogram(props: {
projectId: string;
@@ -47,6 +48,7 @@ export function NumericScoreHistogram(props: {
},
],
limit: 10000,
+ queryClickhouse: useClickhouse(),
},
{
trpc: {
diff --git a/web/src/features/dashboard/components/score-analytics/NumericScoreTimeSeriesChart.tsx b/web/src/features/dashboard/components/score-analytics/NumericScoreTimeSeriesChart.tsx
index b69b3a420a..ce9c2195b3 100644
--- a/web/src/features/dashboard/components/score-analytics/NumericScoreTimeSeriesChart.tsx
+++ b/web/src/features/dashboard/components/score-analytics/NumericScoreTimeSeriesChart.tsx
@@ -19,6 +19,7 @@ import {
} from "@/src/utils/date-range-utils";
import React, { useMemo } from "react";
import { NoDataOrLoading } from "@/src/components/NoDataOrLoading";
+import { useClickhouse } from "@/src/components/layouts/ClickhouseAdminToggle";
export function NumericScoreTimeSeriesChart(props: {
projectId: string;
@@ -74,6 +75,8 @@ export function NumericScoreTimeSeriesChart(props: {
column: "scoreDataType",
},
],
+ queryClickhouse: useClickhouse(),
+ queryName: "numeric-score-time-series",
},
{
trpc: {
diff --git a/web/src/features/dashboard/lib/score-analytics-utils.ts b/web/src/features/dashboard/lib/score-analytics-utils.ts
index e1a6aebe5f..b425d4dd56 100644
--- a/web/src/features/dashboard/lib/score-analytics-utils.ts
+++ b/web/src/features/dashboard/lib/score-analytics-utils.ts
@@ -108,8 +108,10 @@ function groupCategoricalScoreDataByTimestamp(
): Record<string, DatabaseRow[]> {
return data.reduce(
(acc, row) => {
- const timestamp = row[scoreTimestampAccessor];
- if (!(timestamp instanceof Date)) return acc;
+ if (row[scoreTimestampAccessor] === null) {
+ return acc;
+ }
+ const timestamp = new Date(row[scoreTimestampAccessor] ?? new Date());
const key = convertDateToStringTimestamp(timestamp);
if (!acc[key]) {
acc[key] = [];
diff --git a/web/src/features/dashboard/server/dashboard-router.ts b/web/src/features/dashboard/server/dashboard-router.ts
index 7332b91966..2754f046f9 100644
--- a/web/src/features/dashboard/server/dashboard-router.ts
+++ b/web/src/features/dashboard/server/dashboard-router.ts
@@ -26,6 +26,9 @@ import {
getModelLatenciesOverTime,
getObservationLatencies,
getTracesLatencies,
+ getNumericScoreHistogram,
+ getNumericScoreTimeSeries,
+ getCategoricalScoreTimeSeries,
} from "@langfuse/shared/src/server";
import { type DatabaseRow } from "@/src/server/api/services/queryBuilder";
import { dashboardColumnDefinitions } from "@langfuse/shared";
@@ -53,6 +56,8 @@ export const dashboardRouter = createTRPCRouter({
"observation-latencies-aggregated",
"traces-latencies-aggregated",
"model-latencies-over-time",
+ "numeric-score-time-series",
+ "categorical-score-chart",
])
.nullish(),
}),
@@ -237,6 +242,43 @@ export const dashboardRouter = createTRPCRouter({
percentile95Duration: row.p95,
percentile99Duration: row.p99,
})) as DatabaseRow[];
+ case "numeric-score-time-series":
+ const dateTruncNumericScoreTimeSeries = extractTimeSeries(
+ input.groupBy,
+ );
+ if (!dateTruncNumericScoreTimeSeries) {
+ return [];
+ }
+ const numericScoreTimeSeries = await getNumericScoreTimeSeries(
+ input.projectId,
+ input.filter ?? [],
+ dateTruncNumericScoreTimeSeries,
+ );
+ return numericScoreTimeSeries.map((row) => ({
+ scoreTimestamp: row.score_timestamp,
+ scoreName: row.score_name,
+ avgValue: row.avg_value,
+ })) as DatabaseRow[];
+ case "categorical-score-chart":
+ const dateTruncCategoricalScoreTimeSeries = extractTimeSeries(
+ input.groupBy,
+ );
+ const categoricalScoreTimeSeries =
+ await getCategoricalScoreTimeSeries(
+ input.projectId,
+ input.filter ?? [],
+ dateTruncCategoricalScoreTimeSeries,
+ );
+ return categoricalScoreTimeSeries.map((row) => ({
+ ...(row.score_timestamp
+ ? { scoreTimestamp: row.score_timestamp }
+ : {}),
+ scoreName: row.score_name || null,
+ scoreDataType: row.score_data_type || null,
+ scoreSource: row.score_source || null,
+ stringValue: row.score_value || null,
+ countStringValue: Number(row.count) || 0,
+ })) as DatabaseRow[];
default:
throw new TRPCError({
@@ -252,9 +294,32 @@ export const dashboardRouter = createTRPCRouter({
sqlInterface.extend({
projectId: z.string(),
filter: filterInterface.optional(),
+ queryClickhouse: z.boolean().default(false),
}),
)
.query(async ({ input, ctx }) => {
+ if (
+ input.queryClickhouse &&
+ !isClickhouseAdminEligible(ctx.session.user)
+ ) {
+ throw new TRPCError({
+ code: "UNAUTHORIZED",
+ message: "Not eligible to query clickhouse",
+ });
+ }
+
+ if (
+ input.queryClickhouse ||
+ env.LANGFUSE_READ_DASHBOARDS_FROM_CLICKHOUSE === "true"
+ ) {
+ const data = await getNumericScoreHistogram(
+ input.projectId,
+ input.filter ?? [],
+ input.limit ?? 10000,
+ );
+ return createHistogramData(data);
+ }
+
const data = await executeQuery(ctx.prisma, input.projectId, input);
return createHistogramData(data);
}),