🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
feat: add clickhouse support for traces filter options endpoint (#3969)
Max Deichmannb9d8b5026e22
diff --git a/packages/shared/src/server/queries/clickhouse-filter/clickhouse-filter.ts b/packages/shared/src/server/queries/clickhouse-filter/clickhouse-filter.tsindex ce69437f00..7e2028feae 100644--- a/packages/shared/src/server/queries/clickhouse-filter/clickhouse-filter.ts+++ b/packages/shared/src/server/queries/clickhouse-filter/clickhouse-filter.ts@@ -155,6 +155,7 @@ export class StringOptionsFilter implements Filter {}}+// this is used when we want to filter multiple values on a clickhouse column which is also an arrayexport class ArrayOptionsFilter implements Filter {public clickhouseTable: string;protected field: string;@@ -182,10 +183,10 @@ export class ArrayOptionsFilter implements Filter {switch (this.operator) {case "any of":- query = `has({${varName}: Array(String)}, ${this.tablePrefix ? this.tablePrefix + "." : ""}${this.field}) = True`;+ query = `hasAny({${varName}: Array(String)}, ${this.tablePrefix ? this.tablePrefix + "." : ""}${this.field}) = True`;break;case "none of":- query = `has({${varName}: Array(String)}, ${this.tablePrefix ? this.tablePrefix + "." : ""}${this.field}) = False`;+ query = `hasAny({${varName}: Array(String)}, ${this.tablePrefix ? this.tablePrefix + "." : ""}${this.field}) = False`;break;case "all of":query = `arrayAll(x -> has({${varName}: Array(String)}, x), ${this.tablePrefix ? this.tablePrefix + "." : ""}${this.field}) = True`;diff --git a/packages/shared/src/server/repositories/clickhouse.ts b/packages/shared/src/server/repositories/clickhouse.tsindex b8311cc290..d18c47f68d 100644--- a/packages/shared/src/server/repositories/clickhouse.ts+++ b/packages/shared/src/server/repositories/clickhouse.ts@@ -89,20 +89,40 @@ export async function queryClickhouse<T>(opts: {params?: Record<string, unknown> | undefined;}) {// https://opentelemetry.io/docs/specs/semconv/database/database-spans/- getCurrentSpan()?.setAttribute("db.query.text", opts.query);+ getCurrentSpan()?.setAttribute("ch.query.text", opts.query);// same logic as for prisma. we want to see queries in developmentif (env.NODE_ENV === "development") {logger.info(`clickhouse:query ${opts.query}`);}- return (- await clickhouseClient.query({- query: opts.query,- format: "JSONEachRow",- query_params: opts.params,- })- ).json<T>();+ const res = await clickhouseClient.query({+ query: opts.query,+ format: "JSONEachRow",+ query_params: opts.params,+ });++ getCurrentSpan()?.setAttribute("ch.queryId", res.query_id);++ // add summary headers to the span. Helps to tune performance+ const summaryHeader = res.response_headers["x-clickhouse-summary"];+ if (summaryHeader) {+ try {+ const summary = Array.isArray(summaryHeader)+ ? JSON.parse(summaryHeader[0])+ : JSON.parse(summaryHeader);+ for (const key in summary) {+ getCurrentSpan()?.setAttribute(`ch.${key}`, summary[key]);+ }+ } catch (error) {+ logger.debug(+ `Failed to parse clickhouse summary header ${summaryHeader}`,+ error,+ );+ }+ }++ return res.json<T>();}export function convertObservations(jsonRecords: unknown[]): ObservationView[] {diff --git a/packages/shared/src/server/repositories/scores.ts b/packages/shared/src/server/repositories/scores.tsindex 0389951c11..5da59a07dd 100644--- a/packages/shared/src/server/repositories/scores.ts+++ b/packages/shared/src/server/repositories/scores.ts@@ -1,5 +1,11 @@import { ScoreDataType, ScoreSource } from "@prisma/client";import { queryClickhouse } from "./clickhouse";+import {+ DateTimeFilter,+ FilterList,+} from "../queries/clickhouse-filter/clickhouse-filter";+import { FilterState } from "../../types";+import { createFilterFromFilterState } from "../queries/clickhouse-filter/factory";export type FetchScoresReturnType = {id: string;@@ -48,7 +54,7 @@ export const getScoresForTraces = async (projectId: string,traceIds: string[],limit: number,- offset: number+ offset: number,) => {const query = `select@@ -102,3 +108,42 @@ export const getScoresGroupedByNameSourceType = async (projectId: string) => {dataType: row.data_type as ScoreDataType,}));};++export const getScoresGroupedByName = async (+ projectId: string,+ timestampFilter?: FilterState,+) => {+ const chFilter = timestampFilter+ ? createFilterFromFilterState(timestampFilter, {+ scoresPrefix: "s",+ })+ : undefined;++ const timestampFilterRes = chFilter+ ? new FilterList(chFilter).apply()+ : undefined;++ const query = `+ select+ name as value+ from scores s final+ WHERE s.project_id = {projectId: String}+ AND has(['NUMERIC', 'BOOLEAN'], s.data_type)+ ${timestampFilterRes ? `AND ${timestampFilterRes.query}` : ""}+ GROUP BY name+ ORDER BY count() desc+ LIMIT 1000;+ `;++ const rows = await queryClickhouse<{+ name: string;+ }>({+ query: query,+ params: {+ projectId: projectId,+ ...(timestampFilterRes ? timestampFilterRes.params : {}),+ },+ });++ return rows;+};diff --git a/packages/shared/src/server/repositories/traces.ts b/packages/shared/src/server/repositories/traces.tsindex 0cc03142f4..290eff15f9 100644--- a/packages/shared/src/server/repositories/traces.ts+++ b/packages/shared/src/server/repositories/traces.ts@@ -7,6 +7,7 @@ import {import { ObservationLevel } from "@prisma/client";import { FilterState } from "../../types";import { logger } from "../logger";+import { FilterList } from "../queries/clickhouse-filter/clickhouse-filter";export type TracesTableReturnType = Pick<TraceClickhouseRecord,@@ -50,42 +51,43 @@ export const getTracesTable = async (const observationsStatsRes = observationsFilter.apply();const query = `- WITH observations_stats AS (- SELECT- COUNT(*) AS observation_count,- sumMap(usage_details) as usage_details,- SUM(total_cost) AS total_cost,- date_diff('seconds', least(min(start_time), min(end_time)), greatest(max(start_time), max(end_time))) as latencyMs,- multiIf(- arrayExists(x -> x = 'ERROR', groupArray(level)), 'ERROR',- arrayExists(x -> x = 'WARNING', groupArray(level)), 'WARNING',- arrayExists(x -> x = 'DEFAULT', groupArray(level)), 'DEFAULT',- 'DEBUG'- ) AS level,- sumMap(cost_details) as cost_details,- trace_id,- project_id- FROM- observations final- WHERE ${observationsStatsRes.query}- group by trace_id, project_id- ),- scores_avg AS (SELECT project_id,- trace_id,- groupArray(tuple(name, avg_value)) AS "scores_avg"- FROM (- SELECT project_id,- trace_id,- name,- avg(value) avg_value- FROM scores final- WHERE ${scoresAvgFilterRes.query}- GROUP BY project_id,- trace_id,- name- ) tmp- GROUP BY project_id,- trace_id)+ WITH observations_stats AS (+ SELECT+ COUNT(*) AS observation_count,+ sumMap(usage_details) as usage_details,+ SUM(total_cost) AS total_cost,+ date_diff('seconds', least(min(start_time), min(end_time)), greatest(max(start_time), max(end_time))) as latencyMs,+ multiIf(+ arrayExists(x -> x = 'ERROR', groupArray(level)), 'ERROR',+ arrayExists(x -> x = 'WARNING', groupArray(level)), 'WARNING',+ arrayExists(x -> x = 'DEFAULT', groupArray(level)), 'DEFAULT',+ 'DEBUG'+ ) AS level,+ sumMap(cost_details) as cost_details,+ trace_id,+ project_id+ FROM+ observations final+ WHERE ${observationsStatsRes.query}+ group by trace_id, project_id+),++ scores_avg AS (SELECT project_id,+ trace_id,+ groupArray(tuple(name, avg_value)) AS "scores_avg"+ FROM (+ SELECT project_id,+ trace_id,+ name,+ avg(value) avg_value+ FROM scores final+ WHERE ${scoresAvgFilterRes.query}+ GROUP BY project_id,+ trace_id,+ name+ ) tmp+ GROUP BY project_id,+ trace_id)selectt.id,t.project_id,@@ -156,3 +158,77 @@ export const getTraceById = async (traceId: string, projectId: string) => {return res.length ? res[0] : undefined;};++export const getTracesGroupedByName = async (+ projectId: string,+ timestampFilter?: FilterState,+) => {+ const chFilter = timestampFilter+ ? createFilterFromFilterState(timestampFilter, {+ tracesPrefix: "t",+ })+ : undefined;++ const timestampFilterRes = chFilter+ ? new FilterList(chFilter).apply()+ : undefined;++ const query = `+ select+ name as value+ from traces t final+ WHERE t.project_id = {projectId: String}+ ${timestampFilterRes ? `AND ${timestampFilterRes.query}` : ""}+ GROUP BY name+ ORDER BY name desc+ LIMIT 1000;+ `;++ const rows = await queryClickhouse<{+ value: string;+ }>({+ query: query,+ params: {+ projectId: projectId,+ ...(timestampFilterRes ? timestampFilterRes.params : {}),+ },+ });++ return rows;+};++export const getTracesGroupedByTags = async (+ projectId: string,+ timestampFilter?: FilterState,+) => {+ const chFilter = timestampFilter+ ? createFilterFromFilterState(timestampFilter, {+ tracesPrefix: "t",+ })+ : undefined;++ const timestampFilterRes = chFilter+ ? new FilterList(chFilter).apply()+ : undefined;++ const query = `+ select+ distinct(arrayJoin(tags)) as value+ from traces t final+ WHERE t.project_id = {projectId: String}+ ${timestampFilterRes ? `AND ${timestampFilterRes.query}` : ""}+ LIMIT 1000;+ `;++ const rows = await queryClickhouse<{+ value: string;+ }>({+ query: query,+ params: {+ projectId: projectId,+ ...(timestampFilterRes ? timestampFilterRes.params : {}),+ },+ });++ return rows;+};diff --git a/web/src/components/table/use-cases/traces.tsx b/web/src/components/table/use-cases/traces.tsxindex 7e0535d75f..41c5b1af90 100644--- a/web/src/components/table/use-cases/traces.tsx+++ b/web/src/components/table/use-cases/traces.tsx@@ -200,6 +200,7 @@ export default function TracesTable({dateRangeFilter[0]?.type === "datetime"? dateRangeFilter[0]: undefined,+ queryClickhouse: useClickhouse(),},{trpc: {diff --git a/web/src/server/api/routers/generations/getAllQueries.ts b/web/src/server/api/routers/generations/getAllQueries.tsindex 8c8de8aac6..508503ed46 100644--- a/web/src/server/api/routers/generations/getAllQueries.ts+++ b/web/src/server/api/routers/generations/getAllQueries.ts@@ -34,7 +34,7 @@ export const getAllQueries = {generations: generations,};} else {- if (!isClickhouseEligible(ctx.session.user.admin === true)) {+ if (!isClickhouseEligible(ctx.session.user)) {throw new TRPCError({code: "UNAUTHORIZED",message: "Not eligible to query clickhouse",diff --git a/web/src/server/api/routers/scores.ts b/web/src/server/api/routers/scores.tsindex 0fc495cd5a..d410bedbbf 100644--- a/web/src/server/api/routers/scores.ts+++ b/web/src/server/api/routers/scores.ts@@ -368,7 +368,7 @@ export const scoresRouter = createTRPCRouter({dataType: dataType,}));} else {- if (!isClickhouseEligible(ctx.session.user.admin === true)) {+ if (!isClickhouseEligible(ctx.session.user)) {throw new TRPCError({code: "UNAUTHORIZED",message: "Not eligible to query clickhouse",diff --git a/web/src/server/api/routers/traces.ts b/web/src/server/api/routers/traces.tsindex 0d10af7032..c2ec7b5f73 100644--- a/web/src/server/api/routers/traces.ts+++ b/web/src/server/api/routers/traces.ts@@ -33,6 +33,9 @@ import {getScoresForTraces,getTraceById,type TracesTableReturnType,+ getScoresGroupedByName,+ getTracesGroupedByName,+ getTracesGroupedByTags,} from "@langfuse/shared/src/server";import { TRPCError } from "@trpc/server";import Decimal from "decimal.js";@@ -186,7 +189,7 @@ export const traceRouter = createTRPCRouter({),};} else {- if (!isClickhouseEligible(ctx.session.user.admin === true)) {+ if (!isClickhouseEligible(ctx.session.user)) {throw new TRPCError({code: "UNAUTHORIZED",message: "Not eligible to query clickhouse",@@ -284,7 +287,8 @@ export const traceRouter = createTRPCRouter({),}));} else {- if (!isClickhouseEligible(ctx.session.user.admin === true)) {+ ctx.session.user;+ if (!isClickhouseEligible(ctx.session.user)) {throw new TRPCError({code: "UNAUTHORIZED",message: "Not eligible to query clickhouse",@@ -324,47 +328,49 @@ export const traceRouter = createTRPCRouter({z.object({projectId: z.string(),timestampFilter: timeFilter.optional(),+ queryClickhouse: z.boolean().default(false),}),).query(async ({ input, ctx }) => {- 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 }[]>`+ if (!input.queryClickhouse) {+ const { timestampFilter } = input;+ const prismaTimestampFilter = timestampFilter+ ? datetimeFilterToPrisma(timestampFilter)+ : {};++ const rawTimestampFilter =+ timestampFilter && timestampFilter.type === "datetime"+ ? datetimeFilterToPrismaSql(+ "timestamp",+ timestampFilter.operator,+ timestampFilter.value,+ )+ : Prisma.empty;++ const [scores, names, tags] = await Promise.all([+ ctx.prisma.score.groupBy({+ where: {+ projectId: input.projectId,+ timestamp: prismaTimestampFilter,+ dataType: { in: ["NUMERIC", "BOOLEAN"] },+ },+ take: 1000,+ orderBy: { name: "asc" },+ by: ["name"],+ }),+ ctx.prisma.trace.groupBy({+ where: {+ projectId: input.projectId,+ timestamp: prismaTimestampFilter,+ },+ by: ["name"],+ // limiting to 1k trace names to avoid performance issues.+ // some users have unique names for large amounts of traces+ // sending all trace names to the FE exceeds the cloud function return size limit+ take: 1000,+ orderBy: { name: "asc" },+ }),+ ctx.prisma.$queryRaw<{ value: string }[]>`SELECT tags.tag as valueFROM traces, UNNEST(traces.tags) AS tags(tag)WHERE traces.project_id = ${input.projectId} ${rawTimestampFilter}@@ -372,17 +378,49 @@ export const traceRouter = createTRPCRouter({ORDER BY tags.tag ASCLIMIT 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;+ ]);+ const res: TraceOptions = {+ scores_avg: scores.map((score) => score.name),+ name: names+ .filter((n) => n.name !== null)+ .map((name) => ({+ value: name.name ?? "undefined",+ })),+ tags: tags,+ };+ return res;+ } else {+ if (!isClickhouseEligible(ctx.session.user)) {+ throw new TRPCError({+ code: "UNAUTHORIZED",+ message: "Not eligible to query clickhouse",+ });+ }++ const { timestampFilter } = input;++ const [scoreNames, traceNames, tags] = await Promise.all([+ getScoresGroupedByName(+ input.projectId,+ timestampFilter ? [timestampFilter] : [],+ ),+ getTracesGroupedByName(+ input.projectId,+ timestampFilter ? [timestampFilter] : [],+ ),+ getTracesGroupedByTags(+ input.projectId,+ timestampFilter ? [timestampFilter] : [],+ ),+ ]);++ const res: TraceOptions = {+ name: traceNames,+ scores_avg: scoreNames.map((s) => s.name),+ tags: tags,+ };+ return res;+ }}),byId: protectedGetTraceProcedure.input(@@ -401,7 +439,7 @@ export const traceRouter = createTRPCRouter({},});} else {- if (!isClickhouseEligible(ctx.session.user?.admin === true)) {+ if (!isClickhouseEligible(ctx.session.user)) {throw new TRPCError({code: "UNAUTHORIZED",message: "Not eligible to query clickhouse",diff --git a/web/src/server/api/trpc.ts b/web/src/server/api/trpc.tsindex 98cab4f8b4..2c98321fa2 100644--- a/web/src/server/api/trpc.ts+++ b/web/src/server/api/trpc.ts@@ -336,7 +336,7 @@ const enforceTraceAccess = t.middleware(async ({ ctx, rawInput, next }) => {// if the user is eligible for clickhouse, and wants to use clickhouse, do so.const trace =result.data.queryClickhouse === true &&- isClickhouseEligible(ctx.session?.user?.admin === true)+ isClickhouseEligible(ctx.session?.user)? await getTraceById(traceId, projectId): await prisma.trace.findFirst({where: {diff --git a/web/src/server/utils/checkClickhouseAccess.ts b/web/src/server/utils/checkClickhouseAccess.tsindex 19927ba029..abd609f524 100644--- a/web/src/server/utils/checkClickhouseAccess.ts+++ b/web/src/server/utils/checkClickhouseAccess.ts@@ -1,5 +1,14 @@import { env } from "@/src/env.mjs";+import { type User } from "next-auth";-export const isClickhouseEligible = (admin: boolean) => {- return admin === true && env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION;+export const isClickhouseEligible = (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,+ )+ );};