Skip to content

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

chore(dashboards): expand measures for dashboards (#6932)

Steffen Schmitze8787e3f38e7
diff --git a/web/src/__tests__/queryBuilder.servertest.ts b/web/src/__tests__/queryBuilder.servertest.ts
index fe739927a2..8895d08ef1 100644
--- a/web/src/__tests__/queryBuilder.servertest.ts
+++ b/web/src/__tests__/queryBuilder.servertest.ts
@@ -3046,6 +3046,229 @@ describe("queryBuilder", () => {
);
});
+ it("should return null streamingLatency and timeToFirstToken when completion_start_time is null", async () => {
+ const projectId = randomUUID();
+
+ // Create trace
+ const trace = createTrace({
+ project_id: projectId,
+ name: "null-completion-start-time-trace",
+ environment: "default",
+ timestamp: new Date().getTime(),
+ });
+ await createTracesCh([trace]);
+
+ // Create observation with NULL completion_start_time
+ const startTime = new Date();
+ const endTime = new Date(startTime.getTime() + 1000);
+ const observation = createObservation({
+ project_id: projectId,
+ trace_id: trace.id,
+ type: "generation",
+ name: "model-x",
+ provided_model_name: "model-x",
+ environment: "default",
+ start_time: startTime.getTime(),
+ completion_start_time: null, // explicitly null
+ end_time: endTime.getTime(),
+ });
+ await createObservationsCh([observation]);
+
+ // Build query selecting metrics per observation
+ const query: QueryType = {
+ view: "observations",
+ dimensions: [{ field: "name" }],
+ metrics: [
+ { measure: "timeToFirstToken", aggregation: "max" },
+ { measure: "streamingLatency", aggregation: "max" },
+ ],
+ 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,
+ };
+
+ const queryBuilder = new QueryBuilder();
+ const { query: compiledQuery, parameters } = queryBuilder.build(
+ query,
+ projectId,
+ );
+
+ const result = await (
+ await clickhouseClient().query({
+ query: compiledQuery,
+ query_params: parameters,
+ })
+ ).json();
+
+ expect(result.data).toHaveLength(1);
+ const row = result.data[0];
+ expect(row.max_timeToFirstToken).toBeNull();
+ expect(row.max_streamingLatency).toBeNull();
+ });
+
+ it("should return streamingLatency and timeToFirstToken when completion_start_time is present", async () => {
+ const projectId = randomUUID();
+
+ // Create trace
+ const trace = createTrace({
+ project_id: projectId,
+ name: "null-completion-start-time-trace",
+ environment: "default",
+ timestamp: new Date().getTime(),
+ });
+ await createTracesCh([trace]);
+
+ // Create observation with NULL completion_start_time
+ const startTime = new Date();
+ const endTime = new Date(startTime.getTime() + 1000);
+ const observation = createObservation({
+ project_id: projectId,
+ trace_id: trace.id,
+ type: "generation",
+ name: "model-x",
+ provided_model_name: "model-x",
+ environment: "default",
+ start_time: startTime.getTime(),
+ completion_start_time: startTime.getTime() + 200,
+ end_time: endTime.getTime(),
+ });
+ await createObservationsCh([observation]);
+
+ // Build query selecting metrics per observation
+ const query: QueryType = {
+ view: "observations",
+ dimensions: [{ field: "name" }],
+ metrics: [
+ { measure: "timeToFirstToken", aggregation: "max" },
+ { measure: "streamingLatency", aggregation: "max" },
+ ],
+ 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,
+ };
+
+ const queryBuilder = new QueryBuilder();
+ const { query: compiledQuery, parameters } = queryBuilder.build(
+ query,
+ projectId,
+ );
+
+ const result = await (
+ await clickhouseClient().query({
+ query: compiledQuery,
+ query_params: parameters,
+ })
+ ).json();
+
+ expect(result.data).toHaveLength(1);
+ const row = result.data[0];
+ expect(row.max_timeToFirstToken).toBe("200");
+ expect(row.max_streamingLatency).toBe("800");
+ });
+
+ it("should calculate tokens correctly", async () => {
+ const projectId = randomUUID();
+
+ // Create trace
+ const trace = createTrace({
+ project_id: projectId,
+ name: "null-completion-start-time-trace",
+ environment: "default",
+ timestamp: new Date().getTime(),
+ });
+ await createTracesCh([trace]);
+
+ // Create observation with NULL completion_start_time
+ const startTime = new Date();
+ const endTime = new Date(startTime.getTime() + 1000);
+ const observation = createObservation({
+ project_id: projectId,
+ trace_id: trace.id,
+ type: "generation",
+ name: "model-x",
+ provided_model_name: "model-x",
+ environment: "default",
+ start_time: startTime.getTime(),
+ completion_start_time: startTime.getTime() + 200,
+ end_time: endTime.getTime(),
+ usage_details: {
+ input_tokens: 100,
+ input_cache_tokens: 200,
+ output_tokens: 300,
+ output_cache_tokens: 400,
+ total: 1000,
+ },
+ });
+ await createObservationsCh([observation]);
+
+ // Build query selecting metrics per observation
+ const query: QueryType = {
+ view: "observations",
+ dimensions: [{ field: "name" }],
+ metrics: [
+ { measure: "inputTokens", aggregation: "sum" },
+ { measure: "outputTokens", aggregation: "sum" },
+ { measure: "totalTokens", aggregation: "sum" },
+ { measure: "outputTokensPerSecond", aggregation: "avg" },
+ ],
+ filters: [],
+ 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,
+ };
+
+ const queryBuilder = new QueryBuilder();
+ const { query: compiledQuery, parameters } = queryBuilder.build(
+ query,
+ projectId,
+ );
+
+ const result = await (
+ await clickhouseClient().query({
+ query: compiledQuery,
+ query_params: parameters,
+ })
+ ).json();
+
+ expect(result.data).toHaveLength(1);
+ const row = result.data[0];
+ expect(row.sum_inputTokens).toBe("300");
+ expect(row.sum_outputTokens).toBe("700");
+ expect(row.sum_totalTokens).toBe("1000");
+ expect(row.avg_outputTokensPerSecond).toBe(700);
+ });
+
it("should filter observations by metadata correctly", async () => {
// Setup
const projectId = randomUUID();
diff --git a/web/src/features/query/dataModel.ts b/web/src/features/query/dataModel.ts
index 1774a555db..3f55b00685 100644
--- a/web/src/features/query/dataModel.ts
+++ b/web/src/features/query/dataModel.ts
@@ -268,8 +268,32 @@ export const observationsView: ViewDeclarationType = {
sql: "date_diff('millisecond', any(observations.start_time), any(observations.end_time))",
alias: "latency",
type: "integer",
- description: "Latency of an individual observation.",
- unit: "ms",
+ description:
+ "Latency of an individual observation (start time to end time).",
+ unit: "millisecond",
+ },
+ streamingLatency: {
+ // Return NULL if `completion_start_time` is NULL to avoid misleading latency values
+ sql: "if(isNull(any(observations.completion_start_time)), CAST(NULL AS Nullable(Int64)), date_diff('millisecond', any(observations.completion_start_time), any(observations.end_time)))",
+ alias: "streamingLatency",
+ type: "integer",
+ description:
+ "Latency of the generation step (completion start time to end time).",
+ unit: "millisecond",
+ },
+ inputTokens: {
+ sql: "arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'input') > 0, any(usage_details))))",
+ alias: "inputTokens",
+ type: "integer",
+ description: "Sum of input tokens consumed by the observation.",
+ unit: "tokens",
+ },
+ outputTokens: {
+ sql: "arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'output') > 0, any(usage_details))))",
+ alias: "outputTokens",
+ type: "integer",
+ description: "Sum of output tokens produced by the observation.",
+ unit: "tokens",
},
totalTokens: {
sql: "sumMap(usage_details)['total']",
@@ -278,19 +302,53 @@ export const observationsView: ViewDeclarationType = {
description: "Sum of tokens consumed by the observation.",
unit: "tokens",
},
+ outputTokensPerSecond: {
+ // Calculate average output tokens per second. Denominator uses seconds to align
+ // with the `tokens/s` unit; NULL values avoided by guarding against a 0-second
+ // duration.
+ sql: "arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'output') > 0, any(usage_details)))) / nullIf(date_diff('second', any(observations.completion_start_time), any(observations.end_time)), 0)",
+ alias: "outputTokensPerSecond",
+ type: "decimal",
+ description:
+ "Average number of output tokens produced per second between completion start time and span end time.",
+ unit: "tokens/s",
+ },
+ tokensPerSecond: {
+ sql: "sumMap(usage_details)['total'] / date_diff('second', any(observations.start_time), any(observations.end_time))",
+ alias: "tokensPerSecond",
+ type: "decimal",
+ description:
+ "Average number of tokens consumed per second by the observation.",
+ unit: "tokens/s",
+ },
+ inputCost: {
+ sql: "arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'input') > 0, any(cost_details))))",
+ alias: "inputCost",
+ type: "decimal",
+ description: "Sum of input cost incurred by the observation.",
+ unit: "USD",
+ },
+ outputCost: {
+ sql: "arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'output') > 0, any(cost_details))))",
+ alias: "outputCost",
+ type: "decimal",
+ description: "Sum of output cost incurred by the observation.",
+ unit: "USD",
+ },
totalCost: {
sql: "sum(total_cost)",
alias: "totalCost",
type: "decimal",
- description: "Total cost accumulated by the observation.",
+ description: "Total cost incurred by the observation.",
unit: "USD",
},
timeToFirstToken: {
- sql: "date_diff('millisecond', any(observations.start_time), any(observations.completion_start_time))",
+ // Return NULL if `completion_start_time` is NULL to represent unknown TTFT
+ sql: "if(isNull(any(observations.completion_start_time)), CAST(NULL AS Nullable(Int64)), date_diff('millisecond', any(observations.start_time), any(observations.completion_start_time)))",
alias: "timeToFirstToken",
type: "integer",
description: "Time to first token for the observation.",
- unit: "ms",
+ unit: "millisecond",
},
countScores: {
sql: "uniq(scores.id)",
diff --git a/web/src/features/widgets/components/DashboardWidget.tsx b/web/src/features/widgets/components/DashboardWidget.tsx
index 71f22c0f35..5abada633e 100644
--- a/web/src/features/widgets/components/DashboardWidget.tsx
+++ b/web/src/features/widgets/components/DashboardWidget.tsx
@@ -123,9 +123,15 @@ export function DashboardWidget({
return {
dimension:
item[dimensionField] !== undefined
- ? item[dimensionField]
- ? (item[dimensionField] as string)
- : "n/a"
+ ? (() => {
+ const val = item[dimensionField];
+ if (typeof val === "string") return val;
+ if (val === null || val === undefined || val === "")
+ return "n/a";
+ if (Array.isArray(val)) return val.join(", ");
+ // Objects / numbers / booleans are stringified to avoid React key issues
+ return String(val);
+ })()
: startCase(metricField === "count_count" ? "Count" : metricField),
metric: Number(item[metricField] || 0),
time_dimension: item["time_dimension"],
diff --git a/web/src/features/widgets/components/WidgetForm.tsx b/web/src/features/widgets/components/WidgetForm.tsx
index 0e3d06c412..030b7b214f 100644
--- a/web/src/features/widgets/components/WidgetForm.tsx
+++ b/web/src/features/widgets/components/WidgetForm.tsx
@@ -357,9 +357,14 @@ export function WidgetForm({
return {
dimension:
item[dimensionField] !== undefined
- ? item[dimensionField]
- ? (item[dimensionField] as string)
- : "n/a"
+ ? (() => {
+ const val = item[dimensionField];
+ if (typeof val === "string") return val;
+ if (val === null || val === undefined || val === "")
+ return "n/a";
+ if (Array.isArray(val)) return val.join(", ");
+ return String(val);
+ })()
: startCase(
metricField === "count_count" ? "Count" : metricField,
),