Skip to content

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

feat(monitors): bucket live preview by evaluation window (#14189)

Mark Salpeter085aadd5d493
diff --git a/packages/shared/src/features/monitors/service/helpers.ts b/packages/shared/src/features/monitors/service/helpers.ts
index c03308b296..269756a005 100644
--- a/packages/shared/src/features/monitors/service/helpers.ts
+++ b/packages/shared/src/features/monitors/service/helpers.ts
@@ -10,8 +10,6 @@ import {
Prisma,
} from "@prisma/client";
-import { InvalidRequestError } from "../../../errors";
-
import { DAY, HOUR, MINUTE, WEEK } from "../helpers";
import {
type Monitor,
@@ -19,9 +17,10 @@ import {
type MonitorSeverity,
type MonitorStatus,
type MonitorView,
- type MonitorWindow,
MonitorSchema,
MonitorStatusSchema,
+ windowFromMs,
+ windowToMs,
} from "../types";
import {
@@ -182,61 +181,7 @@ export const viewFromPrisma = (view: PrismaMonitorView): MonitorView => {
}
};
-/** windowToMs converts the MonitorWindow api enum to a bigint of milliseconds. */
-export const windowToMs = (w: MonitorWindow): bigint => {
- switch (w) {
- case "5m":
- return 5n * 60_000n;
- case "10m":
- return 10n * 60_000n;
- case "15m":
- return 15n * 60_000n;
- case "30m":
- return 30n * 60_000n;
- case "1h":
- return 60n * 60_000n;
- case "2h":
- return 2n * 60n * 60_000n;
- case "4h":
- return 4n * 60n * 60_000n;
- case "1d":
- return 24n * 60n * 60_000n;
- case "2d":
- return 2n * 24n * 60n * 60_000n;
- case "1w":
- return 7n * 24n * 60n * 60_000n;
- }
-};
-
-/** windowFromMs converts a bigint of milliseconds to the MonitorWindow api enum. */
-export const windowFromMs = (ms: bigint): MonitorWindow => {
- switch (ms) {
- case 5n * 60_000n:
- return "5m";
- case 10n * 60_000n:
- return "10m";
- case 15n * 60_000n:
- return "15m";
- case 30n * 60_000n:
- return "30m";
- case 60n * 60_000n:
- return "1h";
- case 2n * 60n * 60_000n:
- return "2h";
- case 4n * 60n * 60_000n:
- return "4h";
- case 24n * 60n * 60_000n:
- return "1d";
- case 2n * 24n * 60n * 60_000n:
- return "2d";
- case 7n * 24n * 60n * 60_000n:
- return "1w";
- default:
- throw new InvalidRequestError(
- `windowMs ${ms.toString()} does not correspond to a known MonitorWindow tier`,
- );
- }
-};
+export { windowToMs, windowFromMs };
/** monitorFromPrisma converts a Prisma monitor row to the domain Monitor. */
export const monitorFromPrisma = (monitor: PrismaMonitor): Monitor =>
diff --git a/packages/shared/src/features/monitors/types.ts b/packages/shared/src/features/monitors/types.ts
index 70023431c4..f88b460f41 100644
--- a/packages/shared/src/features/monitors/types.ts
+++ b/packages/shared/src/features/monitors/types.ts
@@ -7,8 +7,9 @@ import {
} from "@prisma/client";
import { z } from "zod";
+import { InvalidRequestError } from "../../errors";
import { singleFilter } from "../../interfaces/filters";
-import { metric as MetricSchema, viewsV2 } from "../query/types";
+import { granularities, metric as MetricSchema, viewsV2 } from "../query/types";
import { isValidQuery } from "./isValidQuery";
import { isValidThresholdOrder } from "./isValidThresholdOrder";
@@ -59,7 +60,7 @@ export type MonitorThresholdOperator = z.infer<
* window. The service translates between this and a bigint of milliseconds
* (the Prisma `windowMs` column) at the persistence boundary.
*/
-export const MonitorWindowSchema = z.enum([
+export const MonitorWindowSchema = granularities.extract([
"5m",
"10m",
"15m",
@@ -73,6 +74,62 @@ export const MonitorWindowSchema = z.enum([
]);
export type MonitorWindow = z.infer<typeof MonitorWindowSchema>;
+/** windowToMs converts the MonitorWindow api enum to a bigint of milliseconds. */
+export const windowToMs = (w: MonitorWindow): bigint => {
+ switch (w) {
+ case "5m":
+ return 5n * 60_000n;
+ case "10m":
+ return 10n * 60_000n;
+ case "15m":
+ return 15n * 60_000n;
+ case "30m":
+ return 30n * 60_000n;
+ case "1h":
+ return 60n * 60_000n;
+ case "2h":
+ return 2n * 60n * 60_000n;
+ case "4h":
+ return 4n * 60n * 60_000n;
+ case "1d":
+ return 24n * 60n * 60_000n;
+ case "2d":
+ return 2n * 24n * 60n * 60_000n;
+ case "1w":
+ return 7n * 24n * 60n * 60_000n;
+ }
+};
+
+/** windowFromMs converts a bigint of milliseconds to the MonitorWindow api enum. */
+export const windowFromMs = (ms: bigint): MonitorWindow => {
+ switch (ms) {
+ case 5n * 60_000n:
+ return "5m";
+ case 10n * 60_000n:
+ return "10m";
+ case 15n * 60_000n:
+ return "15m";
+ case 30n * 60_000n:
+ return "30m";
+ case 60n * 60_000n:
+ return "1h";
+ case 2n * 60n * 60_000n:
+ return "2h";
+ case 4n * 60n * 60_000n:
+ return "4h";
+ case 24n * 60n * 60_000n:
+ return "1d";
+ case 2n * 24n * 60n * 60_000n:
+ return "2d";
+ case 7n * 24n * 60n * 60_000n:
+ return "1w";
+ default:
+ throw new InvalidRequestError(
+ `windowMs ${ms.toString()} does not correspond to a known MonitorWindow tier`,
+ );
+ }
+};
+
/**
* MonitorViewSchema is an alias of the query `viewsV2` schema.
*/
diff --git a/packages/shared/src/features/query/server/queryBuilder.intervalBucketing.test.ts b/packages/shared/src/features/query/server/queryBuilder.intervalBucketing.test.ts
new file mode 100644
index 0000000000..230069b521
--- /dev/null
+++ b/packages/shared/src/features/query/server/queryBuilder.intervalBucketing.test.ts
@@ -0,0 +1,51 @@
+/** queryBuilder.intervalBucketing.test.ts verifies the 10 Monitor window
+ * tokens compile to toStartOfInterval bucketing and matching WITH FILL steps. */
+import { describe, it, expect, vi } from "vitest";
+
+import { type QueryType } from "../types";
+import { QueryBuilder } from "./queryBuilder";
+
+vi.mock("../../../server/queries/clickhouse-sql/query-options", () => ({
+ shouldSkipObservationsFinal: vi.fn().mockResolvedValue(false),
+}));
+
+/** windowBucketCases maps each window token to its expected ClickHouse interval. */
+const windowBucketCases = [
+ ["5m", "INTERVAL 5 MINUTE"],
+ ["10m", "INTERVAL 10 MINUTE"],
+ ["15m", "INTERVAL 15 MINUTE"],
+ ["30m", "INTERVAL 30 MINUTE"],
+ ["1h", "INTERVAL 1 HOUR"],
+ ["2h", "INTERVAL 2 HOUR"],
+ ["4h", "INTERVAL 4 HOUR"],
+ ["1d", "INTERVAL 1 DAY"],
+ ["2d", "INTERVAL 2 DAY"],
+ ["1w", "INTERVAL 7 DAY"],
+] as const;
+
+/** buildWindowQuery compiles a minimal traces query bucketed by the given window granularity. */
+const buildWindowQuery = async (granularity: string) => {
+ const query = {
+ view: "traces",
+ dimensions: [],
+ metrics: [{ measure: "count", aggregation: "count" }],
+ filters: [],
+ timeDimension: { granularity },
+ fromTimestamp: "2025-01-01T00:00:00.000Z",
+ toTimestamp: "2025-01-02T00:00:00.000Z",
+ orderBy: null,
+ } as unknown as QueryType;
+ return new QueryBuilder().build(query, "test-project");
+};
+
+describe("queryBuilder interval bucketing", () => {
+ it.each(windowBucketCases)(
+ "%s window buckets via toStartOfInterval and fills with the matching STEP",
+ async (granularity, interval) => {
+ const { query } = await buildWindowQuery(granularity);
+ expect(query).toContain("toStartOfInterval");
+ expect(query).toContain(interval);
+ expect(query).toContain(`STEP ${interval}`);
+ },
+ );
+});
diff --git a/packages/shared/src/features/query/server/queryBuilder.ts b/packages/shared/src/features/query/server/queryBuilder.ts
index 8f8ec00095..f2d8dff121 100644
--- a/packages/shared/src/features/query/server/queryBuilder.ts
+++ b/packages/shared/src/features/query/server/queryBuilder.ts
@@ -832,6 +832,26 @@ export class QueryBuilder {
return `toMonday(${sql})`;
case "month":
return `toStartOfMonth(${sql})`;
+ case "5m":
+ return `toStartOfInterval(${sql}, INTERVAL 5 MINUTE)`;
+ case "10m":
+ return `toStartOfInterval(${sql}, INTERVAL 10 MINUTE)`;
+ case "15m":
+ return `toStartOfInterval(${sql}, INTERVAL 15 MINUTE)`;
+ case "30m":
+ return `toStartOfInterval(${sql}, INTERVAL 30 MINUTE)`;
+ case "1h":
+ return `toStartOfInterval(${sql}, INTERVAL 1 HOUR)`;
+ case "2h":
+ return `toStartOfInterval(${sql}, INTERVAL 2 HOUR)`;
+ case "4h":
+ return `toStartOfInterval(${sql}, INTERVAL 4 HOUR)`;
+ case "1d":
+ return `toStartOfInterval(${sql}, INTERVAL 1 DAY)`;
+ case "2d":
+ return `toStartOfInterval(${sql}, INTERVAL 2 DAY)`;
+ case "1w":
+ return `toStartOfInterval(${sql}, INTERVAL 7 DAY)`;
case "auto":
throw new Error(
`Granularity 'auto' is not supported for getTimeDimensionSql`,
@@ -1102,6 +1122,36 @@ export class QueryBuilder {
case "month":
step = "INTERVAL 1 MONTH";
break;
+ case "5m":
+ step = "INTERVAL 5 MINUTE";
+ break;
+ case "10m":
+ step = "INTERVAL 10 MINUTE";
+ break;
+ case "15m":
+ step = "INTERVAL 15 MINUTE";
+ break;
+ case "30m":
+ step = "INTERVAL 30 MINUTE";
+ break;
+ case "1h":
+ step = "INTERVAL 1 HOUR";
+ break;
+ case "2h":
+ step = "INTERVAL 2 HOUR";
+ break;
+ case "4h":
+ step = "INTERVAL 4 HOUR";
+ break;
+ case "1d":
+ step = "INTERVAL 1 DAY";
+ break;
+ case "2d":
+ step = "INTERVAL 2 DAY";
+ break;
+ case "1w":
+ step = "INTERVAL 7 DAY";
+ break;
default:
step = "INTERVAL 1 DAY"; // Default to day if granularity is unknown
}
diff --git a/packages/shared/src/features/query/types.ts b/packages/shared/src/features/query/types.ts
index 8724ed5c72..f0cd492af5 100644
--- a/packages/shared/src/features/query/types.ts
+++ b/packages/shared/src/features/query/types.ts
@@ -142,6 +142,7 @@ export const metric = z.object({
aggregation: metricAggregations,
});
+/** granularities is the superset of time-bucket tokens: the 6 base options plus the 10 Monitor window increments. */
export const granularities = z.enum([
"auto",
"minute",
@@ -149,6 +150,16 @@ export const granularities = z.enum([
"day",
"week",
"month",
+ "5m",
+ "10m",
+ "15m",
+ "30m",
+ "1h",
+ "2h",
+ "4h",
+ "1d",
+ "2d",
+ "1w",
]);
export type QueryType = z.infer<typeof query>;
diff --git a/web/src/features/mcp/features/metrics/tools/getMetricsSchema.ts b/web/src/features/mcp/features/metrics/tools/getMetricsSchema.ts
index 95f3770931..2285b22097 100644
--- a/web/src/features/mcp/features/metrics/tools/getMetricsSchema.ts
+++ b/web/src/features/mcp/features/metrics/tools/getMetricsSchema.ts
@@ -1,9 +1,9 @@
import {
getValidAggregationsForMeasureType,
- granularities,
viewsV2,
viewDeclarations,
} from "@langfuse/shared/query";
+import { publicGranularities } from "@/src/features/public-api/types/metrics";
import { z } from "zod";
import { defineTool } from "../../../core/define-tool";
import { runMcpTool } from "../../../core/run-mcp-tool";
@@ -31,7 +31,7 @@ export const [getMetricsSchemaTool, handleGetMetricsSchema] = defineTool({
return {
supportedViews,
- granularities: granularities.options,
+ granularities: publicGranularities.options,
config: {
bins: { min: 1, max: 100 },
row_limit: { min: 1, max: 1000, default: 100 },
diff --git a/web/src/features/mcp/features/metrics/tools/queryMetrics.ts b/web/src/features/mcp/features/metrics/tools/queryMetrics.ts
index 4ca13ce850..8d53169f0c 100644
--- a/web/src/features/mcp/features/metrics/tools/queryMetrics.ts
+++ b/web/src/features/mcp/features/metrics/tools/queryMetrics.ts
@@ -2,12 +2,14 @@ import { InvalidRequestError } from "@langfuse/shared";
import { executeQuery } from "@langfuse/shared/query/server";
import {
dimension,
- granularities,
metric,
validateQuery,
viewsV2,
} from "@langfuse/shared/query";
-import { MetricsQueryObjectV2 } from "@/src/features/public-api/types/metrics";
+import {
+ MetricsQueryObjectV2,
+ publicGranularities,
+} from "@/src/features/public-api/types/metrics";
import { defineTool } from "../../../core/define-tool";
import { McpAdvancedFilterBaseSchema } from "../../../core/filter-schema";
import { runMcpTool } from "../../../core/run-mcp-tool";
@@ -65,7 +67,7 @@ const MetricsQueryObjectV2BaseSchema = z.object({
filters: z.array(McpAdvancedFilterBaseSchema).optional().default([]),
timeDimension: z
.object({
- granularity: granularities,
+ granularity: publicGranularities,
})
.optional(),
fromTimestamp: z.iso.datetime({ offset: true }),
diff --git a/web/src/features/monitors/components/MonitorChartPreview.tsx b/web/src/features/monitors/components/MonitorChartPreview.tsx
index 551d6bf4c6..d7a535280c 100644
--- a/web/src/features/monitors/components/MonitorChartPreview.tsx
+++ b/web/src/features/monitors/components/MonitorChartPreview.tsx
@@ -1,15 +1,8 @@
-import { useMemo, useState } from "react";
+import { useMemo } from "react";
import { type z } from "zod";
import { api } from "@/src/utils/api";
import { Card, CardContent } from "@/src/components/ui/card";
-import {
- Select,
- SelectContent,
- SelectItem,
- SelectTrigger,
- SelectValue,
-} from "@/src/components/ui/select";
import { Chart } from "@/src/features/widgets/chart-library/Chart";
import { ChartLoadingState } from "@/src/features/widgets/chart-library/ChartLoadingState";
import { type DataPoint } from "@/src/features/widgets/chart-library/chart-props";
@@ -22,19 +15,14 @@ import {
import {
type MonitorThresholdOperator,
type MonitorView,
+ type MonitorWindow,
+ windowToMs,
} from "@langfuse/shared/monitors";
-import { TIME_RANGES } from "@/src/utils/date-range-utils";
-/** previewRangePresets lists the time ranges offered in the preview picker. */
-const previewRangePresets = [
- "last1Hour",
- "last6Hours",
- "last1Day",
- "last7Days",
- "last30Days",
-] as const satisfies ReadonlyArray<keyof typeof TIME_RANGES>;
+import { renderChartSubtitle } from "../helpers/renderMonitorLabels";
-type PreviewRangePreset = (typeof previewRangePresets)[number];
+/** previewBucketCount is the number of complete window buckets the preview renders. */
+const previewBucketCount = 20;
/** MonitorChartPreview renders the live time-series preview with alert/warning threshold bands for a monitor draft. */
export const MonitorChartPreview = ({
@@ -43,6 +31,7 @@ export const MonitorChartPreview = ({
filters,
measure,
aggregation,
+ window,
thresholdOperator,
alertThreshold,
warningThreshold,
@@ -52,23 +41,21 @@ export const MonitorChartPreview = ({
filters: FilterState;
measure: string;
aggregation: z.infer<typeof metricAggregations>;
+ window: MonitorWindow;
thresholdOperator: MonitorThresholdOperator;
alertThreshold: number | null | undefined;
warningThreshold: number | null | undefined;
}) => {
- /** rangePreset is the currently selected preview window key. */
- const [rangePreset, setRangePreset] =
- useState<PreviewRangePreset>("last1Day");
-
- /** fromTimestamp and toTimestamp bound the preview query to the picked range, anchored to now. */
+ /** fromTimestamp and toTimestamp span 20 complete window buckets ending at the last floored boundary. */
const { fromTimestamp, toTimestamp } = useMemo(() => {
- const now = Date.now();
- const minutes = TIME_RANGES[rangePreset].minutes ?? 24 * 60;
+ const ms = Number(windowToMs(window));
+ const to = Math.floor(Date.now() / ms) * ms;
+ const from = to - previewBucketCount * ms;
return {
- toTimestamp: new Date(now).toISOString(),
- fromTimestamp: new Date(now - minutes * 60_000).toISOString(),
+ toTimestamp: new Date(to).toISOString(),
+ fromTimestamp: new Date(from).toISOString(),
};
- }, [rangePreset]);
+ }, [window]);
/** queryResult runs the preview query for the draft monitor. */
const queryResult = api.dashboard.executeQuery.useQuery(
@@ -80,7 +67,7 @@ export const MonitorChartPreview = ({
dimensions: [],
metrics: [{ measure, aggregation }],
filters,
- timeDimension: { granularity: "auto" },
+ timeDimension: { granularity: window },
fromTimestamp,
toTimestamp,
orderBy: null,
@@ -139,24 +126,16 @@ export const MonitorChartPreview = ({
<Card className="h-full">
<CardContent className="flex h-full flex-col pt-4">
<div className="mb-4 flex items-center justify-between">
- <h3 className="text-lg font-bold tracking-tight">Live Preview</h3>
- <Select
- value={rangePreset}
- onValueChange={(value) =>
- setRangePreset(value as PreviewRangePreset)
- }
- >
- <SelectTrigger className="h-8 w-auto gap-2 text-xs">
- <SelectValue />
- </SelectTrigger>
- <SelectContent align="end">
- {previewRangePresets.map((preset) => (
- <SelectItem key={preset} value={preset} className="text-xs">
- {TIME_RANGES[preset].label}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
+ <div>
+ <h3 className="text-lg font-bold tracking-tight">Live Preview</h3>
+ <p className="text-muted-foreground text-sm">
+ {renderChartSubtitle({
+ view,
+ metric: { measure, aggregation },
+ window,
+ })}
+ </p>
+ </div>
</div>
<div className="relative min-h-0 flex-1">
<Chart
diff --git a/web/src/features/monitors/components/MonitorForm.tsx b/web/src/features/monitors/components/MonitorForm.tsx
index 8cc40321b1..ade15f0643 100644
--- a/web/src/features/monitors/components/MonitorForm.tsx
+++ b/web/src/features/monitors/components/MonitorForm.tsx
@@ -83,47 +83,16 @@ import { MonitorChartPreview } from "./MonitorChartPreview";
import { MonitorAutomationsPanel } from "./MonitorAutomationsPanel";
import { MonitorSeverityBadge } from "./MonitorSeverityBadge";
import { Badge } from "@/src/components/ui/badge";
-
-/** windowLabels maps each MonitorWindow enum value to a human label. */
-const windowLabels: Record<MonitorWindow, string> = {
- "5m": "5 minutes",
- "10m": "10 minutes",
- "15m": "15 minutes",
- "30m": "30 minutes",
- "1h": "1 hour",
- "2h": "2 hours",
- "4h": "4 hours",
- "1d": "1 day",
- "2d": "2 days",
- "1w": "1 week",
-};
-
-/** operatorLabels maps each MonitorThresholdOperator to a natural-language label. */
-const operatorLabels: Record<MonitorThresholdOperator, string> = {
- GT: "above",
- GTE: "above or equal to",
- LT: "below",
- LTE: "below or equal to",
- EQ: "equal to",
- NEQ: "not equal to",
-};
-
-/** operatorSymbol maps each MonitorThresholdOperator to a single math glyph. */
-const operatorSymbol: Record<MonitorThresholdOperator, string> = {
- GT: ">",
- GTE: "≥",
- LT: "<",
- LTE: "≤",
- EQ: "=",
- NEQ: "≠",
-};
-
-/** viewLabels maps each MonitorView to a human label. */
-const viewLabels: Record<MonitorView, string> = {
- observations: "Observations",
- "scores-numeric": "Scores (numeric)",
- "scores-categorical": "Scores (categorical)",
-};
+import {
+ operatorLabels,
+ operatorSymbol,
+ viewLabels,
+ windowLabels,
+} from "../helpers/monitorLabels";
+import {
+ aggregationLabel,
+ renderNamePlaceholder,
+} from "../helpers/renderMonitorLabels";
/** createDefaults returns the form defaults for a brand-new monitor. */
const createDefaults = (projectId: string): Partial<CreateMonitor> => ({
@@ -377,30 +346,27 @@ export const MonitorForm = ({
return getValidMonitorAggregationsForMeasure(measureDef);
}, [watched.view, watched.metric?.measure]);
- /** namePlaceholder builds an auto-suggested name from the current view + metric + threshold (e.g. "Count of Observations > 0"). */
- const namePlaceholder = useMemo(() => {
- const view = (watched.view ?? "observations") as MonitorView;
- const measure = watched.metric?.measure ?? "count";
- const aggregation = watched.metric?.aggregation ?? "count";
- const op = (watched.thresholdOperator ??
- MonitorThresholdOperatorSchema.enum.GT) as MonitorThresholdOperator;
- const threshold = watched.alertThreshold;
- const aggLabel = startCase(aggregation);
- const viewLabel = viewLabels[view];
- const base =
- measure === "count"
- ? `${aggLabel} of ${viewLabel}`
- : `${aggLabel} of ${viewLabel} ${startCase(measure)}`;
- const value =
- threshold != null && Number.isFinite(threshold) ? threshold : 0;
- return `${base} ${operatorSymbol[op]} ${value}`;
- }, [
- watched.view,
- watched.metric?.measure,
- watched.metric?.aggregation,
- watched.thresholdOperator,
- watched.alertThreshold,
- ]);
+ /** namePlaceholder builds an auto-suggested name from the current view + metric + threshold (e.g. "Sum of Observations Latency is below 100"). */
+ const namePlaceholder = useMemo(
+ () =>
+ renderNamePlaceholder({
+ view: (watched.view ?? "observations") as MonitorView,
+ metric: {
+ measure: watched.metric?.measure ?? "count",
+ aggregation: watched.metric?.aggregation ?? "count",
+ },
+ thresholdOperator: (watched.thresholdOperator ??
+ MonitorThresholdOperatorSchema.enum.GT) as MonitorThresholdOperator,
+ alertThreshold: watched.alertThreshold,
+ }),
+ [
+ watched.view,
+ watched.metric?.measure,
+ watched.metric?.aggregation,
+ watched.thresholdOperator,
+ watched.alertThreshold,
+ ],
+ );
namePlaceholderRef.current = namePlaceholder;
@@ -581,7 +547,7 @@ export const MonitorForm = ({
<SelectContent>
{aggregationOptions.map((a) => (
<SelectItem key={a} value={a}>
- {startCase(a)}
+ {aggregationLabel(a)}
</SelectItem>
))}
</SelectContent>
@@ -917,6 +883,7 @@ export const MonitorForm = ({
(watched.metric?.aggregation ??
"count") as CreateMonitor["metric"]["aggregation"]
}
+ window={(watched.window ?? "5m") as MonitorWindow}
thresholdOperator={
watched.thresholdOperator ??
MonitorThresholdOperatorSchema.enum.GT
diff --git a/web/src/features/monitors/helpers/monitorLabels.ts b/web/src/features/monitors/helpers/monitorLabels.ts
new file mode 100644
index 0000000000..d634c411ab
--- /dev/null
+++ b/web/src/features/monitors/helpers/monitorLabels.ts
@@ -0,0 +1,46 @@
+import {
+ type MonitorThresholdOperator,
+ type MonitorView,
+ type MonitorWindow,
+} from "@langfuse/shared/monitors";
+
+/** windowLabels maps each MonitorWindow enum value to a human label. */
+export const windowLabels: Record<MonitorWindow, string> = {
+ "5m": "5 minutes",
+ "10m": "10 minutes",
+ "15m": "15 minutes",
+ "30m": "30 minutes",
+ "1h": "1 hour",
+ "2h": "2 hours",
+ "4h": "4 hours",
+ "1d": "1 day",
+ "2d": "2 days",
+ "1w": "1 week",
+};
+
+/** operatorLabels maps each MonitorThresholdOperator to a natural-language label. */
+export const operatorLabels: Record<MonitorThresholdOperator, string> = {
+ GT: "above",
+ GTE: "above or equal to",
+ LT: "below",
+ LTE: "below or equal to",
+ EQ: "equal to",
+ NEQ: "not equal to",
+};
+
+/** operatorSymbol maps each MonitorThresholdOperator to a single math glyph. */
+export const operatorSymbol: Record<MonitorThresholdOperator, string> = {
+ GT: ">",
+ GTE: "≥",
+ LT: "<",
+ LTE: "≤",
+ EQ: "=",
+ NEQ: "≠",
+};
+
+/** viewLabels maps each MonitorView to a human label. */
+export const viewLabels: Record<MonitorView, string> = {
+ observations: "Observations",
+ "scores-numeric": "Scores (numeric)",
+ "scores-categorical": "Scores (categorical)",
+};
diff --git a/web/src/features/monitors/helpers/renderMonitorLabels.clienttest.ts b/web/src/features/monitors/helpers/renderMonitorLabels.clienttest.ts
new file mode 100644
index 0000000000..d6544bbf51
--- /dev/null
+++ b/web/src/features/monitors/helpers/renderMonitorLabels.clienttest.ts
@@ -0,0 +1,49 @@
+import { describe, expect, it } from "vitest";
+
+import { renderNamePlaceholder } from "./renderMonitorLabels";
+
+describe("renderNamePlaceholder", () => {
+ it("measured metric: aggregation of view + measure is operator threshold", () => {
+ expect(
+ renderNamePlaceholder({
+ view: "observations",
+ metric: { measure: "latency", aggregation: "sum" },
+ thresholdOperator: "LT",
+ alertThreshold: 100,
+ }),
+ ).toBe("Sum of Observations Latency is below 100");
+ });
+
+ it("percentile aggregation: kept verbatim, not start-cased into 'P 95'", () => {
+ expect(
+ renderNamePlaceholder({
+ view: "observations",
+ metric: { measure: "latency", aggregation: "p95" },
+ thresholdOperator: "GT",
+ alertThreshold: 100,
+ }),
+ ).toBe("p95 of Observations Latency is above 100");
+ });
+
+ it("bare count: omits the measure", () => {
+ expect(
+ renderNamePlaceholder({
+ view: "observations",
+ metric: { measure: "count", aggregation: "count" },
+ thresholdOperator: "GT",
+ alertThreshold: 5,
+ }),
+ ).toBe("Count of Observations is above 5");
+ });
+
+ it("missing threshold: defaults the value to 0", () => {
+ expect(
+ renderNamePlaceholder({
+ view: "observations",
+ metric: { measure: "count", aggregation: "count" },
+ thresholdOperator: "GT",
+ alertThreshold: null,
+ }),
+ ).toBe("Count of Observations is above 0");
+ });
+});
diff --git a/web/src/features/monitors/helpers/renderMonitorLabels.ts b/web/src/features/monitors/helpers/renderMonitorLabels.ts
new file mode 100644
index 0000000000..4fcc5df219
--- /dev/null
+++ b/web/src/features/monitors/helpers/renderMonitorLabels.ts
@@ -0,0 +1,73 @@
+import { startCase } from "lodash";
+import { type z } from "zod";
+
+import { type metricAggregations } from "@langfuse/shared";
+import {
+ type MonitorThresholdOperator,
+ type MonitorView,
+ type MonitorWindow,
+} from "@langfuse/shared/monitors";
+
+import { operatorLabels, viewLabels, windowLabels } from "./monitorLabels";
+
+/** proseWindowLabels overrides windowLabels for prose, dropping the redundant "1" on singular units. */
+const proseWindowLabels: Partial<Record<MonitorWindow, string>> = {
+ "1h": "hour",
+ "1d": "day",
+ "1w": "week",
+};
+
+/** windowLabel renders a window for prose, e.g. "hour" or "5 minutes". */
+const windowLabel = (window: MonitorWindow): string =>
+ proseWindowLabels[window] ?? windowLabels[window];
+
+/** aggregationLabel renders an aggregation as a leading word, e.g. "Sum" or "p95". */
+export const aggregationLabel = (
+ aggregation: z.infer<typeof metricAggregations>,
+): string =>
+ // startCase mangles percentile tokens ("p95" -> "P 95"); keep them verbatim.
+ /^p\d+$/.test(aggregation) ? aggregation : startCase(aggregation);
+
+/** metricSubject renders the noun a metric measures, e.g. "Observations Latency" or "Observations" for a bare count. */
+const metricSubject = (view: MonitorView, measure: string): string =>
+ measure === "count"
+ ? viewLabels[view]
+ : `${viewLabels[view]} ${startCase(measure)}`;
+
+/** renderMetricDescription renders a metric as prose, e.g. "Sum of Observations Latency". */
+const renderMetricDescription = (
+ view: MonitorView,
+ metric: { measure: string; aggregation: z.infer<typeof metricAggregations> },
+): string =>
+ `${aggregationLabel(metric.aggregation)} of ${metricSubject(view, metric.measure)}`;
+
+/** renderNamePlaceholder renders the auto-suggested monitor name, e.g. "Sum of Observations Latency is below 100". */
+export const renderNamePlaceholder = ({
+ view,
+ metric,
+ thresholdOperator,
+ alertThreshold,
+}: {
+ view: MonitorView;
+ metric: { measure: string; aggregation: z.infer<typeof metricAggregations> };
+ thresholdOperator: MonitorThresholdOperator;
+ alertThreshold?: number | null;
+}): string => {
+ const value =
+ alertThreshold != null && Number.isFinite(alertThreshold)
+ ? alertThreshold
+ : 0;
+ return `${renderMetricDescription(view, metric)} is ${operatorLabels[thresholdOperator]} ${value}`;
+};
+
+/** renderChartSubtitle renders the preview subtitle, e.g. "Sum of Observations Latency every 5 minutes". */
+export const renderChartSubtitle = ({
+ view,
+ metric,
+ window,
+}: {
+ view: MonitorView;
+ metric: { measure: string; aggregation: z.infer<typeof metricAggregations> };
+ window: MonitorWindow;
+}): string =>
+ `${renderMetricDescription(view, metric)} every ${windowLabel(window)}`;
diff --git a/web/src/features/monitors/index.ts b/web/src/features/monitors/index.ts
deleted file mode 100644
index 3f95154ffc..0000000000
--- a/web/src/features/monitors/index.ts
+++ /dev/null
@@ -1 +0,0 @@
-export { MonitorForm } from "./components/MonitorForm";
diff --git a/web/src/features/monitors/pages/EditMonitorPage.tsx b/web/src/features/monitors/pages/EditMonitorPage.tsx
index 33891aaa12..2f18bde894 100644
--- a/web/src/features/monitors/pages/EditMonitorPage.tsx
+++ b/web/src/features/monitors/pages/EditMonitorPage.tsx
@@ -3,7 +3,7 @@ import { useEffect, useState } from "react";
import { ErrorPage } from "@/src/components/error-page";
import Page from "@/src/components/layouts/page";
-import { MonitorForm } from "@/src/features/monitors";
+import { MonitorForm } from "@/src/features/monitors/components/MonitorForm";
import { MonitorPagePermissions } from "@/src/features/monitors/components/MonitorPagePermissions";
import { api } from "@/src/utils/api";
diff --git a/web/src/features/monitors/pages/NewMonitorPage.tsx b/web/src/features/monitors/pages/NewMonitorPage.tsx
index 31564129f7..f5407c1b80 100644
--- a/web/src/features/monitors/pages/NewMonitorPage.tsx
+++ b/web/src/features/monitors/pages/NewMonitorPage.tsx
@@ -1,7 +1,7 @@
import { useRouter } from "next/router";
import Page from "@/src/components/layouts/page";
-import { MonitorForm } from "@/src/features/monitors";
+import { MonitorForm } from "@/src/features/monitors/components/MonitorForm";
import { MonitorPagePermissions } from "@/src/features/monitors/components/MonitorPagePermissions";
/** NewMonitorPage renders the create-monitor form for a project. */
diff --git a/web/src/features/public-api/types/metrics.ts b/web/src/features/public-api/types/metrics.ts
index dff05fa0f7..537c4c7bb2 100644
--- a/web/src/features/public-api/types/metrics.ts
+++ b/web/src/features/public-api/types/metrics.ts
@@ -14,6 +14,16 @@ import {
viewsV2,
} from "@langfuse/shared/query";
+/** publicGranularities is the base 6 granularities exposed on the public metrics API and MCP. */
+export const publicGranularities = granularities.extract([
+ "auto",
+ "minute",
+ "hour",
+ "day",
+ "week",
+ "month",
+]);
+
/**
* Query Object Structure
*/
@@ -30,7 +40,7 @@ export const MetricsQueryObject = z
filters: z.array(singleFilter).optional().default([]),
timeDimension: z
.object({
- granularity: granularities,
+ granularity: publicGranularities,
})
.nullable()
.optional()
@@ -98,7 +108,7 @@ export const MetricsQueryObjectV2 = z
filters: z.array(singleFilter).optional().default([]),
timeDimension: z
.object({
- granularity: granularities,
+ granularity: publicGranularities,
})
.nullable()
.optional()