🪢 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(dashboards): add histogram chart type (#7140)
Steffen Schmitzec563b775b90
diff --git a/fern/apis/server/definition/metrics.yml b/fern/apis/server/definition/metrics.ymlindex 6e9098d965..df833eacfe 100644--- a/fern/apis/server/definition/metrics.yml+++ b/fern/apis/server/definition/metrics.yml@@ -28,7 +28,7 @@ service:"metrics": [ // Required. At least one metric must be provided{"measure": string, // What to measure, e.g. "count", "latency", "value"- "aggregation": string // How to aggregate, e.g. "count", "sum", "avg", "p95"+ "aggregation": string // How to aggregate, e.g. "count", "sum", "avg", "p95", "histogram"}],"filters": [ // Optional. Default: []@@ -50,7 +50,11 @@ service:"field": string, // Field to order by"direction": string // "asc" or "desc"}- ]+ ],+ "config": { // Optional. Query-specific configuration+ "bins": number, // Optional. Number of bins for histogram (1-100), default: 10+ "row_limit": number // Optional. Row limit for results (1-1000)+ }}```response: MetricsResponse@@ -62,3 +66,4 @@ types:docs: |The metrics data. Each item in the list contains the metric values and dimensions requested in the query.Format varies based on the query parameters.+ Histograms will return an array with [lower, upper, height] tuples.diff --git a/packages/shared/prisma/generated/types.ts b/packages/shared/prisma/generated/types.tsindex 273089c178..f2e93d6859 100644--- a/packages/shared/prisma/generated/types.ts+++ b/packages/shared/prisma/generated/types.ts@@ -110,7 +110,8 @@ export const DashboardWidgetChartType = {HORIZONTAL_BAR: "HORIZONTAL_BAR",VERTICAL_BAR: "VERTICAL_BAR",PIE: "PIE",- NUMBER: "NUMBER"+ NUMBER: "NUMBER",+ HISTOGRAM: "HISTOGRAM"} as const;export type DashboardWidgetChartType = (typeof DashboardWidgetChartType)[keyof typeof DashboardWidgetChartType];export type Account = {diff --git a/packages/shared/prisma/migrations/20250604085536_add_histogram_chart_type/migration.sql b/packages/shared/prisma/migrations/20250604085536_add_histogram_chart_type/migration.sqlnew file mode 100644index 0000000000..ea604b35d9--- /dev/null+++ b/packages/shared/prisma/migrations/20250604085536_add_histogram_chart_type/migration.sql@@ -0,0 +1,2 @@+-- AlterEnum+ALTER TYPE "DashboardWidgetChartType" ADD VALUE 'HISTOGRAM';diff --git a/packages/shared/prisma/schema.prisma b/packages/shared/prisma/schema.prismaindex 1425b95294..84d0fc5ad1 100644--- a/packages/shared/prisma/schema.prisma+++ b/packages/shared/prisma/schema.prisma@@ -1156,6 +1156,7 @@ enum DashboardWidgetChartType {VERTICAL_BARPIENUMBER+ HISTOGRAM}model DashboardWidget {diff --git a/packages/shared/src/server/services/DashboardService/types.ts b/packages/shared/src/server/services/DashboardService/types.tsindex 3c1f8f3fce..bf58d860fd 100644--- a/packages/shared/src/server/services/DashboardService/types.ts+++ b/packages/shared/src/server/services/DashboardService/types.ts@@ -28,6 +28,11 @@ export const BigNumberChartConfig = BaseTotalValueChartConfig.extend({type: z.literal("NUMBER"),});+export const HistogramChartConfig = BaseTotalValueChartConfig.extend({+ type: z.literal("HISTOGRAM"),+ bins: z.number().int().min(1).max(100).optional().default(10),+});+// Define dimension schemaexport const DimensionSchema = z.object({field: z.string(),@@ -47,6 +52,7 @@ export const ChartConfigSchema = z.discriminatedUnion("type", [VerticalBarChartConfig,PieChartConfig,BigNumberChartConfig,+ HistogramChartConfig,]);export const DashboardDefinitionWidgetWidgetSchema = z.object({diff --git a/web/public/generated/api/openapi.yml b/web/public/generated/api/openapi.ymlindex 7656eb83f6..9d142c984a 100644--- a/web/public/generated/api/openapi.yml+++ b/web/public/generated/api/openapi.yml@@ -1589,7 +1589,7 @@ paths:"metrics": [ // Required. At least one metric must be provided{"measure": string, // What to measure, e.g. "count", "latency", "value"- "aggregation": string // How to aggregate, e.g. "count", "sum", "avg", "p95"+ "aggregation": string // How to aggregate, e.g. "count", "sum", "avg", "p95", "histogram"}],"filters": [ // Optional. Default: []@@ -1611,7 +1611,11 @@ paths:"field": string, // Field to order by"direction": string // "asc" or "desc"}- ]+ ],+ "config": { // Optional. Query-specific configuration+ "bins": number, // Optional. Number of bins for histogram (1-100), default: 10+ "row_limit": number // Optional. Row limit for results (1-1000)+ }}```@@ -6349,6 +6353,8 @@ components:and dimensions requested in the query.Format varies based on the query parameters.++ Histograms will return an array with [lower, upper, height] tuples.required:- dataPaginatedModels:diff --git a/web/public/generated/postman/collection.json b/web/public/generated/postman/collection.jsonindex 6777c6a0c5..8160b02e0a 100644--- a/web/public/generated/postman/collection.json+++ b/web/public/generated/postman/collection.json@@ -1270,7 +1270,7 @@{"key": "query","value": "",- "description": "JSON string containing the query parameters with the following structure:\n```json\n{\n \"view\": string, // Required. One of \"traces\", \"observations\", \"scores-numeric\", \"scores-categorical\"\n \"dimensions\": [ // Optional. Default: []\n {\n \"field\": string // Field to group by, e.g. \"name\", \"userId\", \"sessionId\"\n }\n ],\n \"metrics\": [ // Required. At least one metric must be provided\n {\n \"measure\": string, // What to measure, e.g. \"count\", \"latency\", \"value\"\n \"aggregation\": string // How to aggregate, e.g. \"count\", \"sum\", \"avg\", \"p95\"\n }\n ],\n \"filters\": [ // Optional. Default: []\n {\n \"column\": string, // Column to filter on\n \"operator\": string, // Operator, e.g. \"=\", \">\", \"<\", \"contains\"\n \"value\": any, // Value to compare against\n \"type\": string, // Data type, e.g. \"string\", \"number\", \"stringObject\"\n \"key\": string // Required only when filtering on metadata\n }\n ],\n \"timeDimension\": { // Optional. Default: null. If provided, results will be grouped by time\n \"granularity\": string // One of \"minute\", \"hour\", \"day\", \"week\", \"month\", \"auto\"\n },\n \"fromTimestamp\": string, // Required. ISO datetime string for start of time range\n \"toTimestamp\": string, // Required. ISO datetime string for end of time range\n \"orderBy\": [ // Optional. Default: null\n {\n \"field\": string, // Field to order by\n \"direction\": string // \"asc\" or \"desc\"\n }\n ]\n}\n```"+ "description": "JSON string containing the query parameters with the following structure:\n```json\n{\n \"view\": string, // Required. One of \"traces\", \"observations\", \"scores-numeric\", \"scores-categorical\"\n \"dimensions\": [ // Optional. Default: []\n {\n \"field\": string // Field to group by, e.g. \"name\", \"userId\", \"sessionId\"\n }\n ],\n \"metrics\": [ // Required. At least one metric must be provided\n {\n \"measure\": string, // What to measure, e.g. \"count\", \"latency\", \"value\"\n \"aggregation\": string // How to aggregate, e.g. \"count\", \"sum\", \"avg\", \"p95\", \"histogram\"\n }\n ],\n \"filters\": [ // Optional. Default: []\n {\n \"column\": string, // Column to filter on\n \"operator\": string, // Operator, e.g. \"=\", \">\", \"<\", \"contains\"\n \"value\": any, // Value to compare against\n \"type\": string, // Data type, e.g. \"string\", \"number\", \"stringObject\"\n \"key\": string // Required only when filtering on metadata\n }\n ],\n \"timeDimension\": { // Optional. Default: null. If provided, results will be grouped by time\n \"granularity\": string // One of \"minute\", \"hour\", \"day\", \"week\", \"month\", \"auto\"\n },\n \"fromTimestamp\": string, // Required. ISO datetime string for start of time range\n \"toTimestamp\": string, // Required. ISO datetime string for end of time range\n \"orderBy\": [ // Optional. Default: null\n {\n \"field\": string, // Field to order by\n \"direction\": string // \"asc\" or \"desc\"\n }\n ],\n \"config\": { // Optional. Query-specific configuration\n \"bins\": number, // Optional. Number of bins for histogram (1-100), default: 10\n \"row_limit\": number // Optional. Row limit for results (1-1000)\n }\n}\n```"}],"variable": []diff --git a/web/src/__tests__/async/metrics-api.servertest.ts b/web/src/__tests__/async/metrics-api.servertest.tsindex 8c8fb0e17e..a13a78e234 100644--- a/web/src/__tests__/async/metrics-api.servertest.ts+++ b/web/src/__tests__/async/metrics-api.servertest.ts@@ -399,4 +399,102 @@ describe("/api/public/metrics API Endpoint", () => {expect(body).toHaveProperty("error");expect(body.message).toMatch(/Invalid filter column/);});++ it("should handle histogram aggregation with custom bin count", async () => {+ // Create test data with varying costs for histogram+ const histogramTraceId = randomUUID();++ // Create a trace for histogram testing+ await createTracesCh([+ createTrace({+ id: histogramTraceId,+ name: "histogram-test-trace",+ project_id: projectId,+ timestamp: now.getTime(),+ metadata: { test: testMetadataValue },+ }),+ ]);++ // Create observations with varying costs to test histogram+ const histogramObservations: ReturnType<typeof createObservation>[] = [];+ const costValues = [+ // Low cost cluster - 5 observations+ 0.001, 0.002, 0.003, 0.004, 0.005,+ // Medium cost cluster - 5 observations+ 0.05, 0.06, 0.07, 0.08, 0.09,+ // High cost cluster - 5 observations+ 0.5, 0.6, 0.7, 0.8, 0.9,+ ];++ costValues.forEach((cost, index) => {+ histogramObservations.push(+ createObservation({+ id: randomUUID(),+ trace_id: histogramTraceId,+ project_id: projectId,+ name: `histogram-observation-${index}`,+ start_time: now.getTime(),+ total_cost: cost,+ metadata: { test: testMetadataValue },+ }),+ );+ });++ await createObservationsCh(histogramObservations);++ // Test histogram query with custom bin count+ const histogramQuery = {+ view: "observations",+ dimensions: [],+ metrics: [{ measure: "totalCost", aggregation: "histogram" }],+ filters: [+ {+ column: "metadata",+ operator: "contains",+ key: "test",+ value: testMetadataValue,+ type: "stringObject",+ },+ ],+ timeDimension: null,+ fromTimestamp: twoDaysAgo.toISOString(),+ toTimestamp: tomorrow.toISOString(),+ orderBy: null,+ config: { bins: 15 },+ };++ // Make the API call+ const response = await makeZodVerifiedAPICall(+ GetMetricsV1Response,+ "GET",+ `/api/public/metrics?query=${encodeURIComponent(JSON.stringify(histogramQuery))}`,+ );++ // Validate response format+ expect(response.status).toBe(200);+ expect(Array.isArray(response.body.data)).toBe(true);+ expect(response.body.data).toHaveLength(1);++ // Validate histogram data structure+ const histogramData = response.body.data[0].histogram_totalCost as [+ number,+ number,+ number,+ ][];+ expect(Array.isArray(histogramData)).toBe(true);+ expect(histogramData.length).toBeGreaterThan(0);+ expect(histogramData.length).toBeLessThanOrEqual(15); // Should not exceed requested bins++ // Verify histogram tuple structure [lower, upper, height]+ histogramData.forEach((bin: [number, number, number]) => {+ expect(Array.isArray(bin)).toBe(true);+ expect(bin).toHaveLength(3);+ const [lower, upper, height] = bin;+ expect(typeof lower).toBe("number");+ expect(typeof upper).toBe("number");+ expect(typeof height).toBe("number");+ expect(lower).toBeLessThanOrEqual(upper);+ expect(height).toBeGreaterThanOrEqual(0);+ });+ });});diff --git a/web/src/__tests__/queryBuilder.servertest.ts b/web/src/__tests__/queryBuilder.servertest.tsindex bcac620284..55fefd8572 100644--- a/web/src/__tests__/queryBuilder.servertest.ts+++ b/web/src/__tests__/queryBuilder.servertest.ts@@ -3349,6 +3349,132 @@ describe("queryBuilder", () => {expect(result.data[0].name).toBe("observation-basic");expect(result.data[0].count_count).toBe("1");});++ it("should generate histogram with custom bin count for cost distribution", async () => {+ // Setup+ const projectId = randomUUID();++ // Create traces with observations that have different costs+ const traces = [];+ const observations = [];++ // Create trace for cost distribution test+ const trace = createTrace({+ project_id: projectId,+ name: "cost-distribution-trace",+ environment: "default",+ timestamp: new Date().getTime(),+ });+ traces.push(trace);++ // Create observations with varying costs to test histogram with custom bins+ // Generate 30 observations with costs ranging from $0.001 to $1.00+ const costValues = [+ // Low cost cluster ($0.001-$0.01) - 10 observations+ ...Array.from({ length: 10 }, (_, i) => 0.001 + i * 0.001),+ // Medium cost cluster ($0.05-$0.20) - 10 observations+ ...Array.from({ length: 10 }, (_, i) => 0.05 + i * 0.015),+ // High cost cluster ($0.50-$1.00) - 10 observations+ ...Array.from({ length: 10 }, (_, i) => 0.5 + i * 0.05),+ ];++ costValues.forEach((cost, index) => {+ observations.push(+ createObservation({+ project_id: projectId,+ trace_id: trace.id,+ type: "generation",+ name: `cost-observation-${index}`,+ provided_model_name: "gpt-4",+ environment: "default",+ start_time: new Date().getTime(),+ end_time: new Date().getTime() + 1000,+ total_cost: cost,+ }),+ );+ });++ await createTracesCh(traces);+ await createObservationsCh(observations);++ // Test histogram with custom bin count (20 bins)+ const customBinHistogramQuery: QueryType = {+ view: "observations",+ dimensions: [],+ metrics: [+ {+ measure: "totalCost",+ aggregation: "histogram",+ },+ ],+ filters: [+ {+ column: "type",+ operator: "=",+ value: "generation",+ 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,+ chartConfig: { type: "HISTOGRAM", bins: 20 }, // Custom bin count+ };++ // Execute histogram query with custom bins+ const queryBuilder = new QueryBuilder(customBinHistogramQuery.chartConfig);+ const { query: compiledQuery, parameters } = queryBuilder.build(+ customBinHistogramQuery,+ projectId,+ );++ // Verify the generated SQL contains histogram function with custom bins+ expect(compiledQuery).toContain("histogram(20)");+ expect(compiledQuery).toContain("total_cost");++ const result = await (+ await clickhouseClient().query({+ query: compiledQuery,+ query_params: parameters,+ })+ ).json();++ // Assert histogram results with custom bins+ expect(result.data).toHaveLength(1);+ const histogramData = result.data[0].histogram_totalCost;++ // ClickHouse histogram returns array of tuples [lower, upper, height]+ expect(Array.isArray(histogramData)).toBe(true);+ expect(histogramData.length).toBeGreaterThan(0);+ expect(histogramData.length).toBeLessThanOrEqual(20); // Should not exceed requested bins++ // Verify histogram tuple structure and cost ranges+ histogramData.forEach((bin: [number, number, number]) => {+ expect(Array.isArray(bin)).toBe(true);+ expect(bin).toHaveLength(3);+ const [lower, upper, height] = bin;+ expect(typeof lower).toBe("number");+ expect(typeof upper).toBe("number");+ expect(typeof height).toBe("number");+ expect(lower).toBeLessThan(upper);+ expect(height).toBeGreaterThan(0);+ // Cost values should be in expected range+ expect(lower).toBeGreaterThanOrEqual(0);+ expect(upper).toBeLessThanOrEqual(1.1); // Allow some margin for ClickHouse binning+ });++ // Verify total count matches our data+ const totalCount = histogramData.reduce(+ (sum: number, bin: [number, number, number]) => sum + bin[2],+ 0,+ );+ expect(totalCount).toBe(30); // Should match our 30 observations+ });});});});diff --git a/web/src/features/dashboard/server/dashboard-router.ts b/web/src/features/dashboard/server/dashboard-router.tsindex cc5fdf7246..442e8ee56f 100644--- a/web/src/features/dashboard/server/dashboard-router.ts+++ b/web/src/features/dashboard/server/dashboard-router.ts@@ -326,10 +326,9 @@ export async function executeQuery(query: QueryType,): Promise<Array<Record<string, unknown>>> {try {- const { query: compiledQuery, parameters } = new QueryBuilder().build(- query,- projectId,- );+ const { query: compiledQuery, parameters } = new QueryBuilder(+ query.chartConfig,+ ).build(query, projectId);const result = await queryClickhouse<Record<string, unknown>>({query: compiledQuery,diff --git a/web/src/features/public-api/types/metrics.ts b/web/src/features/public-api/types/metrics.tsindex 2802595c30..4dde694b27 100644--- a/web/src/features/public-api/types/metrics.ts+++ b/web/src/features/public-api/types/metrics.ts@@ -41,6 +41,12 @@ export const MetricsQueryObject = z.nullable().optional().default(null),+ config: z+ .object({+ bins: z.number().int().min(1).max(100).optional(),+ row_limit: z.number().int().positive().lte(1000).optional(),+ })+ .optional(),}).refine((query) =>diff --git a/web/src/features/query/server/queryBuilder.ts b/web/src/features/query/server/queryBuilder.tsindex 5a17db34d4..e918fedda7 100644--- a/web/src/features/query/server/queryBuilder.ts+++ b/web/src/features/query/server/queryBuilder.ts@@ -30,34 +30,44 @@ type AppliedMetricType = {};export class QueryBuilder {- private translateAggregation(- aggregation: z.infer<typeof metricAggregations>,- ): string {- switch (aggregation) {+ private chartConfig?: { bins?: number; row_limit?: number };++ constructor(chartConfig?: { bins?: number; row_limit?: number }) {+ this.chartConfig = chartConfig;+ }++ private translateAggregation(metric: AppliedMetricType): string {+ switch (metric.aggregation) {case "sum":- return "sum";+ return `sum(${metric.alias || metric.sql})`;case "avg":- return "avg";+ return `avg(${metric.alias || metric.sql})`;case "count":- return "count";+ return `count(${metric.alias || metric.sql})`;case "max":- return "max";+ return `max(${metric.alias || metric.sql})`;case "min":- return "min";+ return `min(${metric.alias || metric.sql})`;case "p50":- return "quantile(0.5)";+ return `quantile(0.5)(${metric.alias || metric.sql})`;case "p75":- return "quantile(0.75)";+ return `quantile(0.75)(${metric.alias || metric.sql})`;case "p90":- return "quantile(0.9)";+ return `quantile(0.9)(${metric.alias || metric.sql})`;case "p95":- return "quantile(0.95)";+ return `quantile(0.95)(${metric.alias || metric.sql})`;case "p99":- return "quantile(0.99)";+ return `quantile(0.99)(${metric.alias || metric.sql})`;+ case "histogram":+ // Get histogram bins from chart config, fallback to 10+ const bins = this.chartConfig?.bins ?? 10;+ return `histogram(${bins})(toFloat64(${metric.alias || metric.sql}))`;default:// eslint-disable-next-line @typescript-eslint/no-unused-vars- const exhaustiveCheck: never = aggregation;- throw new InvalidRequestError(`Invalid aggregation: ${aggregation}`);+ const exhaustiveCheck: never = metric.aggregation;+ throw new InvalidRequestError(+ `Invalid aggregation: ${metric.aggregation}`,+ );}}@@ -491,7 +501,7 @@ export class QueryBuilder {private buildOuterMetricsPart(appliedMetrics: AppliedMetricType[]) {return appliedMetrics.length > 0- ? `${appliedMetrics.map((metric) => `${this.translateAggregation(metric.aggregation)}(${metric.alias || metric.sql}) as ${metric.aggregation}_${metric.alias || metric.sql}`).join(",\n")}`+ ? `${appliedMetrics.map((metric) => `${this.translateAggregation(metric)} as ${metric.aggregation}_${metric.alias || metric.sql}`).join(",\n")}`: "count(*) as count";}diff --git a/web/src/features/query/types.ts b/web/src/features/query/types.tsindex 0e2b4da350..b3ebdde1c8 100644--- a/web/src/features/query/types.ts+++ b/web/src/features/query/types.ts@@ -69,6 +69,7 @@ export const metricAggregations = z.enum(["p90","p95","p99",+ "histogram",]);export const metric = z.object({@@ -110,6 +111,14 @@ export const query = z}),).nullable(),+ // Chart configuration for chart-specific settings like histogram bins+ chartConfig: z+ .object({+ type: z.string(),+ bins: z.number().int().min(1).max(100).optional(),+ row_limit: z.number().int().positive().lte(1000).optional(),+ })+ .optional(),}).refine((query) =>diff --git a/web/src/features/widgets/chart-library/Chart.tsx b/web/src/features/widgets/chart-library/Chart.tsxindex abd6e49da0..581e2215d1 100644--- a/web/src/features/widgets/chart-library/Chart.tsx+++ b/web/src/features/widgets/chart-library/Chart.tsx@@ -6,6 +6,7 @@ import VerticalBarChartTimeSeries from "@/src/features/widgets/chart-library/Verimport HorizontalBarChart from "@/src/features/widgets/chart-library/HorizontalBarChart";import VerticalBarChart from "@/src/features/widgets/chart-library/VerticalBarChart";import PieChart from "@/src/features/widgets/chart-library/PieChart";+import HistogramChart from "@/src/features/widgets/chart-library/HistogramChart";import { type DashboardWidgetChartType } from "@langfuse/shared/src/db";import { Button } from "@/src/components/ui/button";import { AlertCircle } from "lucide-react";@@ -52,12 +53,17 @@ export const Chart = ({return <VerticalBarChart data={renderedData.slice(0, rowLimit)} />;case "PIE":return <PieChart data={renderedData.slice(0, rowLimit)} />;+ case "HISTOGRAM":+ return <HistogramChart data={renderedData} />;case "NUMBER": {// Show the sum of all metrics, or just the first metric if only oneconst value =renderedData.length === 1? renderedData[0].metric- : renderedData.reduce((acc, d) => acc + (d.metric || 0), 0);+ : renderedData.reduce(+ (acc, d) => acc + ((d.metric as number) || 0),+ 0,+ );return <BigNumber metric={value} />;}default:diff --git a/web/src/features/widgets/chart-library/HistogramChart.tsx b/web/src/features/widgets/chart-library/HistogramChart.tsxnew file mode 100644index 0000000000..155956fb7d--- /dev/null+++ b/web/src/features/widgets/chart-library/HistogramChart.tsx@@ -0,0 +1,101 @@+import React from "react";+import { type DataPoint } from "@/src/features/widgets/chart-library/chart-props";+import { BarChart, Bar, XAxis, YAxis, ResponsiveContainer } from "recharts";+import { ChartContainer, ChartTooltip } from "@/src/components/ui/chart";+import { compactNumberFormatter } from "@/src/utils/numbers";++interface HistogramDataPoint {+ binLabel: string;+ count: number;+ lower?: number;+ upper?: number;+ height?: number;+}++const HistogramChart = ({ data }: { data: DataPoint[] }) => {+ const transformHistogramData = (data: DataPoint[]): HistogramDataPoint[] => {+ if (!data.length) return [];++ // Check if this is ClickHouse histogram format (array of tuples)+ const firstDataPoint = data[0];+ if (firstDataPoint?.metric && Array.isArray(firstDataPoint.metric)) {+ // ClickHouse histogram format: [(lower, upper, height), ...]+ return (firstDataPoint.metric as [number, number, number][]).map(+ ([lower, upper, height]) => ({+ binLabel: `[${compactNumberFormatter(lower)}, ${compactNumberFormatter(upper)}]`,+ count: height,+ lower,+ upper,+ height,+ }),+ );+ }++ // Fallback: treat as regular data points with binLabel+ return data.map((item) => ({+ binLabel: item.dimension || `Bin ${data.indexOf(item) + 1}`,+ count: (item.metric as number) || 0,+ }));+ };++ const histogramData = transformHistogramData(data);++ // Chart configuration+ const config = {+ count: {+ label: "Count",+ color: "hsl(var(--chart-1))",+ },+ };++ if (!histogramData.length) {+ return (+ <div className="flex h-full items-center justify-center text-muted-foreground">+ No data available+ </div>+ );+ }++ return (+ <ChartContainer config={config}>+ <ResponsiveContainer width="100%" height="100%">+ <BarChart+ data={histogramData}+ margin={{ top: 20, right: 30, left: 20, bottom: 5 }}+ >+ <XAxis+ dataKey="binLabel"+ stroke="hsl(var(--chart-grid))"+ fontSize={12}+ tickLine={false}+ axisLine={false}+ angle={-45}+ textAnchor="end"+ height={90}+ />+ <YAxis+ stroke="hsl(var(--chart-grid))"+ fontSize={12}+ tickLine={false}+ axisLine={false}+ />+ <Bar+ dataKey="count"+ fill="hsl(var(--chart-1))"+ radius={[2, 2, 0, 0]}+ />+ <ChartTooltip+ contentStyle={{ backgroundColor: "hsl(var(--background))" }}+ formatter={(value, name) => [+ `${value}`,+ name === "count" ? "Count" : name,+ ]}+ labelFormatter={(label) => `Bin: ${label}`}+ />+ </BarChart>+ </ResponsiveContainer>+ </ChartContainer>+ );+};++export default HistogramChart;diff --git a/web/src/features/widgets/chart-library/PieChart.tsx b/web/src/features/widgets/chart-library/PieChart.tsxindex 3ffc9854d4..603ed3c6e1 100644--- a/web/src/features/widgets/chart-library/PieChart.tsx+++ b/web/src/features/widgets/chart-library/PieChart.tsx@@ -23,7 +23,7 @@ export const PieChart: React.FC<ChartProps> = ({}) => {// Calculate total metric value for center labelconst totalValue = useMemo(() => {- return data.reduce((acc, curr) => acc + curr.metric, 0);+ return data.reduce((acc, curr) => acc + (curr.metric as number), 0);}, [data]);// Transform data for PieChartdiff --git a/web/src/features/widgets/chart-library/chart-props.ts b/web/src/features/widgets/chart-library/chart-props.tsindex b8dbabb5b6..131a3e7515 100644--- a/web/src/features/widgets/chart-library/chart-props.ts+++ b/web/src/features/widgets/chart-library/chart-props.ts@@ -3,7 +3,7 @@ import { type ChartConfig } from "@/src/components/ui/chart";export interface DataPoint {time_dimension: string | undefined;dimension: string | undefined;- metric: number;+ metric: number | Array<Array<number>>;}export interface ChartProps {diff --git a/web/src/features/widgets/chart-library/utils.ts b/web/src/features/widgets/chart-library/utils.tsindex bfa6a09325..61e498f228 100644--- a/web/src/features/widgets/chart-library/utils.ts+++ b/web/src/features/widgets/chart-library/utils.ts@@ -15,7 +15,7 @@ export const groupDataByTimeDimension = (data: DataPoint[]) => {}const dimension = item.dimension || "Unknown";- acc[time][dimension] = item.metric;+ acc[time][dimension] = item.metric as number;return acc;},@@ -49,6 +49,8 @@ export const isTimeSeriesChart = (case "HORIZONTAL_BAR":case "VERTICAL_BAR":case "PIE":+ case "HISTOGRAM":+ case "NUMBER":return false;default:return false;diff --git a/web/src/features/widgets/components/DashboardWidget.tsx b/web/src/features/widgets/components/DashboardWidget.tsxindex f849b56d76..acf94820ff 100644--- a/web/src/features/widgets/components/DashboardWidget.tsx+++ b/web/src/features/widgets/components/DashboardWidget.tsx@@ -93,6 +93,7 @@ export function DashboardWidget({fromTimestamp: fromTimestamp.toISOString(),toTimestamp: toTimestamp.toISOString(),orderBy: null,+ chartConfig: widget.data?.chartConfig,},},{@@ -119,6 +120,7 @@ export function DashboardWidget({agg: "count",};const metricField = `${metric.agg}_${metric.measure}`;+ const metricValue = item[metricField];return {dimension:@@ -133,7 +135,9 @@ export function DashboardWidget({return String(val);})(): startCase(metricField === "count_count" ? "Count" : metricField),- metric: Number(item[metricField] || 0),+ metric: Array.isArray(metricValue)+ ? metricValue+ : Number(metricValue || 0),time_dimension: item["time_dimension"],};});diff --git a/web/src/features/widgets/components/WidgetForm.tsx b/web/src/features/widgets/components/WidgetForm.tsxindex 232f5f3897..09fc447ac4 100644--- a/web/src/features/widgets/components/WidgetForm.tsx+++ b/web/src/features/widgets/components/WidgetForm.tsx@@ -46,6 +46,7 @@ import {LineChart,BarChartHorizontal,Hash,+ BarChart3,} from "lucide-react";import {buildWidgetName,@@ -96,6 +97,13 @@ const chartTypes: ChartType[] = [icon: BarChart,supportsBreakdown: true,},+ {+ group: "total-value",+ name: "Histogram",+ value: "HISTOGRAM",+ icon: BarChart3,+ supportsBreakdown: false,+ },{group: "total-value",name: "Pie Chart",@@ -120,7 +128,11 @@ export function WidgetForm({dimension: string;filters?: FilterState;chartType: DashboardWidgetChartType;- chartConfig?: { type: DashboardWidgetChartType; row_limit?: number };+ chartConfig?: {+ type: DashboardWidgetChartType;+ row_limit?: number;+ bins?: number;+ };};projectId: string;onSave: (widgetData: {@@ -131,7 +143,11 @@ export function WidgetForm({metrics: { measure: string; agg: string }[];filters: any[];chartType: DashboardWidgetChartType;- chartConfig: { type: DashboardWidgetChartType; row_limit?: number };+ chartConfig: {+ type: DashboardWidgetChartType;+ row_limit?: number;+ bins?: number;+ };}) => void;widgetId?: string;}) {@@ -166,6 +182,9 @@ export function WidgetForm({const [rowLimit, setRowLimit] = useState<number>(initialValues.chartConfig?.row_limit ?? 100,);+ const [histogramBins, setHistogramBins] = useState<number>(+ initialValues.chartConfig?.bins ?? 10,+ );// Filter stateconst { selectedOption, dateRange, setDateRangeAndOption } =@@ -291,12 +310,35 @@ export function WidgetForm({}}, [selectedChartType, selectedDimension]);- // Set aggregation to "count" when metric is "count"+ // Set aggregation based on chart type and metric, with histogram chart type taking priorityuseEffect(() => {- if (selectedMeasure === "count" && selectedAggregation !== "count") {+ // Histogram chart type always takes priority+ if (+ selectedChartType === "HISTOGRAM" &&+ selectedAggregation !== "histogram"+ ) {+ setSelectedAggregation("histogram");+ }+ // If switching away from histogram chart type and aggregation is still histogram, reset to appropriate default+ else if (+ selectedChartType !== "HISTOGRAM" &&+ selectedAggregation === "histogram"+ ) {+ if (selectedMeasure === "count") {+ setSelectedAggregation("count");+ } else {+ setSelectedAggregation("sum"); // Default aggregation for non-count metrics+ }+ }+ // Only set to "count" for count metric if not using histogram chart type+ else if (+ selectedMeasure === "count" &&+ selectedChartType !== "HISTOGRAM" &&+ selectedAggregation !== "count"+ ) {setSelectedAggregation("count");}- }, [selectedMeasure, selectedAggregation]);+ }, [selectedMeasure, selectedAggregation, selectedChartType]);// Get available metrics for the selected viewconst availableMetrics = useMemo(() => {@@ -336,7 +378,12 @@ export function WidgetForm({view: selectedView,dimensions:selectedDimension !== "none" ? [{ field: selectedDimension }] : [],- metrics: [{ measure: selectedMeasure, aggregation: selectedAggregation }],+ metrics: [+ {+ measure: selectedMeasure,+ aggregation: selectedAggregation,+ },+ ],filters: [...mapLegacyUiTableFilterToView(selectedView, userFilterState)],timeDimension: isTimeSeriesChart(selectedChartType as DashboardWidgetChartType,@@ -346,6 +393,10 @@ export function WidgetForm({fromTimestamp: fromTimestamp.toISOString(),toTimestamp: toTimestamp.toISOString(),orderBy: null,+ chartConfig:+ selectedChartType === "HISTOGRAM"+ ? { type: selectedChartType, bins: histogramBins }+ : { type: selectedChartType },};}, [selectedView,@@ -355,6 +406,7 @@ export function WidgetForm({userFilterState,dateRange,selectedChartType,+ histogramBins,]);const queryResult = api.dashboard.executeQuery.useQuery(@@ -379,6 +431,7 @@ export function WidgetForm({const dimensionField = selectedDimension;// Get the metric field (first metric in the query with its aggregation)const metricField = `${selectedAggregation}_${selectedMeasure}`;+ const metric = item[metricField];return {dimension:@@ -394,7 +447,7 @@ export function WidgetForm({: startCase(metricField === "count_count" ? "Count" : metricField,),- metric: Number(item[metricField] || 0),+ metric: Array.isArray(metric) ? metric : Number(metric || 0),time_dimension: item["time_dimension"],};}) ?? [],@@ -413,17 +466,27 @@ export function WidgetForm({view: selectedView,dimensions:selectedDimension !== "none" ? [{ field: selectedDimension }] : [],- metrics: [{ measure: selectedMeasure, agg: selectedAggregation }],+ metrics: [+ {+ measure: selectedMeasure,+ agg: selectedAggregation,+ },+ ],filters: mapLegacyUiTableFilterToView(selectedView, userFilterState),chartType: selectedChartType as DashboardWidgetChartType,chartConfig: isTimeSeriesChart(selectedChartType as DashboardWidgetChartType,)? { type: selectedChartType as DashboardWidgetChartType }- : {- type: selectedChartType as DashboardWidgetChartType,- row_limit: rowLimit,- },+ : selectedChartType === "HISTOGRAM"+ ? {+ type: selectedChartType as DashboardWidgetChartType,+ bins: histogramBins,+ }+ : {+ type: selectedChartType as DashboardWidgetChartType,+ row_limit: rowLimit,+ },});};@@ -545,25 +608,34 @@ export function WidgetForm({</SelectContent></Select>{selectedMeasure !== "count" && (- <Select- value={selectedAggregation}- onValueChange={(value) =>- setSelectedAggregation(- value as z.infer<typeof metricAggregations>,- )- }- >- <SelectTrigger id="aggregation-select">- <SelectValue placeholder="Select Aggregation" />- </SelectTrigger>- <SelectContent>- {metricAggregations.options.map((aggregation) => (- <SelectItem key={aggregation} value={aggregation}>- {startCase(aggregation)}- </SelectItem>- ))}- </SelectContent>- </Select>+ <div className="space-y-1">+ <Select+ value={selectedAggregation}+ disabled={selectedChartType === "HISTOGRAM"} // Disable when histogram chart type is selected+ onValueChange={(value) =>+ setSelectedAggregation(+ value as z.infer<typeof metricAggregations>,+ )+ }+ >+ <SelectTrigger id="aggregation-select">+ <SelectValue placeholder="Select Aggregation" />+ </SelectTrigger>+ <SelectContent>+ {metricAggregations.options.map((aggregation) => (+ <SelectItem key={aggregation} value={aggregation}>+ {startCase(aggregation)}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ {selectedChartType === "HISTOGRAM" && (+ <p className="text-xs text-muted-foreground">+ Aggregation is automatically set to+ "histogram" for histogram charts+ </p>+ )}+ </div>)}</div>@@ -704,6 +776,27 @@ export function WidgetForm({/></div>+ {/* Histogram Bins Selection - Only shown for HISTOGRAM chart type */}+ {selectedChartType === "HISTOGRAM" && (+ <div className="space-y-2">+ <Label htmlFor="histogram-bins">Number of Bins (1-100)</Label>+ <Input+ id="histogram-bins"+ type="number"+ min={1}+ max={100}+ value={histogramBins}+ onChange={(e) => {+ const value = parseInt(e.target.value);+ if (!isNaN(value) && value >= 1 && value <= 100) {+ setHistogramBins(value);+ }+ }}+ placeholder="Enter number of bins (1-100)"+ />+ </div>+ )}+{/* Row Limit Selection - Only shown for non-time series charts that support breakdown */}{chartTypes.find((c) => c.value === selectedChartType)?.supportsBreakdown &&diff --git a/web/src/pages/api/public/metrics/index.ts b/web/src/pages/api/public/metrics/index.tsindex 72c83cc323..73149d051c 100644--- a/web/src/pages/api/public/metrics/index.ts+++ b/web/src/pages/api/public/metrics/index.ts@@ -26,10 +26,9 @@ export default withMiddlewares({});// Execute the query using QueryBuilder- const { query: compiledQuery, parameters } = new QueryBuilder().build(- queryParams,- auth.scope.projectId,- );+ const { query: compiledQuery, parameters } = new QueryBuilder(+ queryParams.config,+ ).build(queryParams, auth.scope.projectId);// Run the query against ClickHouseconst result = await queryClickhouse<Record<string, unknown>>({diff --git a/web/src/pages/project/[projectId]/widgets/[widgetId]/index.tsx b/web/src/pages/project/[projectId]/widgets/[widgetId]/index.tsxindex b32ad2bd08..fa591178e0 100644--- a/web/src/pages/project/[projectId]/widgets/[widgetId]/index.tsx+++ b/web/src/pages/project/[projectId]/widgets/[widgetId]/index.tsx@@ -58,7 +58,7 @@ export default function EditWidget() {metrics: { measure: string; agg: string }[];filters: any[];chartType: DashboardWidgetChartType;- chartConfig: { type: DashboardWidgetChartType; row_limit?: number };+ chartConfig: { type: DashboardWidgetChartType; row_limit?: number; bins?: number };}) => {if (!widgetId) return;diff --git a/web/src/pages/project/[projectId]/widgets/new.tsx b/web/src/pages/project/[projectId]/widgets/new.tsxindex 2b2293df72..3196a3dd66 100644--- a/web/src/pages/project/[projectId]/widgets/new.tsx+++ b/web/src/pages/project/[projectId]/widgets/new.tsx@@ -49,7 +49,7 @@ export default function NewWidget() {metrics: { measure: string; agg: string }[];filters: any[];chartType: DashboardWidgetChartType;- chartConfig: { type: DashboardWidgetChartType; row_limit?: number };+ chartConfig: { type: DashboardWidgetChartType; row_limit?: number; bins?: number };}) => {if (!widgetData.name.trim()) {showErrorToast("Error", "Widget name is required");@@ -98,6 +98,7 @@ export default function NewWidget() {aggregation: "count",filters: [],chartType: "LINE_TIME_SERIES",+ chartConfig: { type: "LINE_TIME_SERIES" },}}widgetId={undefined}/>