🪢 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 observation by model charts to new query builder (#6245)
Steffen Schmitz6582dbc645e1
diff --git a/web/src/__tests__/queryBuilderDashboards.servertest.ts b/web/src/__tests__/queryBuilderDashboards.servertest.tsindex f8444c61f8..a83db40c6d 100644--- a/web/src/__tests__/queryBuilderDashboards.servertest.ts+++ b/web/src/__tests__/queryBuilderDashboards.servertest.ts@@ -9,6 +9,7 @@ import {getObservationsCostGroupedByName,getScoreAggregate,groupTracesByTime,+ getTotalObservationUsageByTimeByModel,} from "@langfuse/shared/src/server";import { type FilterState } from "@langfuse/shared";import { type QueryType } from "@/src/features/query/types";@@ -965,4 +966,78 @@ describe("selfServeDashboards", () => {});});});++ describe("observations-total-cost-by-model-timeseries query", () => {+ it("should return the same result with query builder as with legacy function", async () => {+ // 1. Get result using the legacy function+ const legacyResult = await getTotalObservationUsageByTimeByModel(+ projectId,+ [+ {+ type: "datetime",+ operator: ">=",+ column: "timestamp",+ value: new Date(defaultFromTime),+ },+ {+ type: "datetime",+ operator: "<=",+ column: "timestamp",+ value: new Date(defaultToTime),+ },+ ],+ );++ // 2. Define the equivalent query for the query builder+ const queryBuilderQuery: QueryType = {+ view: "observations",+ dimensions: [{ field: "providedModelName" }],+ metrics: [+ { measure: "totalTokens", aggregation: "sum" },+ { measure: "totalCost", aggregation: "sum" },+ ],+ filters: [],+ timeDimension: {+ granularity: "hour",+ },+ fromTimestamp: defaultFromTime,+ toTimestamp: defaultToTime,+ orderBy: null,+ };++ // 3. Get result using the query builder+ const queryBuilderResult = await executeQuery(+ projectId,+ queryBuilderQuery,+ );++ // 4. Verify both results+ expect(queryBuilderResult).toBeDefined();+ expect(legacyResult).toBeDefined();++ // Verify both result sets have 70 to 80 rows+ expect(legacyResult.length).toBeGreaterThanOrEqual(70);+ expect(legacyResult.length).toBeLessThanOrEqual(80);+ expect(queryBuilderResult.length).toBeGreaterThanOrEqual(70);+ expect(queryBuilderResult.length).toBeLessThanOrEqual(80);++ // Create maps for easier comparison+ const legacyResultMap = new Map(+ legacyResult.map((item) => [+ `${item.model}-${item.startTime.getTime()}`,+ item,+ ]),+ );++ // Verify each model's costs and token usage match+ queryBuilderResult.forEach((row: any) => {+ const key = `${row.provided_model_name}-${new Date(row.time_dimension).getTime()}`;+ const legacyData = legacyResultMap.get(key);++ expect(legacyData).toBeDefined();+ expect(Number(row.sum_total_cost)).toBe(Number(legacyData?.cost));+ expect(Number(row.sum_total_tokens)).toBe(Number(legacyData?.units));+ });+ });+ });});diff --git a/web/src/features/dashboard/components/ModelUsageChart.tsx b/web/src/features/dashboard/components/ModelUsageChart.tsxindex d2be542325..0f6e023b71 100644--- a/web/src/features/dashboard/components/ModelUsageChart.tsx+++ b/web/src/features/dashboard/components/ModelUsageChart.tsx@@ -1,5 +1,4 @@import { NoDataOrLoading } from "@/src/components/NoDataOrLoading";-import { env } from "@/src/env.mjs";import { BaseTimeSeriesChart } from "@/src/features/dashboard/components/BaseTimeSeriesChart";import { DashboardCard } from "@/src/features/dashboard/components/cards/DashboardCard";import {@@ -21,18 +20,29 @@ import {ModelSelectorPopover,useModelSelection,} from "@/src/features/dashboard/components/ModelSelector";+import {+ type QueryType,+ mapLegacyUiTableFilterToView,+} from "@/src/features/query";+import { type DatabaseRow } from "@/src/server/api/services/sqlInterface";export const ModelUsageChart = ({className,projectId,globalFilterState,agg,+ fromTimestamp,+ toTimestamp,+ userAndEnvFilterState,isLoading = false,}: {className?: string;projectId: string;globalFilterState: FilterState;agg: DashboardDateRangeAggregationOption;+ fromTimestamp: Date;+ toTimestamp: Date;+ userAndEnvFilterState: FilterState;isLoading?: boolean;}) => {const {@@ -44,42 +54,42 @@ export const ModelUsageChart = ({handleSelectAll,} = useModelSelection(projectId, globalFilterState);- const queryResult = api.dashboard.chart.useQuery(+ // Define the query for model usage data using the new QueryType structure+ const modelUsageQuery: QueryType = {+ view: "observations",+ dimensions: [{ field: "providedModelName" }],+ metrics: [+ { measure: "totalCost", aggregation: "sum" },+ { measure: "totalTokens", aggregation: "sum" },+ ],+ filters: [+ ...mapLegacyUiTableFilterToView("observations", userAndEnvFilterState),+ {+ column: "type",+ operator: "=",+ value: "GENERATION",+ type: "string",+ },+ {+ column: "providedModelName",+ operator: "any of",+ value: selectedModels,+ type: "stringOptions",+ },+ ],+ timeDimension: {+ granularity: "auto",+ },+ fromTimestamp: fromTimestamp.toISOString(),+ toTimestamp: toTimestamp.toISOString(),+ orderBy: null,+ };++ // Execute the query using the new dashboard.executeQuery functionality+ const queryResult = 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: "totalTokens", agg: "SUM" },- { column: "calculatedTotalCost", agg: "SUM" },- { column: "model" },- ],- filter: [- ...globalFilterState,- { type: "string", column: "type", operator: "=", value: "GENERATION" },- {- type: "stringOptions",- column: "model",- operator: "any of",- value: selectedModels,- } as const,- ],- groupBy: [- {- type: "datetime",- column: "startTime",- temporalUnit: dashboardDateRangeAggregationSettings[agg].date_trunc,- },- {- type: "string",- column: "model",- },- ],- orderBy: [- { column: "calculatedTotalCost", direction: "DESC", agg: "SUM" },- ],- queryName: "observations-total-cost-by-model-timeseries",+ query: modelUsageQuery,},{enabled: !isLoading && selectedModels.length > 0 && allModels.length > 0,@@ -94,9 +104,7 @@ export const ModelUsageChart = ({const queryCostByType = api.dashboard.chart.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",+ from: "traces_observations",select: [{ column: "totalTokens", agg: "SUM" },{ column: "calculatedTotalCost", agg: "SUM" },@@ -141,9 +149,7 @@ export const ModelUsageChart = ({const queryUsageByType = api.dashboard.chart.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",+ from: "traces_observations",select: [{ column: "totalTokens", agg: "SUM" },{ column: "calculatedTotalCost", agg: "SUM" },@@ -212,12 +218,16 @@ export const ModelUsageChart = ({const unitsByModel =queryResult.data && allModels.length > 0? fillMissingValuesAndTransform(- extractTimeSeriesData(queryResult.data, "startTime", [- {- uniqueIdentifierColumns: [{ accessor: "model" }],- valueColumn: "units",- },- ]),+ extractTimeSeriesData(+ queryResult.data as DatabaseRow[],+ "time_dimension",+ [+ {+ uniqueIdentifierColumns: [{ accessor: "provided_model_name" }],+ valueColumn: "sum_total_tokens",+ },+ ],+ ),selectedModels,): [];@@ -225,25 +235,33 @@ export const ModelUsageChart = ({const costByModel =queryResult.data && allModels.length > 0? fillMissingValuesAndTransform(- extractTimeSeriesData(queryResult.data, "startTime", [- {- uniqueIdentifierColumns: [{ accessor: "model" }],- valueColumn: "cost",- },- ]),+ extractTimeSeriesData(+ queryResult.data as DatabaseRow[],+ "time_dimension",+ [+ {+ uniqueIdentifierColumns: [{ accessor: "provided_model_name" }],+ valueColumn: "sum_total_cost",+ },+ ],+ ),selectedModels,): [];const totalCost = queryResult.data?.reduce((acc, curr) =>- acc + (!isNaN(curr.cost as number) ? (curr.cost as number) : 0),+ acc ++ (!isNaN(Number(curr.sum_total_cost)) ? Number(curr.sum_total_cost) : 0),0,);const totalTokens = queryResult.data?.reduce((acc, curr) =>- acc + (!isNaN(curr.units as number) ? (curr.units as number) : 0),+ acc ++ (!isNaN(Number(curr.sum_total_tokens))+ ? Number(curr.sum_total_tokens)+ : 0),0,);diff --git a/web/src/features/dashboard/server/dashboard-router.ts b/web/src/features/dashboard/server/dashboard-router.tsindex 3d970761d8..5e6c887958 100644--- a/web/src/features/dashboard/server/dashboard-router.ts+++ b/web/src/features/dashboard/server/dashboard-router.ts@@ -12,7 +12,6 @@ import { createHistogramData } from "@/src/features/dashboard/lib/score-analyticimport { TRPCError } from "@trpc/server";import {getScoreAggregate,- groupTracesByTime,getDistinctModels,getScoresAggregateOverTime,getTracesGroupedByUsers,@@ -23,10 +22,8 @@ import {getNumericScoreHistogram,getNumericScoreTimeSeries,getCategoricalScoreTimeSeries,- getObservationsStatusTimeSeries,extractFromAndToTimestampsFromFilter,logger,- getTotalObservationUsageByTimeByModel,getObservationCostByTypeByTime,getObservationUsageByTypeByTime,queryClickhouse,@@ -51,8 +48,9 @@ export const dashboardRouter = createTRPCRouter({// "traces-grouped-by-name",// "observations-model-cost","score-aggregate",- "traces-timeseries",- "observations-total-cost-by-model-timeseries",+ // "traces-timeseries",+ // "observations-total-cost-by-model-timeseries",+ // Cost by type and usage by type are currently not supported in the new data model"observations-usage-by-type-timeseries","observations-cost-by-type-timeseries","distinct-models",@@ -64,7 +62,7 @@ export const dashboardRouter = createTRPCRouter({"model-latencies-over-time","numeric-score-time-series","categorical-score-chart",- "observations-status-timeseries",+ // "observations-status-timeseries",]).nullish(),}),@@ -116,7 +114,6 @@ export const dashboardRouter = createTRPCRouter({input.projectId,input.filter ?? [],);-return scores.map((row) => ({scoreName: row.name,scoreSource: row.source,@@ -124,26 +121,24 @@ export const dashboardRouter = createTRPCRouter({avgValue: row.avg_value,countScoreId: Number(row.count),})) as DatabaseRow[];-- case "traces-timeseries":- const rows = await groupTracesByTime(- input.projectId,- input.filter ?? [],- );-- return rows as DatabaseRow[];- case "observations-total-cost-by-model-timeseries":- const dateTruncObs = extractTimeSeries(input.groupBy);- if (!dateTruncObs) {- return [];- }- const rowsObs = await getTotalObservationUsageByTimeByModel(- input.projectId,- input.filter ?? [],- );-- return rowsObs as DatabaseRow[];-+ // case "traces-timeseries":+ // const rows = await groupTracesByTime(+ // input.projectId,+ // input.filter ?? [],+ // );+ //+ // return rows as DatabaseRow[];+ // case "observations-total-cost-by-model-timeseries":+ // const dateTruncObs = extractTimeSeries(input.groupBy);+ // if (!dateTruncObs) {+ // return [];+ // }+ // const rowsObs = await getTotalObservationUsageByTimeByModel(+ // input.projectId,+ // input.filter ?? [],+ // );+ //+ // return rowsObs as DatabaseRow[];case "observations-usage-by-type-timeseries":const rowsObsType = await getObservationUsageByTypeByTime(input.projectId,@@ -151,7 +146,6 @@ export const dashboardRouter = createTRPCRouter({);return rowsObsType as DatabaseRow[];-case "observations-cost-by-type-timeseries":const rowsObsCostByType = await getObservationCostByTypeByTime(input.projectId,@@ -159,7 +153,6 @@ export const dashboardRouter = createTRPCRouter({);return rowsObsCostByType as DatabaseRow[];-case "distinct-models":const models = await getDistinctModels(input.projectId,@@ -261,12 +254,11 @@ export const dashboardRouter = createTRPCRouter({input.filter ?? [],);return categoricalScoreTimeSeries as DatabaseRow[];- case "observations-status-timeseries":- return (await getObservationsStatusTimeSeries(- input.projectId,- input.filter ?? [],- )) as DatabaseRow[];-+ // case "observations-status-timeseries":+ // return (await getObservationsStatusTimeSeries(+ // input.projectId,+ // input.filter ?? [],+ // )) as DatabaseRow[];default:throw new TRPCError({code: "NOT_FOUND",@@ -344,7 +336,7 @@ export async function executeQuery(});return result;} catch (error) {- logger.error("Error executing query", { error, projectId, query });+ logger.error("Error executing query", error, { projectId, query });throw new TRPCError({code: "INTERNAL_SERVER_ERROR",message: "Failed to execute query",diff --git a/web/src/features/query/server/queryBuilder.ts b/web/src/features/query/server/queryBuilder.tsindex 877bc4bd8e..2532eca03b 100644--- a/web/src/features/query/server/queryBuilder.ts+++ b/web/src/features/query/server/queryBuilder.ts@@ -135,7 +135,7 @@ export class QueryBuilder {type = "datetime";} else {throw new Error(- `Invalid filter column. Must be one of ${Object.keys(view.dimensions)} or ${Object.keys(view.measures)} or ${view.timeDimension}`,+ `Invalid filter column ${filter.column}. Must be one of ${Object.keys(view.dimensions)} or ${Object.keys(view.measures)} or ${view.timeDimension}`,);}diff --git a/web/src/pages/project/[projectId]/index.tsx b/web/src/pages/project/[projectId]/index.tsxindex 7f298f6cbe..e7efc87061 100644--- a/web/src/pages/project/[projectId]/index.tsx+++ b/web/src/pages/project/[projectId]/index.tsx@@ -264,6 +264,9 @@ export default function Dashboard() {className="col-span-1 min-h-24 xl:col-span-3"projectId={projectId}globalFilterState={mergedFilterState}+ fromTimestamp={fromTimestamp}+ toTimestamp={toTimestamp}+ userAndEnvFilterState={[...userFilterState, ...environmentFilter]}agg={agg}isLoading={environmentFilterOptions.isLoading}/>