Skip to content

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

chore: migrate score charts to new query builder (#6294)

Steffen Schmitz3b4800c37a85
diff --git a/web/src/__tests__/queryBuilder.servertest.ts b/web/src/__tests__/queryBuilder.servertest.ts
index 173472e2e9..40b6ab3472 100644
--- a/web/src/__tests__/queryBuilder.servertest.ts
+++ b/web/src/__tests__/queryBuilder.servertest.ts
@@ -37,6 +37,29 @@ describe("queryBuilder", () => {
orderBy: null,
} as QueryType,
],
+ // [
+ // "trace query with metric filter",
+ // {
+ // view: "traces",
+ // dimensions: [{ field: "name" }],
+ // metrics: [
+ // { measure: "count", aggregation: "count" },
+ // { measure: "observationsCount", aggregation: "p95" },
+ // ],
+ // filters: [
+ // {
+ // column: "observationsCount",
+ // operator: ">",
+ // value: 0,
+ // type: "number",
+ // },
+ // ],
+ // timeDimension: null,
+ // fromTimestamp: "2025-01-01T00:00:00.000Z",
+ // toTimestamp: "2025-03-01T00:00:00.000Z",
+ // orderBy: null,
+ // } as QueryType,
+ // ],
[
"query with auto time dimension for month granularity",
{
@@ -1668,8 +1691,10 @@ describe("queryBuilder", () => {
);
// Verify SQL includes segment filter for NUMERIC types
- expect(compiledQuery).toContain("data_type = {");
- expect(Object.values(parameters)).toContain("NUMERIC");
+ // Verify SQL includes segment filter for non-NUMERIC types
+ expect(compiledQuery).toContain("position(scores_numeric.data_type, {");
+ expect(compiledQuery).toContain(": String}) = 0");
+ expect(Object.values(parameters)).toContain("CATEGORICAL");
const result = await (
await clickhouseClient().query({
@@ -1930,6 +1955,127 @@ describe("queryBuilder", () => {
expect(summaryTraceRow.count_count).toBe("1"); // 1 score (accuracy)
expect(parseFloat(summaryTraceRow.avg_value)).toBeCloseTo(0.95, 2);
});
+
+ it("should filter boolean scores correctly", async () => {
+ // Setup
+ const projectId = randomUUID();
+
+ // Create traces
+ const traces = [
+ createTrace({
+ project_id: projectId,
+ name: "trace-1",
+ environment: "production",
+ }),
+ createTrace({
+ project_id: projectId,
+ name: "trace-2",
+ environment: "production",
+ }),
+ ];
+ await createTracesCh(traces);
+
+ // Create observations
+ const observations = [
+ createObservation({
+ project_id: projectId,
+ trace_id: traces[0].id,
+ name: "observation-1",
+ environment: "production",
+ }),
+ createObservation({
+ project_id: projectId,
+ trace_id: traces[1].id,
+ name: "observation-2",
+ environment: "production",
+ }),
+ ];
+ await createObservationsCh(observations);
+
+ // Create boolean scores
+ const scores = [
+ {
+ name: "is_hallucination",
+ traceId: traces[0].id,
+ observationId: observations[0].id,
+ stringValue: "true",
+ dataType: "BOOLEAN" as const,
+ },
+ {
+ name: "is_hallucination",
+ traceId: traces[1].id,
+ observationId: observations[1].id,
+ stringValue: "false",
+ dataType: "BOOLEAN" as const,
+ },
+ {
+ name: "is_helpful",
+ traceId: traces[0].id,
+ observationId: observations[0].id,
+ stringValue: "false",
+ dataType: "BOOLEAN" as const,
+ },
+ {
+ name: "is_helpful",
+ traceId: traces[1].id,
+ observationId: observations[1].id,
+ stringValue: "true",
+ dataType: "BOOLEAN" as const,
+ },
+ ];
+
+ await setupScores(projectId, scores);
+
+ // Define query to filter for true Boolean scores only
+ const query: QueryType = {
+ view: "scores-numeric",
+ dimensions: [{ field: "name" }],
+ metrics: [{ measure: "count", aggregation: "count" }],
+ filters: [
+ {
+ column: "name",
+ operator: "any of",
+ value: ["is_hallucination", "is_helpful"],
+ type: "stringOptions",
+ },
+ ],
+ timeDimension: null,
+ fromTimestamp: new Date(
+ new Date().setDate(new Date().getDate() - 1),
+ ).toISOString(),
+ toTimestamp: new Date(
+ new Date().setDate(new Date().getDate() + 1),
+ ).toISOString(),
+ orderBy: null,
+ };
+
+ // Execute query
+ const queryBuilder = new QueryBuilder();
+ const { query: compiledQuery, parameters } = queryBuilder.build(
+ query,
+ projectId,
+ );
+ const result = await (
+ await clickhouseClient().query({
+ query: compiledQuery,
+ query_params: parameters,
+ })
+ ).json();
+
+ // Assert - should only return true scores
+ expect(result.data).toHaveLength(2);
+
+ // Check which scores were true
+ const isHallucination = result.data.find(
+ (row: any) => row.name === "is_hallucination",
+ );
+ const isHelpful = result.data.find(
+ (row: any) => row.name === "is_helpful",
+ );
+
+ expect(isHallucination.count_count).toBe("2");
+ expect(isHelpful.count_count).toBe("2");
+ });
});
describe("scores-categorical view", () => {
@@ -2052,12 +2198,9 @@ describe("queryBuilder", () => {
projectId,
);
- // Verify SQL includes segment filter for non-NUMERIC types
- expect(compiledQuery).toContain(
- "position(scores_categorical.data_type, {",
- );
- expect(compiledQuery).toContain(": String}) = 0");
- expect(Object.values(parameters)).toContain("NUMERIC");
+ // Verify SQL includes segment filter for CATEGORICAL type
+ expect(compiledQuery).toContain("data_type = {");
+ expect(Object.values(parameters)).toContain("CATEGORICAL");
const result = await (
await clickhouseClient().query({
@@ -2066,8 +2209,8 @@ describe("queryBuilder", () => {
})
).json();
- // Assert - should have 6 rows for different name+value combinations
- expect(result.data).toHaveLength(6);
+ // Assert - should have 4 rows for different name+value combinations
+ expect(result.data).toHaveLength(4);
// Check each combination
const evaluationExcellent = result.data.find(
@@ -2093,19 +2236,6 @@ describe("queryBuilder", () => {
row.name === "category" && row.string_value === "factual",
);
expect(categoryFactual.count_count).toBe("1");
-
- // Check boolean scores
- const isCorrectTrue = result.data.find(
- (row: any) =>
- row.name === "is_correct" && row.string_value === "true",
- );
- expect(isCorrectTrue.count_count).toBe("1");
-
- const isCorrectFalse = result.data.find(
- (row: any) =>
- row.name === "is_correct" && row.string_value === "false",
- );
- expect(isCorrectFalse.count_count).toBe("1");
});
it("should filter categorical scores by source", async () => {
@@ -2207,127 +2337,6 @@ describe("queryBuilder", () => {
.sort();
expect(stringValues).toEqual(["command", "statement"]);
});
-
- it("should filter boolean scores correctly", async () => {
- // Setup
- const projectId = randomUUID();
-
- // Create traces
- const traces = [
- createTrace({
- project_id: projectId,
- name: "trace-1",
- environment: "production",
- }),
- createTrace({
- project_id: projectId,
- name: "trace-2",
- environment: "production",
- }),
- ];
- await createTracesCh(traces);
-
- // Create observations
- const observations = [
- createObservation({
- project_id: projectId,
- trace_id: traces[0].id,
- name: "observation-1",
- environment: "production",
- }),
- createObservation({
- project_id: projectId,
- trace_id: traces[1].id,
- name: "observation-2",
- environment: "production",
- }),
- ];
- await createObservationsCh(observations);
-
- // Create boolean scores
- const scores = [
- {
- name: "is_hallucination",
- traceId: traces[0].id,
- observationId: observations[0].id,
- stringValue: "true",
- dataType: "BOOLEAN" as const,
- },
- {
- name: "is_hallucination",
- traceId: traces[1].id,
- observationId: observations[1].id,
- stringValue: "false",
- dataType: "BOOLEAN" as const,
- },
- {
- name: "is_helpful",
- traceId: traces[0].id,
- observationId: observations[0].id,
- stringValue: "false",
- dataType: "BOOLEAN" as const,
- },
- {
- name: "is_helpful",
- traceId: traces[1].id,
- observationId: observations[1].id,
- stringValue: "true",
- dataType: "BOOLEAN" as const,
- },
- ];
-
- await setupScores(projectId, scores);
-
- // Define query to filter for true Boolean scores only
- const query: QueryType = {
- view: "scores-categorical",
- dimensions: [{ field: "name" }],
- metrics: [{ measure: "count", aggregation: "count" }],
- filters: [
- {
- column: "stringValue",
- operator: "=",
- value: "true",
- type: "string",
- },
- ],
- timeDimension: null,
- fromTimestamp: new Date(
- new Date().setDate(new Date().getDate() - 1),
- ).toISOString(),
- toTimestamp: new Date(
- new Date().setDate(new Date().getDate() + 1),
- ).toISOString(),
- orderBy: null,
- };
-
- // Execute query
- const queryBuilder = new QueryBuilder();
- const { query: compiledQuery, parameters } = queryBuilder.build(
- query,
- projectId,
- );
- const result = await (
- await clickhouseClient().query({
- query: compiledQuery,
- query_params: parameters,
- })
- ).json();
-
- // Assert - should only return true scores
- expect(result.data).toHaveLength(2);
-
- // Check which scores were true
- const isHallucination = result.data.find(
- (row: any) => row.name === "is_hallucination",
- );
- const isHelpful = result.data.find(
- (row: any) => row.name === "is_helpful",
- );
-
- expect(isHallucination.count_count).toBe("1");
- expect(isHelpful.count_count).toBe("1");
- });
});
describe("observations view", () => {
diff --git a/web/src/features/dashboard/components/ChartScores.tsx b/web/src/features/dashboard/components/ChartScores.tsx
index 6dd83faf97..5788bb5c34 100644
--- a/web/src/features/dashboard/components/ChartScores.tsx
+++ b/web/src/features/dashboard/components/ChartScores.tsx
@@ -8,55 +8,44 @@ import {
fillMissingValuesAndTransform,
isEmptyTimeSeries,
} from "@/src/features/dashboard/components/hooks";
-import { createTracesTimeFilter } from "@/src/features/dashboard/lib/dashboard-utils";
-import {
- dashboardDateRangeAggregationSettings,
- type DashboardDateRangeAggregationOption,
-} from "@/src/utils/date-range-utils";
+import { type DashboardDateRangeAggregationOption } from "@/src/utils/date-range-utils";
import { getScoreDataTypeIcon } from "@/src/features/scores/components/ScoreDetailColumnHelpers";
import { NoDataOrLoading } from "@/src/components/NoDataOrLoading";
+import {
+ type QueryType,
+ mapLegacyUiTableFilterToView,
+} from "@/src/features/query";
+import { type DatabaseRow } from "@/src/server/api/services/sqlInterface";
export function ChartScores(props: {
className?: string;
agg: DashboardDateRangeAggregationOption;
globalFilterState: FilterState;
+ fromTimestamp: Date;
+ toTimestamp: Date;
projectId: string;
isLoading?: boolean;
}) {
- const scores = api.dashboard.chart.useQuery(
+ const scoresQuery: QueryType = {
+ view: "scores-numeric",
+ dimensions: [{ field: "name" }, { field: "dataType" }, { field: "source" }],
+ metrics: [{ measure: "value", aggregation: "avg" }],
+ filters: mapLegacyUiTableFilterToView(
+ "scores-numeric",
+ props.globalFilterState,
+ ),
+ timeDimension: {
+ granularity: "auto",
+ },
+ fromTimestamp: props.fromTimestamp.toISOString(),
+ toTimestamp: props.toTimestamp.toISOString(),
+ orderBy: null,
+ };
+
+ const scores = api.dashboard.executeQuery.useQuery(
{
projectId: props.projectId,
- from: "traces_scores",
- select: [
- { column: "scoreName" },
- { column: "scoreDataType" },
- { column: "scoreSource" },
- { column: "value", agg: "AVG" },
- ],
- filter: [
- ...createTracesTimeFilter(props.globalFilterState, "scoreTimestamp"),
- {
- type: "stringOptions",
- column: "scoreDataType",
- value: ["NUMERIC", "BOOLEAN"],
- operator: "any of",
- },
- ],
- groupBy: [
- {
- type: "datetime",
- column: "scoreTimestamp",
- temporalUnit:
- dashboardDateRangeAggregationSettings[props.agg].date_trunc,
- },
- {
- type: "string",
- column: "scoreName",
- },
- { type: "string", column: "scoreDataType" },
- { type: "string", column: "scoreSource" },
- ],
- queryName: "scores-aggregate-timeseries",
+ query: scoresQuery,
},
{
trpc: {
@@ -70,21 +59,21 @@ export function ChartScores(props: {
const extractedScores = scores.data
? fillMissingValuesAndTransform(
- extractTimeSeriesData(scores.data, "scoreTimestamp", [
+ extractTimeSeriesData(scores.data as DatabaseRow[], "time_dimension", [
{
uniqueIdentifierColumns: [
{
- accessor: "scoreDataType",
+ accessor: "data_type",
formatFct: (value) =>
getScoreDataTypeIcon(value as ScoreDataType),
},
- { accessor: "scoreName" },
+ { accessor: "name" },
{
- accessor: "scoreSource",
+ accessor: "source",
formatFct: (value) => `(${value.toLowerCase()})`,
},
],
- valueColumn: "avgValue",
+ valueColumn: "avg_value",
},
]),
)
diff --git a/web/src/features/dashboard/components/LatencyChart.tsx b/web/src/features/dashboard/components/LatencyChart.tsx
index bc79b141a5..ca6aa559e1 100644
--- a/web/src/features/dashboard/components/LatencyChart.tsx
+++ b/web/src/features/dashboard/components/LatencyChart.tsx
@@ -52,7 +52,6 @@ export const GenerationLatencyChart = ({
toTimestamp,
);
- // Define the query for model latencies using the new QueryType structure
const latenciesQuery: QueryType = {
view: "observations",
dimensions: [{ field: "providedModelName" }],
@@ -86,7 +85,6 @@ export const GenerationLatencyChart = ({
orderBy: null,
};
- // Execute the query using the new dashboard.executeQuery functionality
const latencies = api.dashboard.executeQuery.useQuery(
{
projectId,
diff --git a/web/src/features/dashboard/components/LatencyTables.tsx b/web/src/features/dashboard/components/LatencyTables.tsx
index 4e1d2b054e..07e34e572f 100644
--- a/web/src/features/dashboard/components/LatencyTables.tsx
+++ b/web/src/features/dashboard/components/LatencyTables.tsx
@@ -25,7 +25,6 @@ export const LatencyTables = ({
toTimestamp: Date;
isLoading?: boolean;
}) => {
- // Define the query for generation latencies using the new QueryType structure
const generationsLatenciesQuery: QueryType = {
view: "observations",
dimensions: [{ field: "name" }],
@@ -50,7 +49,6 @@ export const LatencyTables = ({
orderBy: [{ field: "p95_latency", direction: "desc" }],
};
- // Execute the query using the new dashboard.executeQuery functionality
const generationsLatencies = api.dashboard.executeQuery.useQuery(
{
projectId,
@@ -66,7 +64,6 @@ export const LatencyTables = ({
},
);
- // Define the query for span latencies using the new QueryType structure
const spansLatenciesQuery: QueryType = {
view: "observations",
dimensions: [{ field: "name" }],
@@ -91,7 +88,6 @@ export const LatencyTables = ({
orderBy: [{ field: "p95_latency", direction: "desc" }],
};
- // Execute the query using the new dashboard.executeQuery functionality
const spansLatencies = api.dashboard.executeQuery.useQuery(
{
projectId,
@@ -107,7 +103,6 @@ export const LatencyTables = ({
},
);
- // Define the query for trace latencies using the new QueryType structure
const tracesLatenciesQuery: QueryType = {
view: "traces",
dimensions: [{ field: "name" }],
@@ -124,7 +119,6 @@ export const LatencyTables = ({
orderBy: [{ field: "p95_latency", direction: "desc" }],
};
- // Execute the query using the new dashboard.executeQuery functionality
const tracesLatencies = api.dashboard.executeQuery.useQuery(
{
projectId,
diff --git a/web/src/features/dashboard/components/ModelUsageChart.tsx b/web/src/features/dashboard/components/ModelUsageChart.tsx
index 7c9d17aae3..68592aa4be 100644
--- a/web/src/features/dashboard/components/ModelUsageChart.tsx
+++ b/web/src/features/dashboard/components/ModelUsageChart.tsx
@@ -59,7 +59,6 @@ export const ModelUsageChart = ({
toTimestamp,
);
- // Define the query for model usage data using the new QueryType structure
const modelUsageQuery: QueryType = {
view: "observations",
dimensions: [{ field: "providedModelName" }],
@@ -90,7 +89,6 @@ export const ModelUsageChart = ({
orderBy: null,
};
- // Execute the query using the new dashboard.executeQuery functionality
const queryResult = api.dashboard.executeQuery.useQuery(
{
projectId,
diff --git a/web/src/features/dashboard/components/UserChart.tsx b/web/src/features/dashboard/components/UserChart.tsx
index 3b500aef56..340534a2ad 100644
--- a/web/src/features/dashboard/components/UserChart.tsx
+++ b/web/src/features/dashboard/components/UserChart.tsx
@@ -35,7 +35,6 @@ export const UserChart = ({
isLoading?: boolean;
}) => {
const [isExpanded, setIsExpanded] = useState(false);
- // Define the query for user cost data using the new QueryType structure
const userCostQuery: QueryType = {
view: "observations",
dimensions: [{ field: "userId" }],
@@ -58,7 +57,6 @@ export const UserChart = ({
orderBy: null,
};
- // Execute the query using the new dashboard.executeQuery functionality
const user = api.dashboard.executeQuery.useQuery(
{
projectId,
@@ -74,7 +72,6 @@ export const UserChart = ({
},
);
- // Define the query for trace count data using the new QueryType structure
const traceCountQuery: QueryType = {
view: "traces",
dimensions: [{ field: "userId" }],
@@ -86,7 +83,6 @@ export const UserChart = ({
orderBy: null,
};
- // Execute the query using the new dashboard.executeQuery functionality
const traces = api.dashboard.executeQuery.useQuery(
{
projectId,
diff --git a/web/src/features/dashboard/components/score-analytics/CategoricalScoreChart.tsx b/web/src/features/dashboard/components/score-analytics/CategoricalScoreChart.tsx
index 4db1c41274..1e8f2129dd 100644
--- a/web/src/features/dashboard/components/score-analytics/CategoricalScoreChart.tsx
+++ b/web/src/features/dashboard/components/score-analytics/CategoricalScoreChart.tsx
@@ -1,79 +1,67 @@
import { api } from "@/src/utils/api";
import { type FilterState } from "@langfuse/shared";
import { createTracesTimeFilter } from "@/src/features/dashboard/lib/dashboard-utils";
-import {
- type DashboardDateRangeAggregationOption,
- dashboardDateRangeAggregationSettings,
-} from "@/src/utils/date-range-utils";
+import { type DashboardDateRangeAggregationOption } from "@/src/utils/date-range-utils";
import React, { useMemo } from "react";
import { DashboardCategoricalScoreAdapter } from "@/src/features/scores/adapters";
import { type ScoreData } from "@/src/features/scores/types";
import { CategoricalChart } from "@/src/features/scores/components/ScoreChart";
+import {
+ type QueryType,
+ mapLegacyUiTableFilterToView,
+} from "@/src/features/query";
+import { type DatabaseRow } from "@/src/server/api/services/sqlInterface";
export function CategoricalScoreChart(props: {
projectId: string;
scoreData: ScoreData;
globalFilterState: FilterState;
+ fromTimestamp: Date;
+ toTimestamp: Date;
agg?: DashboardDateRangeAggregationOption;
}) {
- const scores = api.dashboard.chart.useQuery(
+ const scoresQuery: QueryType = {
+ view: "scores-categorical",
+ dimensions: [{ field: "name" }, { field: "stringValue" }],
+ metrics: [{ measure: "count", aggregation: "count" }],
+ filters: [
+ ...mapLegacyUiTableFilterToView(
+ "scores-categorical",
+ createTracesTimeFilter(props.globalFilterState, "scoreTimestamp"),
+ ),
+ {
+ column: "name",
+ operator: "=",
+ value: props.scoreData.name,
+ type: "string",
+ },
+ {
+ column: "source",
+ operator: "=",
+ value: props.scoreData.source,
+ type: "string",
+ },
+ {
+ column: "dataType",
+ operator: "=",
+ value: props.scoreData.dataType,
+ type: "string",
+ },
+ ],
+ timeDimension: props.agg
+ ? {
+ granularity: "day",
+ }
+ : null,
+ fromTimestamp: props.fromTimestamp.toISOString(),
+ toTimestamp: props.toTimestamp.toISOString(),
+ orderBy: null,
+ };
+
+ const scores = api.dashboard.executeQuery.useQuery(
{
projectId: props.projectId,
- from: "traces_scores",
- select: [
- { column: "scoreName" },
- { column: "scoreDataType" },
- { column: "scoreSource" },
- { column: "stringValue" },
- { column: "stringValue", agg: "COUNT" },
- ],
- filter: [
- ...createTracesTimeFilter(props.globalFilterState, "scoreTimestamp"),
- {
- type: "string",
- column: "scoreName",
- value: props.scoreData.name,
- operator: "=",
- },
- {
- type: "string",
- column: "scoreSource",
- value: props.scoreData.source,
- operator: "=",
- },
- {
- type: "string",
- column: "scoreDataType",
- value: props.scoreData.dataType,
- operator: "=",
- },
- ],
- groupBy: [
- { type: "string", column: "stringValue" },
- {
- type: "string",
- column: "scoreName",
- },
- {
- type: "string",
- column: "scoreSource",
- },
- {
- type: "string",
- column: "scoreDataType",
- },
- ...(props.agg
- ? [
- {
- type: "datetime",
- column: "scoreTimestamp",
- temporalUnit:
- dashboardDateRangeAggregationSettings[props.agg].date_trunc,
- } as const,
- ]
- : []),
- ],
- queryName: "categorical-score-chart",
+ query: scoresQuery,
},
{
trpc: {
@@ -88,8 +76,12 @@ export function CategoricalScoreChart(props: {
if (!scores.data) return { chartData: [], chartLabels: [] };
const adapter = new DashboardCategoricalScoreAdapter(
- scores.data,
- "scoreTimestamp",
+ scores.data.map((row) => ({
+ ...row,
+ scoreValue: row.string_value,
+ count: row.count_count,
+ })) as DatabaseRow[],
+ "time_dimension",
props.agg,
);
return adapter.toChartData();
diff --git a/web/src/features/dashboard/components/score-analytics/NumericScoreTimeSeriesChart.tsx b/web/src/features/dashboard/components/score-analytics/NumericScoreTimeSeriesChart.tsx
index d681667601..e76b3647d3 100644
--- a/web/src/features/dashboard/components/score-analytics/NumericScoreTimeSeriesChart.tsx
+++ b/web/src/features/dashboard/components/score-analytics/NumericScoreTimeSeriesChart.tsx
@@ -13,12 +13,14 @@ import {
isEmptyTimeSeries,
} from "@/src/features/dashboard/components/hooks";
import { createTracesTimeFilter } from "@/src/features/dashboard/lib/dashboard-utils";
-import {
- type DashboardDateRangeAggregationOption,
- dashboardDateRangeAggregationSettings,
-} from "@/src/utils/date-range-utils";
+import { type DashboardDateRangeAggregationOption } from "@/src/utils/date-range-utils";
import React, { useMemo } from "react";
import { NoDataOrLoading } from "@/src/components/NoDataOrLoading";
+import {
+ type QueryType,
+ mapLegacyUiTableFilterToView,
+} from "@/src/features/query";
+import { type DatabaseRow } from "@/src/server/api/services/sqlInterface";
export function NumericScoreTimeSeriesChart(props: {
projectId: string;
@@ -27,54 +29,49 @@ export function NumericScoreTimeSeriesChart(props: {
name: string;
agg: DashboardDateRangeAggregationOption;
globalFilterState: FilterState;
+ fromTimestamp: Date;
+ toTimestamp: Date;
}) {
- const scores = api.dashboard.chart.useQuery(
+ const scoresQuery: QueryType = {
+ view: "scores-numeric",
+ dimensions: [{ field: "name" }],
+ metrics: [{ measure: "value", aggregation: "avg" }],
+ filters: [
+ ...mapLegacyUiTableFilterToView(
+ "scores-numeric",
+ createTracesTimeFilter(props.globalFilterState, "scoreTimestamp"),
+ ),
+ {
+ column: "name",
+ operator: "=",
+ value: props.name,
+ type: "string",
+ },
+ {
+ column: "source",
+ operator: "=",
+ value: props.source as string,
+ type: "string",
+ },
+ {
+ column: "dataType",
+ operator: "=",
+ value: props.dataType as string,
+ type: "string",
+ },
+ ],
+ timeDimension: {
+ granularity: "auto",
+ },
+ fromTimestamp: props.fromTimestamp.toISOString(),
+ toTimestamp: props.toTimestamp.toISOString(),
+ orderBy: null,
+ };
+
+ const scores = api.dashboard.executeQuery.useQuery(
{
projectId: props.projectId,
- from: "traces_scores",
- select: [{ column: "scoreName" }, { column: "value", agg: "AVG" }],
- filter: [
- ...createTracesTimeFilter(props.globalFilterState, "scoreTimestamp"),
- {
- type: "string",
- column: "scoreName",
- value: props.name,
- operator: "=",
- },
- {
- type: "string",
- column: "scoreSource",
- value: props.source as string,
- operator: "=",
- },
- {
- type: "string",
- column: "scoreDataType",
- value: props.dataType as string,
- operator: "=",
- },
- ],
- groupBy: [
- {
- type: "datetime",
- column: "scoreTimestamp",
- temporalUnit:
- dashboardDateRangeAggregationSettings[props.agg].date_trunc,
- },
- {
- type: "string",
- column: "scoreName",
- },
- {
- type: "string",
- column: "scoreSource",
- },
- {
- type: "string",
- column: "scoreDataType",
- },
- ],
- queryName: "numeric-score-time-series",
+ query: scoresQuery,
},
{
trpc: {
@@ -88,12 +85,16 @@ export function NumericScoreTimeSeriesChart(props: {
const extractedScores = useMemo(() => {
return scores.data
? fillMissingValuesAndTransform(
- extractTimeSeriesData(scores.data, "scoreTimestamp", [
- {
- uniqueIdentifierColumns: [{ accessor: "scoreName" }],
- valueColumn: "avgValue",
- },
- ]),
+ extractTimeSeriesData(
+ scores.data as DatabaseRow[],
+ "time_dimension",
+ [
+ {
+ uniqueIdentifierColumns: [{ accessor: "name" }],
+ valueColumn: "avg_value",
+ },
+ ],
+ ),
)
: [];
}, [scores.data]);
diff --git a/web/src/features/dashboard/components/score-analytics/ScoreAnalytics.tsx b/web/src/features/dashboard/components/score-analytics/ScoreAnalytics.tsx
index 5c42567742..c18de9ef7b 100644
--- a/web/src/features/dashboard/components/score-analytics/ScoreAnalytics.tsx
+++ b/web/src/features/dashboard/components/score-analytics/ScoreAnalytics.tsx
@@ -25,6 +25,8 @@ export function ScoreAnalytics(props: {
className?: string;
agg: DashboardDateRangeAggregationOption;
globalFilterState: FilterState;
+ fromTimestamp: Date;
+ toTimestamp: Date;
projectId: string;
isLoading?: boolean;
}) {
@@ -129,15 +131,17 @@ export function ScoreAnalytics(props: {
<DocPopup description="Aggregate of up to 10,000 scores" />
)}
</div>
- {(isCategoricalDataType(dataType) ||
- isBooleanDataType(dataType)) && (
+ {isCategoricalDataType(dataType) && (
<CategoricalScoreChart
projectId={props.projectId}
scoreData={scoreData}
globalFilterState={props.globalFilterState}
+ fromTimestamp={props.fromTimestamp}
+ toTimestamp={props.toTimestamp}
/>
)}
- {isNumericDataType(dataType) && (
+ {(isNumericDataType(dataType) ||
+ isBooleanDataType(dataType)) && (
<NumericScoreHistogram
projectId={props.projectId}
source={source}
@@ -154,16 +158,18 @@ export function ScoreAnalytics(props: {
? "Moving average over time"
: "Scores over time"}
</div>
- {(isCategoricalDataType(dataType) ||
- isBooleanDataType(dataType)) && (
+ {isCategoricalDataType(dataType) && (
<CategoricalScoreChart
projectId={props.projectId}
agg={props.agg}
scoreData={scoreData}
globalFilterState={props.globalFilterState}
+ fromTimestamp={props.fromTimestamp}
+ toTimestamp={props.toTimestamp}
/>
)}
- {isNumericDataType(dataType) && (
+ {(isNumericDataType(dataType) ||
+ isBooleanDataType(dataType)) && (
<NumericScoreTimeSeriesChart
agg={props.agg}
source={source}
@@ -171,6 +177,8 @@ export function ScoreAnalytics(props: {
dataType={dataType}
projectId={props.projectId}
globalFilterState={props.globalFilterState}
+ fromTimestamp={props.fromTimestamp}
+ toTimestamp={props.toTimestamp}
/>
)}
</div>
diff --git a/web/src/features/dashboard/server/dashboard-router.ts b/web/src/features/dashboard/server/dashboard-router.ts
index bdbfb6074b..430b97149f 100644
--- a/web/src/features/dashboard/server/dashboard-router.ts
+++ b/web/src/features/dashboard/server/dashboard-router.ts
@@ -5,17 +5,13 @@ import {
} from "@/src/server/api/trpc";
import {
filterInterface,
- type groupByInterface,
sqlInterface,
} from "@/src/server/api/services/sqlInterface";
import { createHistogramData } from "@/src/features/dashboard/lib/score-analytics-utils";
import { TRPCError } from "@trpc/server";
import {
getScoreAggregate,
- getScoresAggregateOverTime,
getNumericScoreHistogram,
- getNumericScoreTimeSeries,
- getCategoricalScoreTimeSeries,
extractFromAndToTimestampsFromFilter,
logger,
getObservationCostByTypeByTime,
@@ -47,14 +43,14 @@ export const dashboardRouter = createTRPCRouter({
"observations-usage-by-type-timeseries",
"observations-cost-by-type-timeseries",
// "distinct-models",
- "scores-aggregate-timeseries",
+ // "scores-aggregate-timeseries",
// "observations-usage-by-users",
// "traces-grouped-by-user",
// "observation-latencies-aggregated",
// "traces-latencies-aggregated",
// "model-latencies-over-time",
- "numeric-score-time-series",
- "categorical-score-chart",
+ // "numeric-score-time-series",
+ // "categorical-score-chart",
// "observations-status-timeseries",
])
.nullish(),
@@ -152,13 +148,13 @@ export const dashboardRouter = createTRPCRouter({
// input.filter ?? [],
// );
// return models as DatabaseRow[];
- case "scores-aggregate-timeseries":
- const aggregatedScores = await getScoresAggregateOverTime(
- input.projectId,
- input.filter ?? [],
- );
-
- return aggregatedScores as DatabaseRow[];
+ // case "scores-aggregate-timeseries":
+ // const aggregatedScores = await getScoresAggregateOverTime(
+ // input.projectId,
+ // input.filter ?? [],
+ // );
+ //
+ // return aggregatedScores as DatabaseRow[];
// case "observations-usage-by-users":
// const rowsUsers = await getModelUsageByUser(
// input.projectId,
@@ -225,25 +221,25 @@ export const dashboardRouter = createTRPCRouter({
// percentile95Duration: row.p95,
// percentile99Duration: row.p99,
// })) as DatabaseRow[];
- case "numeric-score-time-series":
- const dateTruncNumericScoreTimeSeries = extractTimeSeries(
- input.groupBy,
- );
- if (!dateTruncNumericScoreTimeSeries) {
- return [];
- }
- const numericScoreTimeSeries = await getNumericScoreTimeSeries(
- input.projectId,
- input.filter ?? [],
- );
- return numericScoreTimeSeries as DatabaseRow[];
- case "categorical-score-chart":
- const categoricalScoreTimeSeries =
- await getCategoricalScoreTimeSeries(
- input.projectId,
- input.filter ?? [],
- );
- return categoricalScoreTimeSeries as DatabaseRow[];
+ // case "numeric-score-time-series":
+ // const dateTruncNumericScoreTimeSeries = extractTimeSeries(
+ // input.groupBy,
+ // );
+ // if (!dateTruncNumericScoreTimeSeries) {
+ // return [];
+ // }
+ // const numericScoreTimeSeries = await getNumericScoreTimeSeries(
+ // input.projectId,
+ // input.filter ?? [],
+ // );
+ // return numericScoreTimeSeries as DatabaseRow[];
+ // case "categorical-score-chart":
+ // const categoricalScoreTimeSeries =
+ // await getCategoricalScoreTimeSeries(
+ // input.projectId,
+ // input.filter ?? [],
+ // );
+ // return categoricalScoreTimeSeries as DatabaseRow[];
// case "observations-status-timeseries":
// return (await getObservationsStatusTimeSeries(
// input.projectId,
@@ -283,14 +279,14 @@ export const dashboardRouter = createTRPCRouter({
}),
});
-const extractTimeSeries = (groupBy?: z.infer<typeof groupByInterface>) => {
- const temporal = groupBy?.find((group) => {
- if (group.type === "datetime") {
- return group;
- }
- });
- return temporal?.type === "datetime" ? temporal.temporalUnit : undefined;
-};
+// const extractTimeSeries = (groupBy?: z.infer<typeof groupByInterface>) => {
+// const temporal = groupBy?.find((group) => {
+// if (group.type === "datetime") {
+// return group;
+// }
+// });
+// return temporal?.type === "datetime" ? temporal.temporalUnit : undefined;
+// };
/**
* Execute a query using the QueryBuilder.
diff --git a/web/src/features/query/dataModel.ts b/web/src/features/query/dataModel.ts
index c761df4142..7421667d5a 100644
--- a/web/src/features/query/dataModel.ts
+++ b/web/src/features/query/dataModel.ts
@@ -311,8 +311,9 @@ export const scoresNumericView: ViewDeclarationType = {
segments: [
{
column: "data_type",
- operator: "=",
- value: "NUMERIC",
+ // We consider NUMERIC and BOOLEAN scores as numeric.
+ operator: "does not contain",
+ value: "CATEGORICAL",
type: "string",
},
],
@@ -353,9 +354,8 @@ export const scoresCategoricalView: ViewDeclarationType = {
segments: [
{
column: "data_type",
- // Here, we want to include everything that is not numeric.
- operator: "does not contain",
- value: "NUMERIC",
+ operator: "=",
+ value: "CATEGORICAL",
type: "string",
},
],
diff --git a/web/src/features/query/server/queryBuilder.ts b/web/src/features/query/server/queryBuilder.ts
index 2314d3c6f1..9771a04a51 100644
--- a/web/src/features/query/server/queryBuilder.ts
+++ b/web/src/features/query/server/queryBuilder.ts
@@ -123,19 +123,20 @@ export class QueryBuilder {
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;
- }
+ // Filters on measures are underdefined and not allowed in the initial version
+ // } 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";
} else {
throw new Error(
- `Invalid filter column ${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 ${view.timeDimension}`,
);
}
diff --git a/web/src/pages/project/[projectId]/index.tsx b/web/src/pages/project/[projectId]/index.tsx
index 2d736c48e7..a2e7295a47 100644
--- a/web/src/pages/project/[projectId]/index.tsx
+++ b/web/src/pages/project/[projectId]/index.tsx
@@ -282,7 +282,9 @@ export default function Dashboard() {
className="col-span-1 xl:col-span-3"
agg={agg}
projectId={projectId}
- globalFilterState={mergedFilterState}
+ globalFilterState={[...userFilterState, ...environmentFilter]}
+ fromTimestamp={fromTimestamp}
+ toTimestamp={toTimestamp}
isLoading={environmentFilterOptions.isLoading}
/>
<LatencyTables
@@ -305,7 +307,9 @@ export default function Dashboard() {
className="col-span-1 flex-auto justify-between lg:col-span-full"
agg={agg}
projectId={projectId}
- globalFilterState={mergedFilterState}
+ globalFilterState={[...userFilterState, ...environmentFilter]}
+ fromTimestamp={fromTimestamp}
+ toTimestamp={toTimestamp}
isLoading={environmentFilterOptions.isLoading}
/>
</div>