🪢 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
fix: fix model charts (#6202)
Max Deichmann48df0e04de45
diff --git a/packages/shared/src/server/repositories/dashboards.ts b/packages/shared/src/server/repositories/dashboards.tsindex 875137e44f..51edac36de 100644--- a/packages/shared/src/server/repositories/dashboards.ts+++ b/packages/shared/src/server/repositories/dashboards.ts@@ -253,7 +253,7 @@ export const groupTracesByTime = async (}));};-export const getObservationUsageByTime = async (+export const getTotalObservationUsageByTimeByModel = async (projectId: string,filter: FilterState,) => {@@ -324,7 +324,7 @@ export const getObservationUsageByTime = async (});return result.map((row) => ({- start_time: parseClickhouseUTCDateTimeFormat(row.start_time),+ startTime: parseClickhouseUTCDateTimeFormat(row.start_time),units: Object.fromEntries(Object.entries(row.units ?? {}).map(([key, value]) => [key,@@ -337,10 +337,206 @@ export const getObservationUsageByTime = async (Number(value),]),),- provided_model_name: row.provided_model_name,+ model: row.provided_model_name,}));};+export const getObservationCostByTypeByTime = async (+ projectId: string,+ filter: FilterState,+) => {+ const { envFilter, remainingFilters } =+ extractEnvironmentFilterFromFilters(filter);+ const environmentFilter = new FilterList(+ convertEnvFilterToClickhouseFilter(envFilter),+ ).apply();+ const chFilter = new FilterList(+ createFilterFromFilterState(remainingFilters, dashboardColumnDefinitions),+ );++ const appliedFilter = chFilter.apply();++ const tracesFilter = chFilter.find((f) => f.clickhouseTable === "traces");+ const timeFilter = tracesFilter+ ? (chFilter.find(+ (f) =>+ f.clickhouseTable === "observations" &&+ f.field.includes("start_time") &&+ (f.operator === ">=" || f.operator === ">"),+ ) as DateTimeFilter | undefined)+ : undefined;++ const [orderByQuery, orderByParams, bucketSizeInSeconds] = orderByTimeSeries(+ filter,+ "start_time",+ );++ const query = `+ SELECT+ start_time,+ groupArray((cost_key, cost_sum)) AS costs+ FROM (+ SELECT+ ${selectTimeseriesColumn(bucketSizeInSeconds, "start_time", "start_time")},+ cost_key,+ SUM(cost) AS cost_sum+ FROM+ observations o FINAL+ ${tracesFilter ? "LEFT JOIN traces t ON o.trace_id = t.id AND o.project_id = t.project_id" : ""}+ ARRAY JOIN+ mapKeys(cost_details) AS cost_key,+ mapValues(cost_details) AS cost+ WHERE project_id = {projectId: String}+ AND ${appliedFilter.query}+ ${environmentFilter.query ? `AND ${environmentFilter.query}` : ""}+ ${timeFilter ? `AND t.timestamp >= {traceTimestamp: DateTime64(3)} - ${OBSERVATIONS_TO_TRACE_INTERVAL}` : ""}+ GROUP BY+ start_time,+ cost_key+ )+ GROUP BY+ start_time+ ${orderByQuery}+ `;++ const result = await queryClickhouse<{+ start_time: string;+ costs: Array<[string, number | null]>;+ }>({+ query,+ params: {+ projectId,+ ...appliedFilter.params,+ ...environmentFilter.params,+ ...orderByParams,+ ...(timeFilter+ ? { traceTimestamp: convertDateToClickhouseDateTime(timeFilter.value) }+ : {}),+ },+ tags: {+ feature: "dashboard",+ type: "observationCostByTypeByTime",+ kind: "analytic",+ projectId,+ },+ });++ const types = result.flatMap((row) => {+ return row.costs.map((cost) => cost[0]);+ });++ const uniqueTypes = [...new Set(types)];++ return result.flatMap((row) => {+ const intervalStart = parseClickhouseUTCDateTimeFormat(row.start_time);+ return uniqueTypes.map((type) => ({+ intervalStart: intervalStart,+ key: type,+ sum: row.costs.find((cost) => cost[0] === type)?.[1]+ ? Number(row.costs.find((cost) => cost[0] === type)?.[1])+ : 0,+ }));+ });+};++export const getObservationUsageByTypeByTime = async (+ projectId: string,+ filter: FilterState,+) => {+ const { envFilter, remainingFilters } =+ extractEnvironmentFilterFromFilters(filter);+ const environmentFilter = new FilterList(+ convertEnvFilterToClickhouseFilter(envFilter),+ ).apply();+ const chFilter = new FilterList(+ createFilterFromFilterState(remainingFilters, dashboardColumnDefinitions),+ );++ const appliedFilter = chFilter.apply();++ const tracesFilter = chFilter.find((f) => f.clickhouseTable === "traces");+ const timeFilter = tracesFilter+ ? (chFilter.find(+ (f) =>+ f.clickhouseTable === "observations" &&+ f.field.includes("start_time") &&+ (f.operator === ">=" || f.operator === ">"),+ ) as DateTimeFilter | undefined)+ : undefined;++ const [orderByQuery, orderByParams, bucketSizeInSeconds] = orderByTimeSeries(+ filter,+ "start_time",+ );++ const query = `+ SELECT+ start_time,+ groupArray((usage_key, usage_sum)) AS usages+ FROM (+ SELECT+ ${selectTimeseriesColumn(bucketSizeInSeconds, "start_time", "start_time")} ,+ usage_key,+ SUM(usage) AS usage_sum+ FROM+ observations o FINAL+ ${tracesFilter ? "LEFT JOIN traces t ON o.trace_id = t.id AND o.project_id = t.project_id" : ""}+ ARRAY JOIN+ mapKeys(usage_details) AS usage_key,+ mapValues(usage_details) AS usage+ WHERE project_id = {projectId: String}+ AND ${appliedFilter.query}+ ${environmentFilter.query ? `AND ${environmentFilter.query}` : ""}+ ${timeFilter ? `AND t.timestamp >= {traceTimestamp: DateTime64(3)} - ${OBSERVATIONS_TO_TRACE_INTERVAL}` : ""}+ GROUP BY+ start_time,+ usage_key+ )+ GROUP BY+ start_time+ ${orderByQuery}+ `;++ const result = await queryClickhouse<{+ start_time: string;+ usages: Array<[string, number | null]>;+ }>({+ query,+ params: {+ projectId,+ ...appliedFilter.params,+ ...environmentFilter.params,+ ...orderByParams,+ ...(timeFilter+ ? { traceTimestamp: convertDateToClickhouseDateTime(timeFilter.value) }+ : {}),+ },+ tags: {+ feature: "dashboard",+ type: "observationUsageByTime",+ kind: "analytic",+ projectId,+ },+ });++ const types = result.flatMap((row) => {+ return row.usages.map((usage) => usage[0]);+ });++ const uniqueTypes = [...new Set(types)];++ return result.flatMap((row) => {+ const intervalStart = parseClickhouseUTCDateTimeFormat(row.start_time);+ return uniqueTypes.map((type) => ({+ intervalStart: intervalStart,+ key: type,+ sum: row.usages.find((usage) => usage[0] === type)?.[1]+ ? Number(row.usages.find((usage) => usage[0] === type)?.[1])+ : 0,+ }));+ });+};+export const getDistinctModels = async (projectId: string,filter: FilterState,diff --git a/web/src/__tests__/async/repositories/dashboard-repository.servertest.ts b/web/src/__tests__/async/repositories/dashboard-repository.servertest.tsindex 3437c9406a..4cff16701b 100644--- a/web/src/__tests__/async/repositories/dashboard-repository.servertest.ts+++ b/web/src/__tests__/async/repositories/dashboard-repository.servertest.ts@@ -1,5 +1,13 @@import { prepareUsageDataForTimeseriesChart } from "@/src/features/dashboard/components/ModelUsageChart";-import { orderByTimeSeries } from "@langfuse/shared/src/server";+import {+ orderByTimeSeries,+ getObservationUsageByTypeByTime,+ createOrgProjectAndApiKey,+ createTrace,+ createTracesCh,+ createObservationsCh,+ createObservation,+} from "@langfuse/shared/src/server";describe("orderByTimeSeries", () => {it("should return correct bucket size and query for 1 hour time range", () => {@@ -140,4 +148,103 @@ describe("orderByTimeSeries", () => {]);});});++ describe("getObservationUsageByTypeByTime", () => {+ const mockFilter = [+ {+ type: "datetime" as const,+ column: "timestamp",+ operator: ">=" as const,+ value: new Date("2024-01-01T00:00:00Z"),+ },+ {+ type: "datetime" as const,+ column: "timestamp",+ operator: "<=" as const,+ value: new Date("2024-01-02T01:00:00Z"),+ },+ ];++ it("should return usage data grouped by time and type", async () => {+ const { projectId } = await createOrgProjectAndApiKey();++ const trace = createTrace({+ name: "trace-name",+ project_id: projectId,+ timestamp: new Date("2024-01-01T01:00:00Z").getTime(),+ });++ const trace2 = createTrace({+ name: "trace-name",+ project_id: projectId,+ timestamp: new Date("2024-01-01T04:00:00Z").getTime(),+ });++ await createTracesCh([trace, trace2]);++ const obs1 = createObservation({+ trace_id: trace.id,+ project_id: trace.project_id,+ usage_details: { input: 1, output: 2, total: 3 },+ start_time: new Date("2024-01-01T01:00:00Z").getTime(),+ });++ const obs2 = createObservation({+ trace_id: trace.id,+ project_id: trace.project_id,+ usage_details: { input: 4, output: 5, total: 9 },+ start_time: new Date("2024-01-01T01:00:00Z").getTime(),+ });++ const obs3 = createObservation({+ trace_id: trace2.id,+ project_id: trace.project_id,+ usage_details: { input: 400, output: 500, total: 900 },+ start_time: new Date("2024-01-01T04:00:00Z").getTime(),+ });++ await createObservationsCh([obs1, obs2, obs3]);++ const result = await getObservationUsageByTypeByTime(+ projectId,+ mockFilter,+ );++ // Verify the structure of the returned data+ expect(result).toEqual(+ expect.arrayContaining([+ {+ intervalStart: new Date("2024-01-01T01:00:00Z"),+ key: "input",+ sum: 5,+ },+ {+ intervalStart: new Date("2024-01-01T01:00:00Z"),+ key: "output",+ sum: 7,+ },+ {+ intervalStart: new Date("2024-01-01T01:00:00Z"),+ key: "total",+ sum: 12,+ },+ {+ intervalStart: new Date("2024-01-01T04:00:00Z"),+ key: "input",+ sum: 400,+ },+ {+ intervalStart: new Date("2024-01-01T04:00:00Z"),+ key: "output",+ sum: 500,+ },+ {+ intervalStart: new Date("2024-01-01T04:00:00Z"),+ key: "total",+ sum: 900,+ },+ ]),+ );+ });+ });});diff --git a/web/src/features/dashboard/components/ModelUsageChart.tsx b/web/src/features/dashboard/components/ModelUsageChart.tsxindex 53184fd020..130a5ede5c 100644--- a/web/src/features/dashboard/components/ModelUsageChart.tsx+++ b/web/src/features/dashboard/components/ModelUsageChart.tsx@@ -86,7 +86,7 @@ export const ModelUsageChart = ({orderBy: [{ column: "calculatedTotalCost", direction: "DESC", agg: "SUM" },],- queryName: "observations-usage-timeseries",+ queryName: "observations-total-cost-by-model-timeseries",},{enabled: !isLoading && selectedModels.length > 0 && allModels.length > 0,@@ -98,6 +98,97 @@ 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",+ 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-cost-by-type-timeseries",+ },+ {+ enabled: !isLoading && selectedModels.length > 0 && allModels.length > 0,+ trpc: {+ context: {+ skipBatch: true,+ },+ },+ },+ );++ 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",+ 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: "totalTokens", direction: "DESC", agg: "SUM" }],+ queryName: "observations-usage-by-type-timeseries",+ },+ {+ enabled: !isLoading && selectedModels.length > 0 && allModels.length > 0,+ trpc: {+ context: {+ skipBatch: true,+ },+ },+ },+ );const typedData = (queryResult.data as ModelUsageReturnType[]) ?? [];const usageTypeMap = prepareUsageDataForTimeseriesChart(@@ -111,42 +202,42 @@ export const ModelUsageChart = ({...new Set(usageData.map((row) => row.model).filter(Boolean)),];- const unitsByType =- usageData && allModels.length > 0+ const costByType =+ queryCostByType.data && allModels.length > 0? fillMissingValuesAndTransform(- extractTimeSeriesData(usageData, "startTime", [+ extractTimeSeriesData(queryCostByType.data, "intervalStart", [{- uniqueIdentifierColumns: [{ accessor: "usageType" }],- valueColumn: "units",+ uniqueIdentifierColumns: [{ accessor: "key" }],+ valueColumn: "sum",},]),- Array.from(usageTypeMap.keys()),+ [],): [];- const unitsByModel =- usageData && allModels.length > 0+ const unitsByType =+ queryUsageByType.data && allModels.length > 0? fillMissingValuesAndTransform(- extractTimeSeriesData(usageData, "startTime", [+ extractTimeSeriesData(queryUsageByType.data, "intervalStart", [{- uniqueIdentifierColumns: [{ accessor: "model" }],- valueColumn: "units",+ uniqueIdentifierColumns: [{ accessor: "key" }],+ valueColumn: "sum",},]),- currentModels,+ [],): [];- const costByType =+ const unitsByModel =usageData && allModels.length > 0? fillMissingValuesAndTransform(extractTimeSeriesData(usageData, "startTime", [{- uniqueIdentifierColumns: [{ accessor: "usageType" }],- valueColumn: "cost",+ uniqueIdentifierColumns: [{ accessor: "model" }],+ valueColumn: "units",},]),- Array.from(usageTypeMap.keys()),+ currentModels,): [];diff --git a/web/src/features/dashboard/server/dashboard-router.ts b/web/src/features/dashboard/server/dashboard-router.tsindex ffe7ba7a16..97dc93afb0 100644--- a/web/src/features/dashboard/server/dashboard-router.ts+++ b/web/src/features/dashboard/server/dashboard-router.ts@@ -15,7 +15,6 @@ import {getTracesGroupedByName,getObservationsCostGroupedByName,getScoreAggregate,- getObservationUsageByTime,groupTracesByTime,getDistinctModels,getScoresAggregateOverTime,@@ -30,6 +29,9 @@ import {getObservationsStatusTimeSeries,extractFromAndToTimestampsFromFilter,logger,+ getTotalObservationUsageByTimeByModel,+ getObservationCostByTypeByTime,+ getObservationUsageByTypeByTime,} from "@langfuse/shared/src/server";import { type DatabaseRow } from "@/src/server/api/services/sqlInterface";import { dashboardColumnDefinitions } from "@langfuse/shared";@@ -53,7 +55,9 @@ export const dashboardRouter = createTRPCRouter({"observations-model-cost","score-aggregate","traces-timeseries",- "observations-usage-timeseries",+ "observations-total-cost-by-model-timeseries",+ "observations-usage-by-type-timeseries",+ "observations-cost-by-type-timeseries","distinct-models","scores-aggregate-timeseries","observations-usage-by-users",@@ -131,22 +135,33 @@ export const dashboardRouter = createTRPCRouter({);return rows as DatabaseRow[];- case "observations-usage-timeseries":+ case "observations-total-cost-by-model-timeseries":const dateTruncObs = extractTimeSeries(input.groupBy);if (!dateTruncObs) {return [];}- const rowsObs = await getObservationUsageByTime(+ const rowsObs = await getTotalObservationUsageByTimeByModel(input.projectId,input.filter ?? [],);- return rowsObs.map((row) => ({- startTime: row.start_time,- units: row.units,- cost: row.cost,- model: row.provided_model_name,- })) as DatabaseRow[];+ return rowsObs as DatabaseRow[];++ case "observations-usage-by-type-timeseries":+ const rowsObsType = await getObservationUsageByTypeByTime(+ input.projectId,+ input.filter ?? [],+ );++ return rowsObsType as DatabaseRow[];++ case "observations-cost-by-type-timeseries":+ const rowsObsCostByType = await getObservationCostByTypeByTime(+ input.projectId,+ input.filter ?? [],+ );++ return rowsObsCostByType as DatabaseRow[];case "distinct-models":const models = await getDistinctModels(