🪢 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
chore: migrate ModelCostTable to new query mechanism (#6222)
Steffen Schmitzb1aaf57ad59b
diff --git a/.env.prod.example b/.env.prod.exampleindex 48e1920bc5..318371bd11 100644--- a/.env.prod.example+++ b/.env.prod.example@@ -219,17 +219,6 @@ OTEL_SERVICE_NAME="langfuse"### END Enterprise Edition Configuration--### START Envs to be deprecated in Langfuse v3.0--# Disable the expensive analytics queries and related features-# LANGFUSE_DISABLE_EXPENSIVE_POSTGRES_QUERIES="true"--### END Envs to be deprecated in Langfuse v3.0----### START Langfuse Cloud Config# Used for Langfuse Cloud deployments# Not recommended for self-hosted deployments as these are NOT COVERED BY SEMANTIC VERSIONINGdiff --git a/packages/shared/src/server/queries/clickhouse-sql/clickhouse-filter.ts b/packages/shared/src/server/queries/clickhouse-sql/clickhouse-filter.tsindex 8ea0eebce1..00ad08245a 100644--- a/packages/shared/src/server/queries/clickhouse-sql/clickhouse-filter.ts+++ b/packages/shared/src/server/queries/clickhouse-sql/clickhouse-filter.ts@@ -391,6 +391,10 @@ export class FilterList {return this.filters.some(predicate);}+ forEach(callback: (filter: Filter) => void) {+ this.filters.forEach(callback);+ }+length() {return this.filters.length;}diff --git a/web/src/__tests__/queryBuilderDashboards.servertest.ts b/web/src/__tests__/queryBuilderDashboards.servertest.tsindex 7c56a1b6fd..f8444c61f8 100644--- a/web/src/__tests__/queryBuilderDashboards.servertest.ts+++ b/web/src/__tests__/queryBuilderDashboards.servertest.ts@@ -580,6 +580,71 @@ describe("selfServeDashboards", () => {expect(legacyResult.length).toBe(queryBuilderResult.length);});+ it("should filter observations by traceName", async () => {+ // 1. Define a filter for chat-completion trace+ const traceNameFilter: FilterState = [+ {+ type: "string",+ operator: "=",+ column: "traceName",+ value: "chat-completion",+ },+ ];++ // 2. Get legacy result with filter+ const legacyResult = await getObservationsCostGroupedByName(+ projectId,+ traceNameFilter,+ );++ // 3. Define the equivalent query for the query builder+ const queryBuilderQuery: QueryType = {+ view: "observations",+ dimensions: [{ field: "providedModelName" }],+ metrics: [+ { measure: "totalCost", aggregation: "sum" },+ { measure: "totalTokens", aggregation: "sum" },+ ],+ filters: [+ {+ column: "traceName",+ operator: "=",+ value: "chat-completion",+ type: "string",+ },+ ],+ timeDimension: null,+ fromTimestamp: defaultFromTime,+ toTimestamp: defaultToTime,+ orderBy: null,+ };++ // 4. Get result using the query builder+ const queryBuilderResult = await executeQuery(+ projectId,+ queryBuilderQuery,+ );++ // 5. Verify results+ // Verify both results have the same number of rows+ expect(queryBuilderResult.length).toBe(legacyResult.length);++ // Create maps for easier comparison+ const legacyResultMap = new Map(+ legacyResult.map((item) => [item.name, item]),+ );++ // Verify each model is present with correct costs+ queryBuilderResult.forEach((row: any) => {+ const modelName = row.provided_model_name;+ const legacyModelData = legacyResultMap.get(modelName);++ expect(legacyModelData).toBeDefined();+ expect(row.sum_total_cost).toBe(legacyModelData?.sum_cost_details);+ expect(row.sum_total_tokens).toBe(legacyModelData?.sum_usage_details);+ });+ });+it("should filter observations by environment", async () => {// 1. Define a filter for production environmentconst prodFilter: FilterState = [diff --git a/web/src/env.mjs b/web/src/env.mjsindex c08e4d8630..3c3ae62931 100644--- a/web/src/env.mjs+++ b/web/src/env.mjs@@ -49,10 +49,6 @@ export const env = createEnv({LANGFUSE_NEW_USER_SIGNUP_WEBHOOK: z.string().url().optional(),// Add `.min(1) on ID and SECRET if you want to make sure they're not emptyLANGFUSE_ENABLE_EXPERIMENTAL_FEATURES: z.enum(["true", "false"]).optional(),- LANGFUSE_DISABLE_EXPENSIVE_POSTGRES_QUERIES: z- .enum(["true", "false"])- .optional()- .default("false"),SALT: z.string({required_error:"A strong Salt is required to encrypt API keys securely. See: https://langfuse.com/docs/deployment/self-host#deploy-the-container",@@ -342,8 +338,6 @@ export const env = createEnv({NEXT_PUBLIC_SIGN_UP_DISABLED: process.env.NEXT_PUBLIC_SIGN_UP_DISABLED,LANGFUSE_ENABLE_EXPERIMENTAL_FEATURES:process.env.LANGFUSE_ENABLE_EXPERIMENTAL_FEATURES,- LANGFUSE_DISABLE_EXPENSIVE_POSTGRES_QUERIES:- process.env.LANGFUSE_DISABLE_EXPENSIVE_POSTGRES_QUERIES,LANGFUSE_TEAM_SLACK_WEBHOOK: process.env.LANGFUSE_TEAM_SLACK_WEBHOOK,LANGFUSE_NEW_USER_SIGNUP_WEBHOOK:process.env.LANGFUSE_NEW_USER_SIGNUP_WEBHOOK,diff --git a/web/src/features/dashboard/components/ModelCostTable.tsx b/web/src/features/dashboard/components/ModelCostTable.tsxindex 8ec763a9ba..18bc860421 100644--- a/web/src/features/dashboard/components/ModelCostTable.tsx+++ b/web/src/features/dashboard/components/ModelCostTable.tsx@@ -8,45 +8,55 @@ import { api } from "@/src/utils/api";import { compactNumberFormatter } from "@/src/utils/numbers";import { TotalMetric } from "./TotalMetric";import { totalCostDashboardFormatted } from "@/src/features/dashboard/lib/dashboard-utils";-import { env } from "@/src/env.mjs";import { truncate } from "@/src/utils/string";+import {+ type QueryType,+ mapLegacyUiTableFilterToView,+} from "@/src/features/query";export const ModelCostTable = ({className,projectId,globalFilterState,+ fromTimestamp,+ toTimestamp,isLoading = false,}: {className: string;projectId: string;globalFilterState: FilterState;+ fromTimestamp: Date;+ toTimestamp: Date;isLoading?: boolean;}) => {- const metrics = api.dashboard.chart.useQuery(+ // Define the query using the new QueryType structure+ const modelCostQuery: QueryType = {+ view: "observations",+ dimensions: [{ field: "providedModelName" }],+ metrics: [+ { measure: "totalCost", aggregation: "sum" },+ { measure: "totalTokens", aggregation: "sum" },+ ],+ filters: [+ ...mapLegacyUiTableFilterToView("observations", globalFilterState),+ {+ column: "type",+ operator: "=",+ value: "GENERATION",+ type: "string",+ },+ ],+ timeDimension: null,+ fromTimestamp: fromTimestamp.toISOString(),+ toTimestamp: toTimestamp.toISOString(),+ orderBy: null,+ };++ // Execute the query using the new dashboard.executeQuery functionality+ const metrics = api.dashboard.executeQuery.useQuery({projectId,- from: env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION // Langfuse Cloud has already completed the cost backfill job, thus cost can be pulled directly from obs. table- ? "traces_observations"- : "traces_observationsview",- select: [- { column: "calculatedTotalCost", agg: "SUM" },- { column: "totalTokens", agg: "SUM" },- { column: "model" },- ],- filter: [- ...globalFilterState,- {- type: "string",- column: "type",- operator: "=",- value: "GENERATION",- },- ],- groupBy: [{ type: "string", column: "model" }],- orderBy: [- { column: "calculatedTotalCost", direction: "DESC", agg: "SUM" },- ],- queryName: "observations-model-cost",+ query: modelCostQuery,},{trpc: {@@ -60,30 +70,28 @@ export const ModelCostTable = ({const totalTokenCost = metrics.data?.reduce((acc, curr) =>- acc +- (curr.sumCalculatedTotalCost- ? (curr.sumCalculatedTotalCost as number)- : 0),+ acc + (curr.sum_total_cost ? (curr.sum_total_cost as number) : 0),0,);const metricsData = metrics.data? metrics.data- .filter((item) => item.model !== null)+ .filter((item) => item.provided_model_name !== null).map((item, i) => [- <LeftAlignedCell key={`${i}-model`} title={item.model as string}>- {truncate(item.model as string, 30)}+ <LeftAlignedCell+ key={`${i}-model`}+ title={item.provided_model_name as string}+ >+ {truncate(item.provided_model_name as string, 30)}</LeftAlignedCell>,<RightAlignedCell key={`${i}-tokens`}>- {item.sumTotalTokens- ? compactNumberFormatter(item.sumTotalTokens as number)+ {item.sum_total_tokens+ ? compactNumberFormatter(item.sum_total_tokens as number): "0"}</RightAlignedCell>,<RightAlignedCell key={`${i}-cost`}>- {item.sumCalculatedTotalCost- ? totalCostDashboardFormatted(- item.sumCalculatedTotalCost as number,- )+ {item.sum_total_cost+ ? totalCostDashboardFormatted(item.sum_total_cost as number): "$0"}</RightAlignedCell>,])diff --git a/web/src/features/dashboard/server/dashboard-router.ts b/web/src/features/dashboard/server/dashboard-router.tsindex 97dc93afb0..de11df5497 100644--- a/web/src/features/dashboard/server/dashboard-router.ts+++ b/web/src/features/dashboard/server/dashboard-router.ts@@ -11,9 +11,6 @@ import {import { createHistogramData } from "@/src/features/dashboard/lib/score-analytics-utils";import { TRPCError } from "@trpc/server";import {- getTotalTraces,- getTracesGroupedByName,- getObservationsCostGroupedByName,getScoreAggregate,groupTracesByTime,getDistinctModels,@@ -32,6 +29,7 @@ import {getTotalObservationUsageByTimeByModel,getObservationCostByTypeByTime,getObservationUsageByTypeByTime,+ queryClickhouse,} from "@langfuse/shared/src/server";import { type DatabaseRow } from "@/src/server/api/services/sqlInterface";import { dashboardColumnDefinitions } from "@langfuse/shared";@@ -40,7 +38,6 @@ import {type QueryType,query as customQuery,} from "@/src/features/query/types";-import { clickhouseClient } from "@langfuse/shared/src/server";export const dashboardRouter = createTRPCRouter({chart: protectedProjectProcedure@@ -50,9 +47,9 @@ export const dashboardRouter = createTRPCRouter({filter: filterInterface.optional(),queryName: z.enum([- "traces-total",- "traces-grouped-by-name",- "observations-model-cost",+ // "traces-total",+ // "traces-grouped-by-name",+ // "observations-model-cost","score-aggregate","traces-timeseries","observations-total-cost-by-model-timeseries",@@ -83,37 +80,37 @@ export const dashboardRouter = createTRPCRouter({}switch (input.queryName) {- case "traces-total":- const count = await getTotalTraces(- input.projectId,- input.filter ?? [],- );- return count as DatabaseRow[];- case "traces-grouped-by-name":- return (- await getTracesGroupedByName(- input.projectId,- dashboardColumnDefinitions,- input.filter,- )- ).map(- (row) =>- ({- traceName: row.name,- countTraceId: row.count,- }) as DatabaseRow,- );- case "observations-model-cost":- const cost = await getObservationsCostGroupedByName(- input.projectId,- input.filter ?? [],- );-- return cost.map((row) => ({- model: row.name,- sumCalculatedTotalCost: row.sum_cost_details,- sumTotalTokens: row.sum_usage_details,- })) as DatabaseRow[];+ // case "traces-total":+ // const count = await getTotalTraces(+ // input.projectId,+ // input.filter ?? [],+ // );+ // return count as DatabaseRow[];+ // case "traces-grouped-by-name":+ // return (+ // await getTracesGroupedByName(+ // input.projectId,+ // dashboardColumnDefinitions,+ // input.filter,+ // )+ // ).map(+ // (row) =>+ // ({+ // traceName: row.name,+ // countTraceId: row.count,+ // }) as DatabaseRow,+ // );+ // case "observations-model-cost":+ // const cost = await getObservationsCostGroupedByName(+ // input.projectId,+ // input.filter ?? [],+ // );+ //+ // return cost.map((row) => ({+ // model: row.name,+ // sumCalculatedTotalCost: row.sum_cost_details,+ // sumTotalTokens: row.sum_usage_details,+ // })) as DatabaseRow[];case "score-aggregate":const scores = await getScoreAggregate(input.projectId,@@ -325,30 +322,22 @@ export async function executeQuery(query: QueryType,): Promise<Array<Record<string, unknown>>> {try {- // Initialize query builder with ClickHouse client- const queryBuilder = new QueryBuilder();-- // Build the query- const { query: compiledQuery, parameters } = queryBuilder.build(+ const { query: compiledQuery, parameters } = new QueryBuilder().build(query,projectId,);- // Execute the query- const result = await clickhouseClient({+ const result = await queryClickhouse<Record<string, unknown>>({+ query: compiledQuery,+ params: parameters,tags: {feature: "custom-queries",type: query.view,kind: "analytic",projectId,},- }).query({- query: compiledQuery,- query_params: parameters,});-- // Return the result- return (await result.json<Record<string, unknown>>()).data;+ return result;} catch (error) {logger.error("Error executing query", { error, projectId, query });throw new TRPCError({diff --git a/web/src/features/query/server/queryBuilder.ts b/web/src/features/query/server/queryBuilder.tsindex 6c50c0030b..877bc4bd8e 100644--- a/web/src/features/query/server/queryBuilder.ts+++ b/web/src/features/query/server/queryBuilder.ts@@ -120,10 +120,16 @@ export class QueryBuilder {const dimension = view.dimensions[filter.column];clickhouseSelect = dimension.sql;type = dimension.type;+ if (dimension.relationTable) {+ clickhouseTableName = dimension.relationTable;+ }} else if (filter.column in view.measures) {const measure = view.measures[filter.column];clickhouseSelect = measure.sql;type = measure.type;+ if (measure.relationTable) {+ clickhouseTableName = measure.relationTable;+ }} else if (filter.column === view.timeDimension) {clickhouseSelect = view.timeDimension;type = "datetime";@@ -138,7 +144,7 @@ export class QueryBuilder {uiTableId: filter.column,clickhouseTableName,clickhouseSelect,- queryPrefix: view.name,+ queryPrefix: clickhouseTableName,type,};});@@ -238,8 +244,10 @@ export class QueryBuilder {}private collectRelationTables(+ view: ViewDeclarationType,appliedDimensions: AppliedDimensionType[],appliedMetrics: AppliedMetricType[],+ filters: FilterList,) {const relationTables = new Set<string>();appliedDimensions.forEach((dimension) => {@@ -252,6 +260,11 @@ export class QueryBuilder {relationTables.add(metric.relationTable);}});+ filters.forEach((filter) => {+ if (filter.clickhouseTable !== view.name) {+ relationTables.add(filter.clickhouseTable);+ }+ });return relationTables;}@@ -724,8 +737,10 @@ export class QueryBuilder {// Handle relation tablesconst relationTables = this.collectRelationTables(+ view,appliedDimensions,appliedMetrics,+ filterList,);if (relationTables.size > 0) {const relationJoins = this.buildJoins(diff --git a/web/src/pages/project/[projectId]/index.tsx b/web/src/pages/project/[projectId]/index.tsxindex 1c9395a5c7..c6f88d41ad 100644--- a/web/src/pages/project/[projectId]/index.tsx+++ b/web/src/pages/project/[projectId]/index.tsx@@ -18,7 +18,6 @@ import { type ColumnDefinition } from "@langfuse/shared";import { useQueryFilterState } from "@/src/features/filters/hooks/useFilterState";import { LatencyTables } from "@/src/features/dashboard/components/LatencyTables";import { useMemo } from "react";-import { useSession } from "next-auth/react";import { findClosestDashboardInterval } from "@/src/utils/date-range-utils";import { useDashboardDateRange } from "@/src/hooks/useDashboardDateRange";import { useDebounce } from "@/src/hooks/useDebounce";@@ -43,10 +42,6 @@ export default function Dashboard() {const lookbackLimit = useEntitlementLimit("data-access-days");- const session = useSession();- const disableExpensiveDashboardComponents =- session.data?.environment.disableExpensivePostgresQueries ?? true;-const [userFilterState, setUserFilterState] = useQueryFilterState([],"dashboard",@@ -242,14 +237,14 @@ export default function Dashboard() {toTimestamp={toTimestamp}isLoading={environmentFilterOptions.isLoading}/>- {!disableExpensiveDashboardComponents && (- <ModelCostTable- className="col-span-1 xl:col-span-2"- projectId={projectId}- globalFilterState={mergedFilterState}- isLoading={environmentFilterOptions.isLoading}- />- )}+ <ModelCostTable+ className="col-span-1 xl:col-span-2"+ projectId={projectId}+ globalFilterState={[...userFilterState, ...environmentFilter]}+ fromTimestamp={fromTimestamp}+ toTimestamp={toTimestamp}+ isLoading={environmentFilterOptions.isLoading}+ /><ScoresTableclassName="col-span-1 xl:col-span-2"projectId={projectId}@@ -263,23 +258,19 @@ export default function Dashboard() {agg={agg}isLoading={environmentFilterOptions.isLoading}/>- {!disableExpensiveDashboardComponents && (- <ModelUsageChart- className="col-span-1 min-h-24 xl:col-span-3"- projectId={projectId}- globalFilterState={mergedFilterState}- agg={agg}- isLoading={environmentFilterOptions.isLoading}- />- )}- {!disableExpensiveDashboardComponents && (- <UserChart- className="col-span-1 xl:col-span-3"- projectId={projectId}- globalFilterState={mergedFilterState}- isLoading={environmentFilterOptions.isLoading}- />- )}+ <ModelUsageChart+ className="col-span-1 min-h-24 xl:col-span-3"+ projectId={projectId}+ globalFilterState={mergedFilterState}+ agg={agg}+ isLoading={environmentFilterOptions.isLoading}+ />+ <UserChart+ className="col-span-1 xl:col-span-3"+ projectId={projectId}+ globalFilterState={mergedFilterState}+ isLoading={environmentFilterOptions.isLoading}+ /><ChartScoresclassName="col-span-1 xl:col-span-3"agg={agg}@@ -287,31 +278,25 @@ export default function Dashboard() {globalFilterState={mergedFilterState}isLoading={environmentFilterOptions.isLoading}/>- {!disableExpensiveDashboardComponents && (- <LatencyTables- projectId={projectId}- globalFilterState={mergedFilterState}- isLoading={environmentFilterOptions.isLoading}- />- )}- {!disableExpensiveDashboardComponents && (- <GenerationLatencyChart- className="col-span-1 flex-auto justify-between lg:col-span-full"- projectId={projectId}- agg={agg}- globalFilterState={mergedFilterState}- isLoading={environmentFilterOptions.isLoading}- />- )}- {!disableExpensiveDashboardComponents && (- <ScoreAnalytics- className="col-span-1 flex-auto justify-between lg:col-span-full"- agg={agg}- projectId={projectId}- globalFilterState={mergedFilterState}- isLoading={environmentFilterOptions.isLoading}- />- )}+ <LatencyTables+ projectId={projectId}+ globalFilterState={mergedFilterState}+ isLoading={environmentFilterOptions.isLoading}+ />+ <GenerationLatencyChart+ className="col-span-1 flex-auto justify-between lg:col-span-full"+ projectId={projectId}+ agg={agg}+ globalFilterState={mergedFilterState}+ isLoading={environmentFilterOptions.isLoading}+ />+ <ScoreAnalytics+ className="col-span-1 flex-auto justify-between lg:col-span-full"+ agg={agg}+ projectId={projectId}+ globalFilterState={mergedFilterState}+ isLoading={environmentFilterOptions.isLoading}+ /></div></Page>);diff --git a/web/src/server/auth.ts b/web/src/server/auth.tsindex 7afcfe06ff..8c8fc001f3 100644--- a/web/src/server/auth.ts+++ b/web/src/server/auth.ts@@ -492,8 +492,6 @@ export async function getAuthOptions(): Promise<NextAuthOptions> {environment: {enableExperimentalFeatures:env.LANGFUSE_ENABLE_EXPERIMENTAL_FEATURES === "true",- disableExpensivePostgresQueries:- env.LANGFUSE_DISABLE_EXPENSIVE_POSTGRES_QUERIES === "true",// Enables features that are only available under an enterprise license when self-hosting Langfuse// If you edit this line, you risk executing code that is not MIT licensed (self-contained in /ee folders otherwise)selfHostedInstancePlan: getSelfHostedInstancePlanServerSide(),diff --git a/web/types/next-auth.d.ts b/web/types/next-auth.d.tsindex 86d436c82a..2b92c98174 100644--- a/web/types/next-auth.d.ts+++ b/web/types/next-auth.d.ts@@ -21,7 +21,6 @@ declare module "next-auth" {environment: {// Run-time environment variables that need to be available client-sideenableExperimentalFeatures: boolean;- disableExpensivePostgresQueries: boolean;// Enables features that are only available under an enterprise/commercial license when self-hosting LangfuseselfHostedInstancePlan: Plan | null;};