Skip to content

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

feat: add generations table clickhouse support (#4015)

Max Deichmannda85e80689b1
diff --git a/packages/shared/src/server/filterToPrisma.ts b/packages/shared/src/server/filterToPrisma.ts
index fd09b804a1..826cb73ec2 100644
--- a/packages/shared/src/server/filterToPrisma.ts
+++ b/packages/shared/src/server/filterToPrisma.ts
@@ -26,7 +26,7 @@ const arrayOperatorReplacements = {
export function tableColumnsToSqlFilterAndPrefix(
filters: FilterState,
tableColumns: ColumnDefinition[],
- table: TableNames
+ table: TableNames,
): Prisma.Sql {
const sql = tableColumnsToSqlFilter(filters, tableColumns, table);
if (sql === Prisma.empty) {
@@ -42,14 +42,14 @@ export function tableColumnsToSqlFilterAndPrefix(
export function tableColumnsToSqlFilter(
filters: FilterState,
tableColumns: ColumnDefinition[],
- table: TableNames
+ table: TableNames,
): Prisma.Sql {
const internalFilters = filters.map((filter) => {
// Get column definition to map column to internal name, e.g. "t.id"
const col = tableColumns.find(
(c) =>
// TODO: Only use id instead of name
- c.name === filter.column || c.id === filter.column
+ c.name === filter.column || c.id === filter.column,
);
if (!col) {
logger.error("Invalid filter column", filter.column);
@@ -71,13 +71,13 @@ export function tableColumnsToSqlFilter(
? Prisma.raw(
arrayOperatorReplacements[
filter.operator as keyof typeof arrayOperatorReplacements
- ]
+ ],
)
: filter.operator in operatorReplacements
? Prisma.raw(
operatorReplacements[
filter.operator as keyof typeof operatorReplacements
- ]
+ ],
)
: Prisma.raw(filter.operator); //checked by zod
@@ -97,13 +97,13 @@ export function tableColumnsToSqlFilter(
break;
case "stringOptions":
valuePrisma = Prisma.sql`(${Prisma.join(
- filter.value.map((v) => Prisma.sql`${v}`)
+ filter.value.map((v) => Prisma.sql`${v}`),
)})`;
break;
case "arrayOptions":
valuePrisma = Prisma.sql`ARRAY[${Prisma.join(
filter.value.map((v) => Prisma.sql`${v}`),
- ", "
+ ", ",
)}] `;
break;
@@ -123,12 +123,12 @@ export function tableColumnsToSqlFilter(
filter.type === "string" || filter.type === "stringObject"
? [
["contains", "does not contain", "ends with"].includes(
- filter.operator
+ filter.operator,
)
? Prisma.raw("'%' || ")
: Prisma.empty,
["contains", "does not contain", "starts with"].includes(
- filter.operator
+ filter.operator,
)
? Prisma.raw(" || '%'")
: Prisma.empty,
@@ -152,7 +152,7 @@ export function tableColumnsToSqlFilter(
const castValueToPostgresTypes = (
column: ColumnDefinition,
- table: TableNames
+ table: TableNames,
) => {
return column.name === "type" &&
(table === "observations" ||
@@ -168,7 +168,7 @@ const dateOperators = filterOperators["datetime"];
export const datetimeFilterToPrismaSql = (
safeColumn: string,
operator: (typeof dateOperators)[number],
- value: Date
+ value: Date,
) => {
if (!dateOperators.includes(operator)) {
throw new Error("Invalid operator: " + operator);
@@ -178,12 +178,12 @@ export const datetimeFilterToPrismaSql = (
}
return Prisma.sql`AND ${Prisma.raw(safeColumn)} ${Prisma.raw(
- operator
+ operator,
)} ${value}::timestamp with time zone at time zone 'UTC'`;
};
export const datetimeFilterToPrisma = (
- timestampFilter: z.infer<typeof timeFilter>
+ timestampFilter: z.infer<typeof timeFilter>,
) => {
const prismaTimestampFilter =
timestampFilter.operator === ">="
diff --git a/packages/shared/src/server/queries/clickhouse-filter/clickhouse-filter.ts b/packages/shared/src/server/queries/clickhouse-filter/clickhouse-filter.ts
index 207cf2a11b..6b9635cd6d 100644
--- a/packages/shared/src/server/queries/clickhouse-filter/clickhouse-filter.ts
+++ b/packages/shared/src/server/queries/clickhouse-filter/clickhouse-filter.ts
@@ -217,6 +217,41 @@ export class ArrayOptionsFilter implements Filter {
}
}
+export class NumberObjectFilter implements Filter {
+ public clickhouseTable: string;
+ protected field: string;
+ protected key: string;
+ protected value: number;
+ protected operator: (typeof filterOperators)["numberObject"][number];
+ protected tablePrefix?: string;
+
+ constructor(opts: {
+ clickhouseTable: string;
+ field: string;
+ operator: (typeof filterOperators)["numberObject"][number];
+ key: string;
+ value: number;
+ tablePrefix?: string;
+ }) {
+ this.clickhouseTable = opts.clickhouseTable;
+ this.field = opts.field;
+ this.value = opts.value;
+ this.operator = opts.operator;
+ this.tablePrefix = opts.tablePrefix;
+ this.key = opts.key;
+ }
+
+ apply(): ClickhouseFilter {
+ const varKeyName = `numberObjectKeyFilter${randomCharacters()}`;
+ const varValueName = `numberObjectValueFilter${randomCharacters()}`;
+ const column = `${this.tablePrefix ? this.tablePrefix + "." : ""}${this.field}`;
+ return {
+ query: `empty(arrayFilter(x -> (((x.1) = {${varKeyName}: String}) AND ((x.2) ${this.operator} {${varValueName}: Decimal})), ${column})) = 0`,
+ params: { [varKeyName]: this.key, [varValueName]: this.value },
+ };
+ }
+}
+
export class BooleanFilter implements Filter {
public clickhouseTable: string;
protected field: string;
diff --git a/packages/shared/src/server/queries/clickhouse-filter/factory.ts b/packages/shared/src/server/queries/clickhouse-filter/factory.ts
index 72f5599d7e..08d38bd3f3 100644
--- a/packages/shared/src/server/queries/clickhouse-filter/factory.ts
+++ b/packages/shared/src/server/queries/clickhouse-filter/factory.ts
@@ -1,6 +1,5 @@
import z from "zod";
import { singleFilter } from "../../../interfaces/filters";
-import { tracesTableUiColumnDefinitions } from "../../../tableDefinitions/mapTracesTable";
import { FilterCondition } from "../../../types";
import { isValidTableName } from "../../clickhouse/schema-utils";
import { logger } from "../../logger";
@@ -13,6 +12,7 @@ import {
NumberFilter,
ArrayOptionsFilter,
BooleanFilter,
+ NumberObjectFilter,
} from "./clickhouse-filter";
export class QueryBuilderError extends Error {
@@ -25,13 +25,13 @@ export class QueryBuilderError extends Error {
// This function ensures that the user only selects valid columns from the clickhouse schema.
// The filter property in this column needs to be zod verified.
// User input for values (e.g. project_id = <value>) are sent to Clickhouse as parameters to prevent SQL injection
-export const createFilterFromFilterState = (filter: FilterCondition[]) => {
+export const createFilterFromFilterState = (
+ filter: FilterCondition[],
+ columnMapping: UiColumnMapping[],
+) => {
return filter.map((frontEndFilter) => {
// checks if the column exists in the clickhouse schema
- const column = matchAndVerifyTracesUiColumn(
- frontEndFilter,
- tracesTableUiColumnDefinitions,
- );
+ const column = matchAndVerifyTracesUiColumn(frontEndFilter, columnMapping);
switch (frontEndFilter.type) {
case "string":
@@ -81,6 +81,16 @@ export const createFilterFromFilterState = (filter: FilterCondition[]) => {
value: frontEndFilter.value,
tablePrefix: column.queryPrefix,
});
+ case "numberObject":
+ return new NumberObjectFilter({
+ clickhouseTable: column.clickhouseTableName,
+ field: column.clickhouseSelect,
+ key: frontEndFilter.key,
+ operator: frontEndFilter.operator,
+ value: frontEndFilter.value,
+ tablePrefix: column.queryPrefix,
+ });
+
default:
throw new QueryBuilderError(
`Invalid filter type: ${frontEndFilter.type}`,
diff --git a/packages/shared/src/server/queries/createGenerationsQuery.ts b/packages/shared/src/server/queries/createGenerationsQuery.ts
index ea2db0ebd1..8047672504 100644
--- a/packages/shared/src/server/queries/createGenerationsQuery.ts
+++ b/packages/shared/src/server/queries/createGenerationsQuery.ts
@@ -9,12 +9,10 @@ import { TableFilters } from "./types";
type AdditionalObservationFields = {
traceName: string | null;
- promptName: string | null;
- promptVersion: string | null;
traceTags: Array<string>;
};
-type FullObservation = AdditionalObservationFields & ObservationView;
+export type FullObservation = AdditionalObservationFields & ObservationView;
export type FullObservations = Array<FullObservation>;
@@ -40,17 +38,17 @@ export function parseGetAllGenerationsInput(filters: TableFilters) {
const filterCondition = tableColumnsToSqlFilterAndPrefix(
filters.filter ?? [],
observationsTableCols,
- "observations"
+ "observations",
);
const orderByCondition = orderByToPrismaSql(
filters.orderBy,
- observationsTableCols
+ observationsTableCols,
);
// to improve query performance, add timeseries filter to observation queries as well
const startTimeFilter = filters.filter?.find(
- (f) => f.column === "Start Time" && f.type === "datetime"
+ (f) => f.column === "Start Time" && f.type === "datetime",
);
const datetimeFilter =
@@ -58,7 +56,7 @@ export function parseGetAllGenerationsInput(filters: TableFilters) {
? datetimeFilterToPrismaSql(
"start_time",
startTimeFilter.operator,
- startTimeFilter.value
+ startTimeFilter.value,
)
: Prisma.empty;
diff --git a/packages/shared/src/server/repositories/index.ts b/packages/shared/src/server/repositories/index.ts
index 147dd5a284..904e3c22ff 100644
--- a/packages/shared/src/server/repositories/index.ts
+++ b/packages/shared/src/server/repositories/index.ts
@@ -1,3 +1,4 @@
export * from "./scores";
export * from "./traces";
export * from "./observations";
+export * from "./types";
diff --git a/packages/shared/src/server/repositories/observations.ts b/packages/shared/src/server/repositories/observations.ts
index cdf53e7a46..66544bc27c 100644
--- a/packages/shared/src/server/repositories/observations.ts
+++ b/packages/shared/src/server/repositories/observations.ts
@@ -16,6 +16,16 @@ import Decimal from "decimal.js";
import { prisma } from "../../db";
import { jsonSchema } from "../../utils/zod";
import { ObservationRecordReadType } from "./definitions";
+import { FilterState } from "../../types";
+import {
+ DateTimeFilter,
+ FilterList,
+ StringFilter,
+} from "../queries/clickhouse-filter/clickhouse-filter";
+import { FullObservations } from "../queries/createGenerationsQuery";
+import { createFilterFromFilterState } from "../queries/clickhouse-filter/factory";
+import { observationsTableUiColumnDefinitions } from "../../tableDefinitions";
+import { TableCount } from "./types";
export const convertObservation = async (
record: ObservationRecordReadType,
@@ -233,3 +243,407 @@ export const getObservationById = async (
}
return mapped.shift() as Observation;
};
+
+export type ObservationTableQuery = {
+ projectId: string;
+ filter: FilterState;
+ limit?: number;
+ offset?: number;
+ selectIOAndMetadata?: boolean;
+};
+
+export type ObservationTableRecord = {
+ id: string;
+ projectId: string;
+ traceId: string;
+ observationCount: number;
+ providedCostDetails: Record<string, number>;
+ costDetails: Record<string, number>;
+ usageDetails: Record<string, number>;
+ providedUsageDetails: Record<string, number>;
+ latencyMs: number;
+ level: ObservationLevel;
+ scoresAvg: Record<string, number>;
+ scoresValues: Record<string, number>;
+};
+
+export type ObservationsTableQueryResult = ObservationRecordReadType & {
+ latency?: string;
+ time_to_first_token?: string;
+ trace_tags?: string[];
+ trace_name?: string;
+ trace_user_id?: string;
+};
+
+export const getObservationsTableCount = async (opts: ObservationTableQuery) =>
+ getObservationsTableInternal<TableCount>({
+ ...opts,
+ select: "count(*) as count",
+ });
+
+export const getObservationsTable = async (
+ opts: ObservationTableQuery,
+): Promise<FullObservations> => {
+ const records =
+ await getObservationsTableInternal<ObservationsTableQueryResult>({
+ ...opts,
+ select: `o.id as id,
+ o.name as name,
+ o."model_parameters" as model_parameters,
+ o.start_time as "start_time",
+ o.end_time as "end_time",
+ o.trace_id as "trace_id",
+ t.name as "trace_name",
+ t.user_id as "trace_user_id",
+ o.completion_start_time as "completion_start_time",
+ o.provided_usage_details as "provided_usage_details",
+ o.usage_details as "usage_details",
+ o.provided_cost_details as "provided_cost_details",
+ o.cost_details as "cost_details",
+ o.level as level,
+ o.status_message as "status_message",
+ o.version as version,
+ t.tags as "trace_tags",
+ o.parent_observation_id as "parent_observation_id",
+ o.created_at as "created_at",
+ o.updated_at as "updated_at",
+ o.provided_model_name as "provided_model_name",
+ o.total_cost as "total_cost",
+ internal_model_id as "internal_model_id",
+ provided_model_name as "provided_model_name",
+ if(isNull(end_time), NULL, date_diff('seconds', start_time, end_time)) as latency,
+ if(isNull(completion_start_time), NULL, date_diff('seconds', start_time, completion_start_time)) as "time_to_first_token"`,
+ });
+ const uniqueModels: string[] = Array.from(
+ new Set(
+ records
+ .map((r) => r.internal_model_id)
+ .filter((r): r is string => Boolean(r)),
+ ),
+ );
+
+ const models =
+ uniqueModels.length > 0
+ ? await prisma.model.findMany({
+ where: {
+ id: {
+ in: uniqueModels,
+ },
+ OR: [{ projectId: opts.projectId }, { projectId: null }],
+ },
+ include: {
+ Price: true,
+ },
+ })
+ : [];
+
+ return records.map((o) => {
+ const model = models.find((p) => p.id === o.internal_model_id);
+ return {
+ id: o.id,
+ type: "GENERATION",
+ name: o.name ?? null,
+ level: o.level as ObservationLevel,
+ version: o.version ?? null,
+ input: o.input ?? null,
+ output: o.output ?? null,
+ metadata: o.metadata,
+ traceId: o.trace_id ?? null,
+ projectId: o.project_id,
+ startTime: parseClickhouseUTCDateTimeFormat(o.start_time),
+ endTime: o.end_time ? parseClickhouseUTCDateTimeFormat(o.end_time) : null,
+ parentObservationId: o.parent_observation_id ?? null,
+ statusMessage: o.status_message ?? null,
+ createdAt: parseClickhouseUTCDateTimeFormat(o.created_at),
+ updatedAt: parseClickhouseUTCDateTimeFormat(o.updated_at),
+ model: o.provided_model_name ?? null,
+ modelParameters: o.model_parameters ?? null,
+ promptTokens: o.usage_details?.input ? Number(o.usage_details?.input) : 0,
+ completionTokens: o.usage_details?.output
+ ? Number(o.usage_details?.output)
+ : 0,
+ totalTokens: o.usage_details?.total ? Number(o.usage_details?.total) : 0,
+ unit: "TOKENS",
+ calculatedInputCost: o.cost_details?.input
+ ? new Decimal(o.cost_details.input)
+ : null,
+ calculatedOutputCost: o.cost_details?.output
+ ? new Decimal(o.cost_details.output)
+ : null,
+ calculatedTotalCost: o.total_cost ? new Decimal(o.total_cost) : null,
+ completionStartTime: o.completion_start_time
+ ? parseClickhouseUTCDateTimeFormat(o.completion_start_time)
+ : null,
+ latency: o.latency ? Number(o.latency) : null,
+ timeToFirstToken: o.time_to_first_token
+ ? Number(o.time_to_first_token)
+ : null,
+ promptId: o.prompt_id ?? null,
+ promptName: o.prompt_name ?? null,
+ promptVersion: o.prompt_version ?? null,
+ modelId: o.internal_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,
+ traceName: o.trace_name ?? null,
+ traceTags: o.trace_tags ?? [],
+ userId: o.trace_user_id ?? null,
+ };
+ });
+};
+
+const getObservationsTableInternal = async <T>(
+ opts: ObservationTableQuery & { select: string },
+): Promise<Array<T>> => {
+ const { projectId, filter, selectIOAndMetadata, limit, offset } = opts;
+
+ const selectString = selectIOAndMetadata
+ ? `
+ ${opts.select},
+ ${selectIOAndMetadata ? `o.input, o.output, o.metadata` : ""}
+ `
+ : opts.select;
+
+ const scoresFilter = new FilterList([
+ new StringFilter({
+ clickhouseTable: "scores",
+ field: "project_id",
+ operator: "=",
+ value: projectId,
+ }),
+ ]);
+
+ const timeFilter = opts.filter.find(
+ (f) =>
+ f.column === "Start Time" && (f.operator === ">=" || f.operator === ">"),
+ );
+ timeFilter
+ ? scoresFilter.push(
+ new DateTimeFilter({
+ clickhouseTable: "scores",
+ field: "timestamp",
+ operator: ">=",
+ value: timeFilter.value as Date,
+ }),
+ )
+ : undefined;
+
+ const observationsFilter = new FilterList([
+ new StringFilter({
+ clickhouseTable: "observations",
+ field: "project_id",
+ operator: "=",
+ value: projectId,
+ tablePrefix: "o",
+ }),
+ ]);
+
+ observationsFilter.push(
+ ...createFilterFromFilterState(
+ filter,
+ observationsTableUiColumnDefinitions,
+ ),
+ );
+
+ const appliedScoresFilter = scoresFilter.apply();
+ const appliedObservationsFilter = observationsFilter.apply();
+
+ const query = `
+ WITH scores_avg AS (
+ SELECT
+ trace_id,
+ observation_id,
+ groupArray(tuple(name, avg_value)) AS "scores_avg"
+ FROM (
+ SELECT
+ trace_id,
+ observation_id,
+ name,
+ avg(value) avg_value,
+ comment
+ FROM
+ scores final
+ WHERE ${appliedScoresFilter.query}
+ GROUP BY
+ trace_id,
+ observation_id,
+ name,
+ comment
+ ORDER BY
+ trace_id
+ ) tmp
+ GROUP BY
+ trace_id,
+ observation_id
+ )
+ SELECT
+ ${selectString}
+ FROM observations o FINAL
+ LEFT JOIN traces t FINAL ON t.id = o.trace_id AND t.project_id = o.project_id
+ LEFT JOIN scores_avg AS s_avg ON s_avg.trace_id = t.id and s_avg.observation_id = o.id
+ WHERE ${appliedObservationsFilter.query}
+ ${limit !== undefined && offset !== undefined ? `LIMIT ${limit} OFFSET ${offset}` : ""};`;
+
+ const res = await queryClickhouse<T>({
+ query,
+ params: {
+ ...appliedScoresFilter.params,
+ ...appliedObservationsFilter.params,
+ },
+ });
+ return res;
+};
+
+export const getObservationsGroupedByModel = async (
+ projectId: string,
+ filter: FilterState,
+) => {
+ const observationsFilter = new FilterList([
+ new StringFilter({
+ clickhouseTable: "observations",
+ field: "project_id",
+ operator: "=",
+ value: projectId,
+ tablePrefix: "o",
+ }),
+ ]);
+
+ observationsFilter.push(
+ ...createFilterFromFilterState(
+ filter,
+ observationsTableUiColumnDefinitions,
+ ),
+ );
+
+ const appliedObservationsFilter = observationsFilter.apply();
+
+ const query = `
+
+ SELECT
+ o.provided_model_name as name
+ FROM observations o FINAL
+ WHERE ${appliedObservationsFilter.query}
+ GROUP BY o.provided_model_name
+ ORDER BY count() DESC
+ LIMIT 1000;
+ `;
+
+ const res = await queryClickhouse<{ name: string }>({
+ query,
+ params: {
+ ...appliedObservationsFilter.params,
+ },
+ });
+ return res.map((r) => ({ model: r.name }));
+};
+
+export const getObservationsGroupedByName = async (
+ projectId: string,
+ filter: FilterState,
+) => {
+ const observationsFilter = new FilterList([
+ new StringFilter({
+ clickhouseTable: "observations",
+ field: "project_id",
+ operator: "=",
+ value: projectId,
+ tablePrefix: "o",
+ }),
+ ]);
+
+ observationsFilter.push(
+ ...createFilterFromFilterState(
+ filter,
+ observationsTableUiColumnDefinitions,
+ ),
+ );
+
+ const appliedObservationsFilter = observationsFilter.apply();
+
+ const query = `
+
+ SELECT
+ o.name as name
+ FROM observations o FINAL
+ WHERE ${appliedObservationsFilter.query}
+ GROUP BY o.name
+ ORDER BY count() DESC
+ LIMIT 1000;
+ `;
+
+ const res = await queryClickhouse<{ name: string }>({
+ query,
+ params: {
+ ...appliedObservationsFilter.params,
+ },
+ });
+ return res;
+};
+
+export const getObservationsGroupedByPromptName = async (
+ projectId: string,
+ filter: FilterState,
+) => {
+ const observationsFilter = new FilterList([
+ new StringFilter({
+ clickhouseTable: "observations",
+ field: "project_id",
+ operator: "=",
+ value: projectId,
+ tablePrefix: "o",
+ }),
+ ]);
+
+ observationsFilter.push(
+ ...createFilterFromFilterState(
+ filter,
+ observationsTableUiColumnDefinitions,
+ ),
+ );
+
+ const appliedObservationsFilter = observationsFilter.apply();
+
+ const query = `
+ SELECT
+ o.prompt_id as id
+ FROM observations o FINAL
+ WHERE ${appliedObservationsFilter.query}
+ AND o.type = 'GENERATION'
+ AND o.prompt_id IS NOT NULL
+ GROUP BY o.prompt_id
+ ORDER BY count() DESC
+ LIMIT 1000;
+ `;
+
+ const res = await queryClickhouse<{ id: string }>({
+ query,
+ params: {
+ ...appliedObservationsFilter.params,
+ },
+ });
+
+ const prompts = res.map((r) => r.id).filter((r): r is string => Boolean(r));
+
+ const pgPrompts =
+ prompts.length > 0
+ ? await prisma.prompt.findMany({
+ select: {
+ id: true,
+ name: true,
+ },
+ where: {
+ id: {
+ in: prompts,
+ },
+ projectId,
+ },
+ })
+ : [];
+
+ return pgPrompts.map((p) => ({
+ promptName: p.name,
+ }));
+};
diff --git a/packages/shared/src/server/repositories/scores.ts b/packages/shared/src/server/repositories/scores.ts
index 98bf42f41a..bd8e7a2e24 100644
--- a/packages/shared/src/server/repositories/scores.ts
+++ b/packages/shared/src/server/repositories/scores.ts
@@ -75,6 +75,34 @@ export const getScoresForTraces = async (
return rows.map(convertToScore);
};
+export const getScoresForObservations = async (
+ projectId: string,
+ observationIds: string[],
+ limit?: number,
+ offset?: number,
+) => {
+ const query = `
+ select
+ *
+ from scores s final
+ WHERE s.project_id = {projectId: String}
+ AND s.observation_id IN ({observationIds: Array(String)})
+ ${limit !== undefined && offset !== undefined ? `limit {limit: Int32} offset {offset: Int32}` : ""}
+ `;
+
+ const rows = await queryClickhouse<FetchScoresReturnType>({
+ query: query,
+ params: {
+ projectId: projectId,
+ observationIds: observationIds,
+ limit: limit,
+ offset: offset,
+ },
+ });
+
+ return rows.map(convertToScore);
+};
+
export const getScoresGroupedByNameSourceType = async (projectId: string) => {
const query = `
select
@@ -111,7 +139,13 @@ export const getScoresGroupedByName = async (
timestampFilter?: FilterState,
) => {
const chFilter = timestampFilter
- ? createFilterFromFilterState(timestampFilter)
+ ? createFilterFromFilterState(timestampFilter, [
+ {
+ uiTableName: "Timestamp",
+ clickhouseTableName: "scores",
+ clickhouseSelect: "timestamp",
+ },
+ ])
: undefined;
const timestampFilterRes = chFilter
@@ -120,7 +154,7 @@ export const getScoresGroupedByName = async (
const query = `
select
- name as value
+ name as name
from scores s final
WHERE s.project_id = {projectId: String}
AND has(['NUMERIC', 'BOOLEAN'], s.data_type)
diff --git a/packages/shared/src/server/repositories/traces.ts b/packages/shared/src/server/repositories/traces.ts
index 0392929384..0ead0ff332 100644
--- a/packages/shared/src/server/repositories/traces.ts
+++ b/packages/shared/src/server/repositories/traces.ts
@@ -11,6 +11,8 @@ import { FilterState } from "../../types";
import { logger } from "../logger";
import { FilterList } from "../queries/clickhouse-filter/clickhouse-filter";
import { TraceRecordReadType } from "./definitions";
+import { tracesTableUiColumnDefinitions } from "../../tableDefinitions/mapTracesTable";
+import { TableCount } from "./types";
const convertClickhouseToDomain = (record: TraceRecordReadType): Trace => {
return {
@@ -57,10 +59,6 @@ export type TracesTableReturnType = Pick<
scores_avg: Array<{ name: string; avg_value: number }>;
};
-export type TableCount = {
- count: number;
-};
-
export const getTracesTableCount = async (
projectId: string,
filter: FilterState,
@@ -124,7 +122,9 @@ const getTracesTableGeneric = async <T>(
const { tracesFilter, scoresFilter, observationsFilter } =
getProjectIdDefaultFilter(projectId, { tracesPrefix: "t" });
- tracesFilter.push(...createFilterFromFilterState(filter));
+ tracesFilter.push(
+ ...createFilterFromFilterState(filter, tracesTableUiColumnDefinitions),
+ );
const tracesFilterRes = tracesFilter.apply();
const scoresAvgFilterRes = scoresFilter.apply();
@@ -216,7 +216,10 @@ export const getTracesGroupedByName = async (
timestampFilter?: FilterState,
) => {
const chFilter = timestampFilter
- ? createFilterFromFilterState(timestampFilter)
+ ? createFilterFromFilterState(
+ timestampFilter,
+ tracesTableUiColumnDefinitions,
+ )
: undefined;
const timestampFilterRes = chFilter
@@ -228,6 +231,7 @@ export const getTracesGroupedByName = async (
name as value
from traces t final
WHERE t.project_id = {projectId: String}
+ AND t.name IS NOT NULL
${timestampFilterRes ? `AND ${timestampFilterRes.query}` : ""}
GROUP BY name
ORDER BY name desc
@@ -252,7 +256,10 @@ export const getTracesGroupedByTags = async (
timestampFilter?: FilterState,
) => {
const chFilter = timestampFilter
- ? createFilterFromFilterState(timestampFilter)
+ ? createFilterFromFilterState(
+ timestampFilter,
+ tracesTableUiColumnDefinitions,
+ )
: undefined;
const timestampFilterRes = chFilter
diff --git a/packages/shared/src/server/repositories/types.ts b/packages/shared/src/server/repositories/types.ts
new file mode 100644
index 0000000000..9c62aeeebb
--- /dev/null
+++ b/packages/shared/src/server/repositories/types.ts
@@ -0,0 +1,3 @@
+export type TableCount = {
+ count: number;
+};
diff --git a/packages/shared/src/tableDefinitions/index.ts b/packages/shared/src/tableDefinitions/index.ts
index 10d2a85b2e..3125346496 100644
--- a/packages/shared/src/tableDefinitions/index.ts
+++ b/packages/shared/src/tableDefinitions/index.ts
@@ -1,2 +1,4 @@
export * from "./sessionsView";
export * from "./types";
+export * from "./mapObservationsTable";
+export * from "./mapTracesTable";
diff --git a/packages/shared/src/tableDefinitions/mapObservationsTable.ts b/packages/shared/src/tableDefinitions/mapObservationsTable.ts
new file mode 100644
index 0000000000..fea3d57a6e
--- /dev/null
+++ b/packages/shared/src/tableDefinitions/mapObservationsTable.ts
@@ -0,0 +1,147 @@
+// This structure is maintained to relate the frontend table definitions with the clickhouse table definitions.
+// The frontend only sends the column names to the backend. This needs to be changed in the future to send column IDs.
+
+import { UiColumnMapping } from "./types";
+
+export const observationsTableUiColumnDefinitions: UiColumnMapping[] = [
+ {
+ uiTableName: "ID",
+ clickhouseTableName: "observations",
+ clickhouseSelect: 'o."id"',
+ },
+ {
+ uiTableName: "Name",
+ clickhouseTableName: "observations",
+ clickhouseSelect: 'o."name"',
+ },
+ {
+ uiTableName: "Trace ID",
+ clickhouseTableName: "observations",
+ clickhouseSelect: 'o."trace_id"',
+ },
+ {
+ uiTableName: "Trace Name",
+ clickhouseTableName: "observations",
+ clickhouseSelect: 'o."trace_name"',
+ },
+ {
+ uiTableName: "User ID",
+ clickhouseTableName: "traces",
+ clickhouseSelect: 't."trace_user_id"',
+ },
+ {
+ uiTableName: "Start Time",
+ clickhouseTableName: "observations",
+ clickhouseSelect: 'o."start_time"',
+ },
+ {
+ uiTableName: "End Time",
+ clickhouseTableName: "observations",
+ clickhouseSelect: 'o."end_time"',
+ },
+ {
+ uiTableName: "Time To First Token (s)",
+ clickhouseTableName: "observations",
+ clickhouseSelect:
+ "if(isNull(completion_start_time), NULL, date_diff('seconds', start_time, completion_start_time))}",
+ },
+ {
+ uiTableName: "Latency (s)",
+ clickhouseTableName: "observations",
+ clickhouseSelect:
+ "if(isNull(end_time), NULL, date_diff('seconds', start_time, end_time))",
+ },
+ {
+ uiTableName: "Tokens per second",
+ clickhouseTableName: "observations",
+ clickhouseSelect:
+ " if(isNull(end_time) && mapExists((k, v) -> (k = 'input'), usage_details) != 1, NULL, usage_details['input'] / date_diff('seconds', start_time, end_time)",
+ },
+ {
+ uiTableName: "Input Cost ($)",
+ clickhouseTableName: "observations",
+ clickhouseSelect:
+ "if(mapExists((k, v) -> (k = 'input'), cost_details), cost_details['input'], NULL)",
+ },
+ {
+ uiTableName: "Output Cost ($)",
+ clickhouseTableName: "observations",
+ clickhouseSelect:
+ "if(mapExists((k, v) -> (k = 'output'), cost_details), cost_details['output'], NULL)",
+ },
+ {
+ uiTableName: "Total Cost ($)",
+ clickhouseTableName: "observations",
+ clickhouseSelect:
+ "if(mapExists((k, v) -> (k = 'total'), cost_details), cost_details['total'], NULL)",
+ },
+ {
+ uiTableName: "Level",
+ clickhouseTableName: "observations",
+ clickhouseSelect: 'o."level"',
+ },
+ {
+ uiTableName: "Status Message",
+ clickhouseTableName: "observations",
+ clickhouseSelect: 'o."status_message"',
+ },
+ {
+ uiTableName: "Model",
+ clickhouseTableName: "observations",
+ clickhouseSelect: 'o."model"',
+ },
+ {
+ uiTableName: "Input Tokens",
+ clickhouseTableName: "observations",
+ clickhouseSelect:
+ "if(mapExists((k, v) -> (k = 'input'), usage_details), usage_details['input'], NULL)",
+ },
+ {
+ uiTableName: "Output Tokens",
+ clickhouseTableName: "observations",
+ clickhouseSelect:
+ "if(mapExists((k, v) -> (k = 'output'), usage_details), usage_details['output'], NULL)",
+ },
+ {
+ uiTableName: "Total Tokens",
+ clickhouseTableName: "observations",
+ clickhouseSelect:
+ "if(mapExists((k, v) -> (k = 'total'), usage_details), usage_details['total'], NULL)",
+ },
+ {
+ uiTableName: "Usage",
+ clickhouseTableName: "observations",
+ clickhouseSelect:
+ "if(mapExists((k, v) -> (k = 'total'), usage_details), usage_details['total'], NULL)",
+ },
+ {
+ uiTableName: "Metadata",
+ clickhouseTableName: "observations",
+ clickhouseSelect: 'o."metadata"',
+ },
+ {
+ uiTableName: "Scores",
+ clickhouseTableName: "observations",
+ clickhouseSelect: "s_avg.scores_avg",
+ },
+ {
+ uiTableName: "Version",
+ clickhouseTableName: "observations",
+ clickhouseSelect: 'o."version"',
+ },
+ {
+ uiTableName: "Prompt Name",
+ clickhouseTableName: "prompts",
+ clickhouseSelect: "p.name",
+ },
+ {
+ uiTableName: "Prompt Version",
+ clickhouseTableName: "prompts",
+ clickhouseSelect: "p.version",
+ },
+ {
+ uiTableName: "Trace Tags",
+ clickhouseTableName: "traces",
+ clickhouseSelect: "t.tags",
+ },
+];
diff --git a/web/src/components/table/use-cases/generations.tsx b/web/src/components/table/use-cases/generations.tsx
index 20c15fc2e6..e182a3e302 100644
--- a/web/src/components/table/use-cases/generations.tsx
+++ b/web/src/components/table/use-cases/generations.tsx
@@ -181,6 +181,7 @@ export default function GenerationsTable({
page: 0,
limit: 0,
orderBy: null,
+ queryClickhouse: useClickhouse(),
};
const getAllPayload = {
@@ -202,6 +203,7 @@ export default function GenerationsTable({
projectId,
startTimeFilter:
startTimeFilter?.type === "datetime" ? startTimeFilter : undefined,
+ queryClickhouse: useClickhouse(),
},
{
trpc: {
@@ -745,7 +747,7 @@ export default function GenerationsTable({
},
promptId: generation.promptId ?? undefined,
promptName: generation.promptName ?? undefined,
- promptVersion: generation.promptVersion ?? undefined,
+ promptVersion: generation.promptVersion?.toString() ?? undefined,
traceTags: generation.traceTags ?? undefined,
};
})
@@ -866,6 +868,7 @@ const GenerationsDynamicCell = ({
observationId,
traceId,
projectId,
+ queryClickhouse: useClickhouse(),
},
{
enabled: typeof traceId === "string" && typeof observationId === "string",
diff --git a/web/src/server/api/routers/generations/db/getAllGenerationsSqlQuery.ts b/web/src/server/api/routers/generations/db/getAllGenerationsSqlQuery.ts
index 3630756024..2c47bc6df9 100644
--- a/web/src/server/api/routers/generations/db/getAllGenerationsSqlQuery.ts
+++ b/web/src/server/api/routers/generations/db/getAllGenerationsSqlQuery.ts
@@ -1,10 +1,11 @@
import { aggregateScores } from "@/src/features/scores/lib/aggregateScores";
-import { filterAndValidateDbScoreList } from "@langfuse/shared";
+import { filterAndValidateDbScoreList, type Score } from "@langfuse/shared";
import { prisma } from "@langfuse/shared/src/db";
-
import { type GetAllGenerationsInput } from "../getAllQueries";
import {
createGenerationsQuery,
+ getObservationsTable,
+ getScoresForObservations,
parseGetAllGenerationsInput,
traceException,
type FullObservations,
@@ -14,37 +15,54 @@ import {
export async function getAllGenerations({
input,
selectIOAndMetadata,
+ queryClickhouse,
}: {
input: GetAllGenerationsInput;
selectIOAndMetadata: boolean;
+ queryClickhouse?: boolean;
}) {
const { searchCondition, filterCondition, orderByCondition, datetimeFilter } =
parseGetAllGenerationsInput(input);
- const query = createGenerationsQuery({
- projectId: input.projectId,
- page: input.page,
- limit: input.limit,
- searchCondition,
- filterCondition,
- orderByCondition,
- datetimeFilter,
- selectIOAndMetadata,
- });
+ let generations: FullObservations | IOAndMetadataOmittedObservations;
+ let scores: Score[] = [];
+ if (queryClickhouse) {
+ generations = await getObservationsTable({
+ projectId: input.projectId,
+ filter: input.filter,
+ selectIOAndMetadata: selectIOAndMetadata,
+ offset: input.page * input.limit,
+ limit: input.limit,
+ });
+ scores = await getScoresForObservations(
+ input.projectId,
+ generations.map((gen) => gen.id),
+ );
+ } else {
+ const query = createGenerationsQuery({
+ projectId: input.projectId,
+ page: input.page,
+ limit: input.limit,
+ searchCondition,
+ filterCondition,
+ orderByCondition,
+ datetimeFilter,
+ selectIOAndMetadata,
+ });
- const generations: FullObservations | IOAndMetadataOmittedObservations =
- selectIOAndMetadata
+ generations = selectIOAndMetadata
? ((await prisma.$queryRaw(query)) as FullObservations)
: ((await prisma.$queryRaw(query)) as IOAndMetadataOmittedObservations);
-
- const scores = await prisma.score.findMany({
- where: {
- projectId: input.projectId,
- observationId: {
- in: generations.map((gen) => gen.id),
+ scores = await prisma.score.findMany({
+ where: {
+ projectId: input.projectId,
+ observationId: {
+ in: generations.map((gen) => gen.id),
+ },
},
- },
- });
+ });
+ }
+
const validatedScores = filterAndValidateDbScoreList(scores, traceException);
const fullGenerations = generations.map((generation) => {
diff --git a/web/src/server/api/routers/generations/filterOptionsQuery.ts b/web/src/server/api/routers/generations/filterOptionsQuery.ts
index 75b9041a3f..7ca54dedf2 100644
--- a/web/src/server/api/routers/generations/filterOptionsQuery.ts
+++ b/web/src/server/api/routers/generations/filterOptionsQuery.ts
@@ -6,13 +6,32 @@ import { Prisma } from "@langfuse/shared/src/db";
import {
datetimeFilterToPrisma,
datetimeFilterToPrismaSql,
+ getObservationsGroupedByModel,
+ getObservationsGroupedByName,
+ getObservationsGroupedByPromptName,
+ getScoresGroupedByName,
+ getTracesGroupedByName,
+ getTracesGroupedByTags,
} from "@langfuse/shared/src/server";
+import { isClickhouseEligible } from "@/src/server/utils/checkClickhouseAccess";
+import { TRPCError } from "@trpc/server";
export const filterOptionsQuery = protectedProjectProcedure
.input(
- z.object({ projectId: z.string(), startTimeFilter: timeFilter.optional() }),
+ z.object({
+ projectId: z.string(),
+ startTimeFilter: timeFilter.optional(),
+ queryClickhouse: z.boolean().default(false),
+ }),
)
.query(async ({ input, ctx }) => {
+ if (input.queryClickhouse && !isClickhouseEligible(ctx.session.user)) {
+ throw new TRPCError({
+ code: "UNAUTHORIZED",
+ message: "Not eligible to query clickhouse",
+ });
+ }
+
const { startTimeFilter } = input;
const prismaStartTimeFilter = startTimeFilter
? datetimeFilterToPrisma(startTimeFilter)
@@ -32,42 +51,81 @@ export const filterOptionsQuery = protectedProjectProcedure
)
: Prisma.empty;
+ const getClickhouseTraceName = async (): Promise<
+ Array<{ traceName: string }>
+ > => {
+ const traces = await getTracesGroupedByName(
+ input.projectId,
+ startTimeFilter
+ ? [
+ {
+ column: "Timestamp",
+ operator: startTimeFilter.operator,
+ value: startTimeFilter.value,
+ type: "datetime",
+ },
+ ]
+ : [],
+ );
+ return traces.map((i) => ({ traceName: i.value }));
+ };
+
+ const getClickhouseTraceTags = async (): Promise<
+ Array<{ tag: string }>
+ > => {
+ const traces = await getTracesGroupedByTags(
+ input.projectId,
+ startTimeFilter
+ ? [
+ {
+ column: "Timestamp",
+ operator: startTimeFilter.operator,
+ value: startTimeFilter.value,
+ type: "datetime",
+ },
+ ]
+ : [],
+ );
+ return traces.map((i) => ({ tag: i.value }));
+ };
+
// Score names
const [scores, model, name, promptNames, traceNames, tags] =
- 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`
+ !input.queryClickhouse
+ ? 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
@@ -81,12 +139,12 @@ export const filterOptionsQuery = protectedProjectProcedure
ORDER BY p.name ASC
LIMIT 1000;
`),
- // traceNames
- ctx.prisma.$queryRaw<
- Array<{
- traceName: string | null;
- }>
- >(Prisma.sql`
+ // traceNames
+ ctx.prisma.$queryRaw<
+ Array<{
+ traceName: string | null;
+ }>
+ >(Prisma.sql`
SELECT
t.name "traceName"
FROM traces t
@@ -99,12 +157,12 @@ export const filterOptionsQuery = protectedProjectProcedure
ORDER BY t.name ASC
LIMIT 1000;
`),
- // traceTags
- ctx.prisma.$queryRaw<
- Array<{
- tag: string | null;
- }>
- >(Prisma.sql`
+ // traceTags
+ ctx.prisma.$queryRaw<
+ Array<{
+ tag: string | null;
+ }>
+ >(Prisma.sql`
SELECT
DISTINCT tag
FROM traces t
@@ -116,7 +174,42 @@ export const filterOptionsQuery = protectedProjectProcedure
${rawStartTimeFilter}
LIMIT 1000;
`),
- ]);
+ ])
+ : 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(),
+ ]);
// 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 508503ed46..6dbb4eb7cd 100644
--- a/web/src/server/api/routers/generations/getAllQueries.ts
+++ b/web/src/server/api/routers/generations/getAllQueries.ts
@@ -1,12 +1,13 @@
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 { parseGetAllGenerationsInput } from "@langfuse/shared/src/server";
+import {
+ getObservationsTableCount,
+ parseGetAllGenerationsInput,
+} from "@langfuse/shared/src/server";
import { TRPCError } from "@trpc/server";
import { isClickhouseEligible } from "@/src/server/utils/checkClickhouseAccess";
@@ -41,22 +42,32 @@ export const getAllQueries = {
});
}
- throw new TRPCError({
- code: "NOT_IMPLEMENTED",
- message: "Clickhouse query not implemented yet",
+ const { generations } = await getAllGenerations({
+ input,
+ selectIOAndMetadata: false,
+ queryClickhouse: true,
});
+
+ return {
+ generations: generations,
+ };
}
}),
countAll: protectedProjectProcedure
- .input(GetAllGenerationsInput)
+ .input(
+ GetAllGenerationsInput.extend({
+ queryClickhouse: z.boolean().default(false),
+ }),
+ )
.query(async ({ input, ctx }) => {
- const { searchCondition, filterCondition, datetimeFilter } =
- parseGetAllGenerationsInput(input);
+ if (!input.queryClickhouse) {
+ const { searchCondition, filterCondition, datetimeFilter } =
+ parseGetAllGenerationsInput(input);
- const totalGenerations = await ctx.prisma.$queryRaw<
- Array<{ count: bigint }>
- >(
- Prisma.sql`
+ const totalGenerations = await ctx.prisma.$queryRaw<
+ Array<{ count: bigint }>
+ >(
+ Prisma.sql`
SELECT
count(*)
FROM observations_view o
@@ -87,11 +98,30 @@ export const getAllQueries = {
${searchCondition}
${filterCondition}
`,
- );
+ );
- const count = totalGenerations[0]?.count;
- return {
- totalCount: count ? Number(count) : undefined,
- };
+ const count = totalGenerations[0]?.count;
+ return {
+ totalCount: count ? Number(count) : undefined,
+ };
+ } else {
+ if (!isClickhouseEligible(ctx.session.user)) {
+ throw new TRPCError({
+ code: "UNAUTHORIZED",
+ message: "Not eligible to query clickhouse",
+ });
+ }
+
+ const countQuery = await getObservationsTableCount({
+ projectId: ctx.session.projectId,
+ filter: input.filter ?? [],
+ limit: 1,
+ offset: 0,
+ });
+
+ return {
+ totalCount: countQuery.shift()?.count,
+ };
+ }
}),
};