Skip to content

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

feat: add new metrics api endpoint (#6778)

Steffen Schmitzd94e7c1c06a6
diff --git a/fern/apis/server/definition/metrics.yml b/fern/apis/server/definition/metrics.yml
index 20fd7ac421..ca1e8282fc 100644
--- a/fern/apis/server/definition/metrics.yml
+++ b/fern/apis/server/definition/metrics.yml
@@ -6,6 +6,54 @@ service:
auth: true
base-path: /api/public
endpoints:
+ metrics:
+ docs: Get metrics from the Langfuse project using a query object
+ method: GET
+ path: /metrics
+ request:
+ name: GetMetricsRequest
+ query-parameters:
+ query:
+ type: string
+ docs: |
+ JSON string containing the query parameters with the following structure:
+ ```json
+ {
+ "view": string, // Required. One of "traces", "observations", "scores-numeric", "scores-categorical"
+ "dimensions": [ // Optional. Default: []
+ {
+ "field": string // Field to group by, e.g. "name", "userId", "sessionId"
+ }
+ ],
+ "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"
+ }
+ ],
+ "filters": [ // Optional. Default: []
+ {
+ "column": string, // Column to filter on
+ "operator": string, // Operator, e.g. "=", ">", "<", "contains"
+ "value": any, // Value to compare against
+ "type": string, // Data type, e.g. "string", "number", "stringObject"
+ "key": string // Required only when filtering on metadata
+ }
+ ],
+ "timeDimension": { // Optional. Default: null. If provided, results will be grouped by time
+ "granularity": string // One of "minute", "hour", "day", "week", "month", "year", "auto"
+ },
+ "fromTimestamp": string, // Required. ISO datetime string for start of time range
+ "toTimestamp": string, // Required. ISO datetime string for end of time range
+ "orderBy": [ // Optional. Default: null
+ {
+ "field": string, // Field to order by
+ "direction": string // "asc" or "desc"
+ }
+ ]
+ }
+ ```
+ response: MetricsResponse
daily:
docs: Get daily metrics of the Langfuse project
method: GET
@@ -41,6 +89,13 @@ service:
docs: Optional filter to only include traces and observations before a certain datetime (ISO 8601)
response: DailyMetrics
types:
+ MetricsResponse:
+ properties:
+ data:
+ type: list<map<string, unknown>>
+ 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.
DailyMetrics:
properties:
data:
diff --git a/web/public/generated/api/openapi.yml b/web/public/generated/api/openapi.yml
index f53326eb4c..d1f7895eef 100644
--- a/web/public/generated/api/openapi.yml
+++ b/web/public/generated/api/openapi.yml
@@ -1692,6 +1692,94 @@ paths:
application/json:
schema:
$ref: '#/components/schemas/MembershipRequest'
+ /api/public/metrics:
+ get:
+ description: Get metrics from the Langfuse project using a query object
+ operationId: metrics_metrics
+ tags:
+ - Metrics
+ parameters:
+ - name: query
+ in: query
+ description: >-
+ JSON string containing the query parameters with the following
+ structure:
+
+ ```json
+
+ {
+ "view": string, // Required. One of "traces", "observations", "scores-numeric", "scores-categorical"
+ "dimensions": [ // Optional. Default: []
+ {
+ "field": string // Field to group by, e.g. "name", "userId", "sessionId"
+ }
+ ],
+ "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"
+ }
+ ],
+ "filters": [ // Optional. Default: []
+ {
+ "column": string, // Column to filter on
+ "operator": string, // Operator, e.g. "=", ">", "<", "contains"
+ "value": any, // Value to compare against
+ "type": string, // Data type, e.g. "string", "number", "stringObject"
+ "key": string // Required only when filtering on metadata
+ }
+ ],
+ "timeDimension": { // Optional. Default: null. If provided, results will be grouped by time
+ "granularity": string // One of "minute", "hour", "day", "week", "month", "year", "auto"
+ },
+ "fromTimestamp": string, // Required. ISO datetime string for start of time range
+ "toTimestamp": string, // Required. ISO datetime string for end of time range
+ "orderBy": [ // Optional. Default: null
+ {
+ "field": string, // Field to order by
+ "direction": string // "asc" or "desc"
+ }
+ ]
+ }
+
+ ```
+ required: true
+ schema:
+ type: string
+ responses:
+ '200':
+ description: ''
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/MetricsResponse'
+ '400':
+ description: ''
+ content:
+ application/json:
+ schema: {}
+ '401':
+ description: ''
+ content:
+ application/json:
+ schema: {}
+ '403':
+ description: ''
+ content:
+ application/json:
+ schema: {}
+ '404':
+ description: ''
+ content:
+ application/json:
+ schema: {}
+ '405':
+ description: ''
+ content:
+ application/json:
+ schema: {}
+ security:
+ - BasicAuth: []
/api/public/metrics/daily:
get:
description: Get daily metrics of the Langfuse project
@@ -6266,6 +6354,22 @@ components:
$ref: '#/components/schemas/MembershipResponse'
required:
- memberships
+ MetricsResponse:
+ title: MetricsResponse
+ type: object
+ properties:
+ data:
+ type: array
+ items:
+ type: object
+ additionalProperties: true
+ description: >-
+ 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.
+ required:
+ - data
DailyMetrics:
title: DailyMetrics
type: object
diff --git a/web/public/generated/postman/collection.json b/web/public/generated/postman/collection.json
index f27df52605..df210a4387 100644
--- a/web/public/generated/postman/collection.json
+++ b/web/public/generated/postman/collection.json
@@ -1341,6 +1341,37 @@
"description": null,
"name": "Metrics",
"item": [
+ {
+ "_type": "endpoint",
+ "name": "Metrics",
+ "request": {
+ "description": "Get metrics from the Langfuse project using a query object",
+ "url": {
+ "raw": "{{baseUrl}}/api/public/metrics?query=",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "api",
+ "public",
+ "metrics"
+ ],
+ "query": [
+ {
+ "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\", \"year\", \"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```"
+ }
+ ],
+ "variable": []
+ },
+ "header": [],
+ "method": "GET",
+ "auth": null,
+ "body": null
+ },
+ "response": []
+ },
{
"_type": "endpoint",
"name": "Daily",
diff --git a/web/src/__tests__/async/metrics-api.servertest.ts b/web/src/__tests__/async/metrics-api.servertest.ts
new file mode 100644
index 0000000000..ea32505805
--- /dev/null
+++ b/web/src/__tests__/async/metrics-api.servertest.ts
@@ -0,0 +1,302 @@
+import { randomUUID } from "crypto";
+import {
+ makeZodVerifiedAPICall,
+ makeZodVerifiedAPICallSilent,
+ makeAPICall,
+} from "@/src/__tests__/test-utils";
+import { GetMetricsV1Response } from "@/src/features/public-api/types/metrics";
+import { createBasicAuthHeader } from "@langfuse/shared/src/server";
+import { type QueryType } from "@/src/features/query/types";
+import {
+ createTrace,
+ createObservation,
+ createTracesCh,
+ createObservationsCh,
+} from "@langfuse/shared/src/server";
+
+describe("/api/public/metrics API Endpoint", () => {
+ // Test setup variables
+ const testTraces: Array<{
+ id: string;
+ name: string;
+ timestamp: Date;
+ metadata?: Record<string, any>;
+ }> = [];
+ const testMetadataValue = randomUUID();
+ const projectId = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";
+
+ // Current time for traces
+ const tomorrow = new Date(new Date().getTime() + 3600 * 24 * 1000);
+ const now = new Date();
+ const yesterday = new Date(new Date().getTime() - 3600 * 24 * 1000);
+ const twoDaysAgo = new Date(new Date().getTime() - 3600 * 24 * 2 * 1000);
+
+ // Set up test data before running tests
+ beforeAll(async () => {
+ // Create test traces with different names
+ const trace1Id = randomUUID();
+ const trace2Id = randomUUID();
+ const trace3Id = randomUUID();
+
+ // Create traces with different names and timestamps
+ testTraces.push(
+ {
+ id: trace1Id,
+ name: "trace-test-1",
+ timestamp: now,
+ metadata: { test: testMetadataValue },
+ },
+ {
+ id: trace2Id,
+ name: "trace-test-2",
+ timestamp: yesterday,
+ metadata: { test: testMetadataValue },
+ },
+ {
+ id: trace3Id,
+ name: "trace-test-3",
+ timestamp: yesterday,
+ metadata: { test: testMetadataValue },
+ },
+ );
+
+ // Insert traces into database
+ await createTracesCh(
+ testTraces.map((trace) =>
+ createTrace({
+ id: trace.id,
+ name: trace.name,
+ project_id: projectId,
+ timestamp: trace.timestamp.getTime(),
+ metadata: trace.metadata || {},
+ }),
+ ),
+ );
+
+ // Create observations for trace1
+ const trace1Observations = [];
+ for (let i = 0; i < 3; i++) {
+ trace1Observations.push(
+ createObservation({
+ id: randomUUID(),
+ trace_id: trace1Id,
+ project_id: projectId,
+ name: `observation-${i}`,
+ start_time: now.getTime(),
+ metadata: { test: testMetadataValue },
+ }),
+ );
+ }
+
+ // Create observations for trace2
+ const trace2Observations = [];
+ for (let i = 0; i < 2; i++) {
+ trace2Observations.push(
+ createObservation({
+ id: randomUUID(),
+ trace_id: trace2Id,
+ project_id: projectId,
+ name: `observation-${i}`,
+ start_time: yesterday.getTime(),
+ metadata: { test: testMetadataValue },
+ }),
+ );
+ }
+ await createObservationsCh([...trace1Observations, ...trace2Observations]);
+ });
+
+ it.each([
+ [
+ "simple trace query",
+ {
+ view: "traces",
+ dimensions: [{ field: "name" }],
+ metrics: [{ measure: "count", aggregation: "count" }],
+ filters: [
+ {
+ column: "metadata",
+ operator: "contains",
+ key: "test",
+ value: testMetadataValue,
+ type: "stringObject",
+ },
+ ],
+ timeDimension: null,
+ fromTimestamp: twoDaysAgo.toISOString(),
+ toTimestamp: tomorrow.toISOString(),
+ orderBy: null,
+ } as QueryType,
+ // Expected result structure (data will be dummy)
+ {
+ dataLength: 3,
+ expectedMetrics: ["count_count"],
+ expectedDimensions: ["name"],
+ },
+ ],
+ [
+ "query with time dimension",
+ {
+ view: "traces",
+ dimensions: [{ field: "name" }],
+ metrics: [{ measure: "count", aggregation: "count" }],
+ filters: [
+ {
+ column: "metadata",
+ operator: "contains",
+ key: "test",
+ value: testMetadataValue,
+ type: "stringObject",
+ },
+ ],
+ timeDimension: {
+ granularity: "day",
+ },
+ fromTimestamp: twoDaysAgo.toISOString(),
+ toTimestamp: tomorrow.toISOString(),
+ orderBy: null,
+ } as QueryType,
+ // Expected result structure
+ {
+ dataLength: 4,
+ expectedMetrics: ["count_count"],
+ expectedDimensions: ["time_dimension", "name"],
+ },
+ ],
+ [
+ "observations query with multiple metrics",
+ {
+ view: "observations",
+ dimensions: [{ field: "name" }],
+ metrics: [
+ { measure: "count", aggregation: "count" },
+ { measure: "latency", aggregation: "p95" },
+ ],
+ filters: [
+ {
+ column: "metadata",
+ operator: "contains",
+ key: "test",
+ value: testMetadataValue,
+ type: "stringObject",
+ },
+ ],
+ timeDimension: null,
+ fromTimestamp: twoDaysAgo.toISOString(),
+ toTimestamp: tomorrow.toISOString(),
+ orderBy: null,
+ } as QueryType,
+ // Expected result structure
+ {
+ dataLength: 3,
+ expectedMetrics: ["count_count", "p95_latency"],
+ expectedDimensions: ["name"],
+ },
+ ],
+ ])(
+ "should accept queries and return expected results: %s",
+ async (
+ _name: string,
+ queryObject: QueryType,
+ expectedResult: {
+ dataLength: number;
+ expectedMetrics: string[];
+ expectedDimensions: string[];
+ },
+ ) => {
+ // Add pagination parameters needed for the API
+ const fullQuery = {
+ ...queryObject,
+ // page: 1,
+ // limit: 10,
+ };
+
+ // Make the API call
+ const response = await makeZodVerifiedAPICall(
+ GetMetricsV1Response,
+ "GET",
+ `/api/public/metrics?query=${encodeURIComponent(JSON.stringify(fullQuery))}`,
+ );
+
+ // Validate response format
+ expect(response.status).toBe(200);
+ expect(Array.isArray(response.body.data)).toBe(true);
+
+ // Validate response matches expected structure
+ expect(response.body.data).toHaveLength(expectedResult.dataLength);
+ response.body.data.forEach((item) => {
+ expect(
+ expectedResult.expectedMetrics.every((metric) => metric in item),
+ ).toBe(true);
+ expect(
+ expectedResult.expectedDimensions.every(
+ (dimension) => dimension in item,
+ ),
+ ).toBe(true);
+ });
+ },
+ );
+
+ it("should return 401 with invalid authentication", async () => {
+ const now = new Date();
+ const yesterday = new Date(now);
+ yesterday.setDate(yesterday.getDate() - 1);
+
+ // Create the query object
+ const query = {
+ view: "traces",
+ metrics: [
+ {
+ measure: "totalCount",
+ aggregation: "count",
+ },
+ ],
+ fromTimestamp: yesterday.toISOString(),
+ toTimestamp: now.toISOString(),
+ page: 1,
+ limit: 10,
+ };
+
+ const invalidAuth = createBasicAuthHeader(
+ "invalid-project-key",
+ "invalid-secret-key",
+ );
+
+ const { status } = await makeAPICall(
+ "GET",
+ `/api/public/metrics?query=${encodeURIComponent(JSON.stringify(query))}`,
+ undefined,
+ invalidAuth,
+ );
+
+ expect(status).toBe(401);
+ });
+
+ it("should return 400 for invalid query parameters", async () => {
+ // Test missing required parameters by sending an invalid JSON string
+ const { status } = await makeZodVerifiedAPICallSilent(
+ GetMetricsV1Response,
+ "GET",
+ `/api/public/metrics?query=invalid-json-string`,
+ undefined,
+ );
+
+ expect(status).toBe(400);
+ });
+
+ it("should return 400 for incomplete query object", async () => {
+ // Missing required fields in the query object
+ const incompleteQuery = {
+ view: "traces",
+ // Missing metrics, fromTimestamp, toTimestamp
+ };
+
+ const { status } = await makeZodVerifiedAPICallSilent(
+ GetMetricsV1Response,
+ "GET",
+ `/api/public/metrics?query=${encodeURIComponent(JSON.stringify(incompleteQuery))}`,
+ undefined,
+ );
+
+ expect(status).toBe(400);
+ });
+});
diff --git a/web/src/features/public-api/types/metrics.ts b/web/src/features/public-api/types/metrics.ts
index 6b17dec163..2802595c30 100644
--- a/web/src/features/public-api/types/metrics.ts
+++ b/web/src/features/public-api/types/metrics.ts
@@ -1,14 +1,80 @@
import {
+ InvalidRequestError,
paginationMetaResponseZod,
publicApiPaginationZod,
+ singleFilter,
} from "@langfuse/shared";
import { stringDateTime } from "@langfuse/shared/src/server";
import { z } from "zod";
+import { dimension, granularities, metric, views } from "@/src/features/query";
+
+/**
+ * Query Object Structure
+ */
+export const MetricsQueryObject = z
+ .object({
+ // Pagination parameters
+ // page: z.number().min(1).default(1),
+ // limit: z.number().min(1).max(100).default(10),
+
+ // QueryType structure
+ view: views,
+ dimensions: z.array(dimension).optional().default([]),
+ metrics: z.array(metric),
+ filters: z.array(singleFilter).optional().default([]),
+ timeDimension: z
+ .object({
+ granularity: granularities,
+ })
+ .nullable()
+ .optional()
+ .default(null),
+ fromTimestamp: z.string().datetime({ offset: true }),
+ toTimestamp: z.string().datetime({ offset: true }),
+ orderBy: z
+ .array(
+ z.object({
+ field: z.string(),
+ direction: z.enum(["asc", "desc"]),
+ }),
+ )
+ .nullable()
+ .optional()
+ .default(null),
+ })
+ .refine(
+ (query) =>
+ // Ensure fromTimestamp is before toTimestamp
+ new Date(query.fromTimestamp).getTime() <
+ new Date(query.toTimestamp).getTime(),
+ {
+ message: "fromTimestamp must be before toTimestamp",
+ },
+ );
/**
* Endpoints
*/
+// GET /api/public/metrics
+export const GetMetricsV1Query = z.object({
+ query: z
+ .string()
+ .transform((str) => {
+ try {
+ return JSON.parse(str);
+ } catch (e) {
+ throw new InvalidRequestError("Invalid JSON in query parameter");
+ }
+ })
+ .pipe(MetricsQueryObject),
+});
+
+export const GetMetricsV1Response = z.object({
+ data: z.array(z.record(z.unknown())),
+ // meta: paginationMetaResponseZod,
+});
+
// Get /metrics/daily
export const GetMetricsDailyV1Query = z.object({
...publicApiPaginationZod,
diff --git a/web/src/pages/api/public/metrics/index.ts b/web/src/pages/api/public/metrics/index.ts
new file mode 100644
index 0000000000..72c83cc323
--- /dev/null
+++ b/web/src/pages/api/public/metrics/index.ts
@@ -0,0 +1,67 @@
+import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";
+import { createAuthedProjectAPIRoute } from "@/src/features/public-api/server/createAuthedProjectAPIRoute";
+import { logger } from "@langfuse/shared/src/server";
+import {
+ GetMetricsV1Query,
+ GetMetricsV1Response,
+} from "@/src/features/public-api/types/metrics";
+import { QueryBuilder } from "@/src/features/query/server/queryBuilder";
+import { queryClickhouse } from "@langfuse/shared/src/server";
+
+export default withMiddlewares({
+ GET: createAuthedProjectAPIRoute({
+ name: "Get Metrics",
+ rateLimitResource: "public-api-metrics",
+ querySchema: GetMetricsV1Query,
+ responseSchema: GetMetricsV1Response,
+ fn: async ({ query, auth }) => {
+ try {
+ // Extract the parsed query object
+ const queryParams = query.query;
+
+ // Log the received query for debugging
+ logger.info("Received metrics query", {
+ query: queryParams,
+ projectId: auth.scope.projectId,
+ });
+
+ // Execute the query using QueryBuilder
+ const { query: compiledQuery, parameters } = new QueryBuilder().build(
+ queryParams,
+ auth.scope.projectId,
+ );
+
+ // Run the query against ClickHouse
+ const result = await queryClickhouse<Record<string, unknown>>({
+ query: compiledQuery,
+ params: parameters,
+ clickhouseConfigs: {
+ clickhouse_settings: {
+ date_time_output_format: "iso",
+ },
+ },
+ tags: {
+ feature: "metrics-api",
+ type: queryParams.view,
+ kind: "analytic",
+ projectId: auth.scope.projectId,
+ },
+ });
+
+ // Format and return the result
+ return {
+ data: result,
+ // meta: {
+ // page: queryParams.page,
+ // limit: queryParams.limit,
+ // totalItems: result.length,
+ // totalPages: Math.ceil(result.length / queryParams.limit),
+ // },
+ };
+ } catch (error) {
+ logger.error("Error in metrics API", { error, query });
+ throw error;
+ }
+ },
+ }),
+});