🪢 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: Enable advanced filtering in public API traces endpoint (LFE-3810) (#9492)
Valery Meleshkindee644d8cb7d
diff --git a/fern/apis/server/definition/trace.yml b/fern/apis/server/definition/trace.ymlindex 50f36eb7a3..8d69b44c01 100644--- a/fern/apis/server/definition/trace.yml+++ b/fern/apis/server/definition/trace.yml@@ -66,6 +66,32 @@ service:fields:type: optional<string>docs: "Comma-separated list of fields to include in the response. Available field groups: 'core' (always included), 'io' (input, output, metadata), 'scores', 'observations', 'metrics'. If not specified, all fields are returned. Example: 'core,scores,metrics'. Note: Excluded 'observations' or 'scores' fields return empty arrays; excluded 'metrics' returns -1 for 'totalCost' and 'latency'."+ filter:+ type: optional<string>+ docs: |+ JSON string containing an array of filter conditions. When provided, this takes precedence over legacy filter parameters (userId, name, sessionId, tags, version, release, environment, fromTimestamp, toTimestamp).+ Each filter condition has the following structure:+ ```json+ [+ {+ "type": string, // Required. One of: "datetime", "string", "number", "stringOptions", "categoryOptions", "arrayOptions", "stringObject", "numberObject", "boolean", "null"+ "column": string, // Required. Column to filter on+ "operator": string, // Required. Operator based on type:+ // - datetime: ">", "<", ">=", "<="+ // - string: "=", "contains", "does not contain", "starts with", "ends with"+ // - stringOptions: "any of", "none of"+ // - categoryOptions: "any of", "none of"+ // - arrayOptions: "any of", "none of", "all of"+ // - number: "=", ">", "<", ">=", "<="+ // - stringObject: "=", "contains", "does not contain", "starts with", "ends with"+ // - numberObject: "=", ">", "<", ">=", "<="+ // - boolean: "=", "<>"+ // - null: "is null", "is not null"+ "value": any, // Required (except for null type). Value to compare against. Type depends on filter type+ "key": string // Required only for stringObject, numberObject, and categoryOptions types when filtering on nested fields like metadata+ }+ ]+ ```response: TracesdeleteMultiple:docs: Delete multiple tracesdiff --git a/packages/shared/src/server/index.ts b/packages/shared/src/server/index.tsindex 321e6730e9..06039028e6 100644--- a/packages/shared/src/server/index.ts+++ b/packages/shared/src/server/index.ts@@ -68,6 +68,7 @@ export * from "./logger";export * from "./headerPropagation";export * from "./queries";export * from "./repositories";+export * from "./repositories/traces";export * from "./utils/rendering";export * from "./redis/evalExecutionQueue";export * from "./services/sessions-ui-table-service";diff --git a/packages/shared/src/server/repositories/traces.ts b/packages/shared/src/server/repositories/traces.tsindex 3f4baf1b1f..ee30dd5ac8 100644--- a/packages/shared/src/server/repositories/traces.ts+++ b/packages/shared/src/server/repositories/traces.ts@@ -697,7 +697,7 @@ export const getTraceById = async ({},existingExecution: (input) => {const query = `- SELECT+ SELECTid,name as name,user_id as user_id,diff --git a/web/public/generated/api/openapi.yml b/web/public/generated/api/openapi.ymlindex d0300f759f..a996257215 100644--- a/web/public/generated/api/openapi.yml+++ b/web/public/generated/api/openapi.yml@@ -4621,6 +4621,43 @@ paths:schema:type: stringnullable: true+ - name: filter+ in: query+ description: >-+ JSON string containing an array of filter conditions. When provided,+ this takes precedence over legacy filter parameters (userId, name,+ sessionId, tags, version, release, environment, fromTimestamp,+ toTimestamp).++ Each filter condition has the following structure:++ ```json++ [+ {+ "type": string, // Required. One of: "datetime", "string", "number", "stringOptions", "categoryOptions", "arrayOptions", "stringObject", "numberObject", "boolean", "null"+ "column": string, // Required. Column to filter on+ "operator": string, // Required. Operator based on type:+ // - datetime: ">", "<", ">=", "<="+ // - string: "=", "contains", "does not contain", "starts with", "ends with"+ // - stringOptions: "any of", "none of"+ // - categoryOptions: "any of", "none of"+ // - arrayOptions: "any of", "none of", "all of"+ // - number: "=", ">", "<", ">=", "<="+ // - stringObject: "=", "contains", "does not contain", "starts with", "ends with"+ // - numberObject: "=", ">", "<", ">=", "<="+ // - boolean: "=", "<>"+ // - null: "is null", "is not null"+ "value": any, // Required (except for null type). Value to compare against. Type depends on filter type+ "key": string // Required only for stringObject, numberObject, and categoryOptions types when filtering on nested fields like metadata+ }+ ]++ ```+ required: false+ schema:+ type: string+ nullable: trueresponses:'200':description: ''diff --git a/web/public/generated/postman/collection.json b/web/public/generated/postman/collection.jsonindex 1540725f4f..2584b67d33 100644--- a/web/public/generated/postman/collection.json+++ b/web/public/generated/postman/collection.json@@ -3288,7 +3288,7 @@"request": {"description": "Get list of traces","url": {- "raw": "{{baseUrl}}/api/public/traces?page=&limit=&userId=&name=&sessionId=&fromTimestamp=&toTimestamp=&orderBy=&tags=&version=&release=&environment=&fields=",+ "raw": "{{baseUrl}}/api/public/traces?page=&limit=&userId=&name=&sessionId=&fromTimestamp=&toTimestamp=&orderBy=&tags=&version=&release=&environment=&fields=&filter=","host": ["{{baseUrl}}"],@@ -3362,6 +3362,11 @@"key": "fields","value": "","description": "Comma-separated list of fields to include in the response. Available field groups: 'core' (always included), 'io' (input, output, metadata), 'scores', 'observations', 'metrics'. If not specified, all fields are returned. Example: 'core,scores,metrics'. Note: Excluded 'observations' or 'scores' fields return empty arrays; excluded 'metrics' returns -1 for 'totalCost' and 'latency'."+ },+ {+ "key": "filter",+ "value": "",+ "description": "JSON string containing an array of filter conditions. When provided, this takes precedence over legacy filter parameters (userId, name, sessionId, tags, version, release, environment, fromTimestamp, toTimestamp).\nEach filter condition has the following structure:\n```json\n[\n {\n \"type\": string, // Required. One of: \"datetime\", \"string\", \"number\", \"stringOptions\", \"categoryOptions\", \"arrayOptions\", \"stringObject\", \"numberObject\", \"boolean\", \"null\"\n \"column\": string, // Required. Column to filter on\n \"operator\": string, // Required. Operator based on type:\n // - datetime: \">\", \"<\", \">=\", \"<=\"\n // - string: \"=\", \"contains\", \"does not contain\", \"starts with\", \"ends with\"\n // - stringOptions: \"any of\", \"none of\"\n // - categoryOptions: \"any of\", \"none of\"\n // - arrayOptions: \"any of\", \"none of\", \"all of\"\n // - number: \"=\", \">\", \"<\", \">=\", \"<=\"\n // - stringObject: \"=\", \"contains\", \"does not contain\", \"starts with\", \"ends with\"\n // - numberObject: \"=\", \">\", \"<\", \">=\", \"<=\"\n // - boolean: \"=\", \"<>\"\n // - null: \"is null\", \"is not null\"\n \"value\": any, // Required (except for null type). Value to compare against. Type depends on filter type\n \"key\": string // Required only for stringObject, numberObject, and categoryOptions types when filtering on nested fields like metadata\n }\n]\n```"}],"variable": []diff --git a/web/src/__tests__/async/traces-api.servertest.ts b/web/src/__tests__/async/traces-api.servertest.tsindex 51a1113ce5..ad092e7892 100644--- a/web/src/__tests__/async/traces-api.servertest.ts+++ b/web/src/__tests__/async/traces-api.servertest.ts@@ -954,4 +954,348 @@ describe("/api/public/traces API Endpoint", () => {expect(trace.latency).toBeDefined();});});++ describe("Advanced Filtering", () => {+ const testTraceId = randomUUID();+ const testTraceId2 = randomUUID();++ beforeAll(async () => {+ // Create test traces with different metadata for filtering+ const trace1 = createTrace({+ id: testTraceId,+ name: "filter-test-trace-1",+ user_id: "filter-user-1",+ project_id: projectId,+ metadata: {+ environment: "production",+ model: "gpt-4",+ priority: "high",+ },+ tags: ["important", "customer-facing"],+ environment: "production",+ release: "v1.0.0",+ version: "1.0.0",+ timestamp: new Date("2024-01-01T00:00:00Z").getTime(),+ });++ const trace2 = createTrace({+ id: testTraceId2,+ name: "filter-test-trace-2",+ user_id: "filter-user-2",+ project_id: projectId,+ metadata: {+ environment: "staging",+ model: "gpt-3.5-turbo",+ priority: "low",+ },+ tags: ["test", "internal"],+ environment: "staging",+ release: "v0.9.0",+ version: "0.9.0",+ timestamp: new Date("2024-01-02T00:00:00Z").getTime(),+ });++ await createTracesCh([trace1, trace2]);++ // Simple wait to ensure data is available+ await new Promise((resolve) => setTimeout(resolve, 100));+ }, 10000);++ it("should support basic metadata filtering", async () => {+ const filterParam = JSON.stringify([+ {+ type: "stringObject",+ column: "metadata",+ key: "environment",+ operator: "=",+ value: "production",+ },+ ]);++ const traces = await makeZodVerifiedAPICall(+ GetTracesV1Response,+ "GET",+ `/api/public/traces?filter=${encodeURIComponent(filterParam)}`,+ );++ expect(traces.status).toBe(200);+ const matchingTrace = traces.body.data.find((t) => t.id === testTraceId);+ const nonMatchingTrace = traces.body.data.find(+ (t) => t.id === testTraceId2,+ );++ expect(matchingTrace).toBeTruthy();+ expect(nonMatchingTrace).toBeFalsy();+ });++ it("should support multiple metadata filters with AND logic", async () => {+ const filterParam = JSON.stringify([+ {+ type: "stringObject",+ column: "metadata",+ key: "environment",+ operator: "=",+ value: "production",+ },+ {+ type: "stringObject",+ column: "metadata",+ key: "model",+ operator: "contains",+ value: "gpt-4",+ },+ ]);++ const traces = await makeZodVerifiedAPICall(+ GetTracesV1Response,+ "GET",+ `/api/public/traces?filter=${encodeURIComponent(filterParam)}`,+ );++ expect(traces.status).toBe(200);+ const matchingTrace = traces.body.data.find((t) => t.id === testTraceId);+ const nonMatchingTrace = traces.body.data.find(+ (t) => t.id === testTraceId2,+ );++ expect(matchingTrace).toBeTruthy();+ expect(nonMatchingTrace).toBeFalsy();+ });++ it("should support array tag filtering", async () => {+ const filterParam = JSON.stringify([+ {+ type: "arrayOptions",+ column: "tags",+ operator: "any of",+ value: ["important", "customer-facing"],+ },+ ]);++ const traces = await makeZodVerifiedAPICall(+ GetTracesV1Response,+ "GET",+ `/api/public/traces?filter=${encodeURIComponent(filterParam)}`,+ );++ expect(traces.status).toBe(200);+ const matchingTrace = traces.body.data.find((t) => t.id === testTraceId);++ expect(matchingTrace).toBeTruthy();+ if (matchingTrace) {+ expect(matchingTrace.tags).toContain("important");+ }+ });++ it("should support backward compatibility with simple parameters", async () => {+ // Test multiple simple parameters+ const traces = await makeZodVerifiedAPICall(+ GetTracesV1Response,+ "GET",+ `/api/public/traces?userId=filter-user-1&environment=production`,+ );++ expect(traces.status).toBe(200);+ const matchingTrace = traces.body.data.find((t) => t.id === testTraceId);+ const nonMatchingTrace = traces.body.data.find(+ (t) => t.id === testTraceId2,+ );++ expect(matchingTrace).toBeTruthy();+ expect(nonMatchingTrace).toBeFalsy();+ });++ it("should give precedence to advanced filter over simple parameters", async () => {+ // simple param would match trace2, but filter should match trace1+ const filterParam = JSON.stringify([+ {+ type: "string",+ column: "userId",+ operator: "=",+ value: "filter-user-1",+ },+ ]);++ const traces = await makeZodVerifiedAPICall(+ GetTracesV1Response,+ "GET",+ `/api/public/traces?userId=filter-user-2&filter=${encodeURIComponent(filterParam)}`,+ );++ expect(traces.status).toBe(200);+ const matchingTrace = traces.body.data.find((t) => t.id === testTraceId);+ const nonMatchingTrace = traces.body.data.find(+ (t) => t.id === testTraceId2,+ );++ // Should match trace1 (filter takes precedence) not trace2 (simple param)+ expect(matchingTrace).toBeTruthy();+ expect(nonMatchingTrace).toBeFalsy();+ });++ it("should merge non-conflicting simple and advanced filters", async () => {+ // simple environment + advanced metadata filter+ const filterParam = JSON.stringify([+ {+ type: "stringObject",+ column: "metadata",+ key: "model",+ operator: "contains",+ value: "gpt-4",+ },+ ]);++ const traces = await makeZodVerifiedAPICall(+ GetTracesV1Response,+ "GET",+ `/api/public/traces?userId=filter-user-1&filter=${encodeURIComponent(filterParam)}`,+ );++ expect(traces.status).toBe(200);+ const matchingTrace = traces.body.data.find((t) => t.id === testTraceId);+ const nonMatchingTrace = traces.body.data.find(+ (t) => t.id === testTraceId2,+ );++ expect(matchingTrace).toBeTruthy();+ expect(nonMatchingTrace).toBeFalsy();+ });++ it("should return validation error for malformed filter JSON", async () => {+ const malformedFilter = "invalid-json";++ const traces = await makeZodVerifiedAPICallSilent(+ GetTracesV1Response,+ "GET",+ `/api/public/traces?filter=${encodeURIComponent(malformedFilter)}`,+ );++ expect(traces.status).toBe(400);+ });++ it("should return validation error for invalid filter schema", async () => {+ const invalidFilterParam = JSON.stringify([+ {+ type: "invalid-type", // Invalid filter type+ column: "metadata",+ operator: "=",+ value: "test",+ },+ ]);++ const traces = await makeZodVerifiedAPICallSilent(+ GetTracesV1Response,+ "GET",+ `/api/public/traces?filter=${encodeURIComponent(invalidFilterParam)}`,+ );++ expect(traces.status).toBe(400);+ });++ it("should return validation error for empty string as filter", async () => {+ const traces = await makeZodVerifiedAPICallSilent(+ GetTracesV1Response,+ "GET",+ `/api/public/traces?filter=`,+ );++ expect(traces.status).toBe(200); // Empty string should be treated as undefined+ });++ it("should return validation error for invalid FilterState structure", async () => {+ const invalidStructure = JSON.stringify([+ {+ // Missing required fields for a valid FilterState condition+ column: "userId",+ value: "test",+ // Missing type and operator+ },+ ]);++ const traces = await makeZodVerifiedAPICallSilent(+ GetTracesV1Response,+ "GET",+ `/api/public/traces?filter=${encodeURIComponent(invalidStructure)}`,+ );++ expect(traces.status).toBe(400);+ });++ it("should return validation error for FilterState with invalid operator", async () => {+ const invalidOperator = JSON.stringify([+ {+ type: "string",+ column: "userId",+ operator: "invalid-operator", // Invalid operator+ value: "test",+ },+ ]);++ const traces = await makeZodVerifiedAPICallSilent(+ GetTracesV1Response,+ "GET",+ `/api/public/traces?filter=${encodeURIComponent(invalidOperator)}`,+ );++ expect(traces.status).toBe(400);+ });++ it("should support advanced timestamp filtering with multiple operators", async () => {+ // Test range filter (>= AND <) - should match only trace1+ const filterRange = JSON.stringify([+ {+ type: "datetime",+ column: "timestamp",+ operator: ">=",+ value: "2024-01-01T00:00:00Z",+ },+ {+ type: "datetime",+ column: "timestamp",+ operator: "<",+ value: "2024-01-01T24:00:00Z",+ },+ ]);++ const tracesRange = await makeZodVerifiedAPICall(+ GetTracesV1Response,+ "GET",+ `/api/public/traces?filter=${encodeURIComponent(filterRange)}`,+ );++ expect(tracesRange.status).toBe(200);+ const matchingRange = tracesRange.body.data.find(+ (t) => t.id === testTraceId,+ );+ const nonMatchingRange = tracesRange.body.data.find(+ (t) => t.id === testTraceId2,+ );+ expect(matchingRange).toBeTruthy();+ expect(nonMatchingRange).toBeFalsy();+ });++ it("should give precedence to advanced timestamp filter over simple fromTimestamp/toTimestamp parameters", async () => {+ // simple params would match none of the traces (2023 dates)+ // But advanced filter should match trace2 (timestamp >= 2024-01-01T12:00:00Z)+ const filterParam = JSON.stringify([+ {+ type: "datetime",+ column: "timestamp",+ operator: ">=",+ value: "2024-01-01T12:00:00Z",+ },+ ]);++ const traces = await makeZodVerifiedAPICall(+ GetTracesV1Response,+ "GET",+ `/api/public/traces?orderBy=timestamp.asc&fromTimestamp=2023-01-01T00:00:00Z&toTimestamp=2023-01-02T00:00:00Z&filter=${encodeURIComponent(filterParam)}`,+ );++ expect(traces.status).toBe(200);+ const matchingTrace = traces.body.data.find((t) => t.id === testTraceId2);+ // Should match trace2 (advanced filter wins)+ expect(matchingTrace).toBeTruthy();+ });+ });});diff --git a/web/src/features/public-api/server/traces.ts b/web/src/features/public-api/server/traces.tsindex f6f6e5949b..474ee37808 100644--- a/web/src/features/public-api/server/traces.ts+++ b/web/src/features/public-api/server/traces.ts@@ -10,6 +10,9 @@ import {type TraceRecordReadType,getTimeframesTracesAMT,measureAndReturn,+ FilterList,+ tracesTableUiColumnDefinitions,+ createFilterFromFilterState,} from "@langfuse/shared/src/server";import { type OrderByState } from "@langfuse/shared";import { snakeCase } from "lodash";@@ -18,6 +21,8 @@ import {type TraceFieldGroup,} from "@/src/features/public-api/types/traces";+import type { FilterState } from "@langfuse/shared";+export type TraceQueryType = {page: number;limit: number;@@ -36,11 +41,42 @@ export type TraceQueryType = {fields?: TraceFieldGroup[];};+function deriveFilters(+ props: TraceQueryType,+ advancedFilters?: FilterState,+): FilterList {+ const filterList = new FilterList(+ createFilterFromFilterState(+ advancedFilters ?? [],+ tracesTableUiColumnDefinitions,+ ),+ );++ let simpleFilters = convertApiProvidedFilterToClickhouseFilter(+ props,+ filterParams,+ );++ // Advanced filter takes precedence. Remove all simple filters that are also in advanced filter+ const advancedFilterColumns = new Set();+ filterList.forEach((f) => advancedFilterColumns.add(f.field));+ simpleFilters+ .filter((sf) => {+ return !advancedFilterColumns.has(sf.field);+ })+ .forEach((f) => filterList.push(f));++ // Return merged filters+ return filterList;+}+export const generateTracesForPublicApi = async ({props,+ advancedFilters,orderBy,}: {props: TraceQueryType;+ advancedFilters?: FilterState;orderBy: OrderByState;}) => {const requestedFields = props.fields ?? TRACE_FIELD_GROUPS;@@ -49,10 +85,7 @@ export const generateTracesForPublicApi = async ({const includeObservations = requestedFields.includes("observations");const includeMetrics = requestedFields.includes("metrics");- const filter = convertApiProvidedFilterToClickhouseFilter(- props,- filterParams,- );+ let filter = deriveFilters(props, advancedFilters);const appliedFilter = filter.apply();const timeFilter = filter.find(@@ -161,7 +194,7 @@ export const generateTracesForPublicApi = async ({const query = `${withClause}-+SELECT-- Core fields (always included)t.id as id,@@ -222,7 +255,7 @@ export const generateTracesForPublicApi = async ({const query = `${withClause}-+SELECT-- Core fields (always included)t.id as id,@@ -294,13 +327,12 @@ export const generateTracesForPublicApi = async ({export const getTracesCountForPublicApi = async ({props,+ advancedFilters,}: {props: TraceQueryType;+ advancedFilters?: FilterState;}) => {- const filter = convertApiProvidedFilterToClickhouseFilter(- props,- filterParams,- );+ let filter = deriveFilters(props, advancedFilters);const appliedFilter = filter.apply();const query = `diff --git a/web/src/features/public-api/types/traces.ts b/web/src/features/public-api/types/traces.tsindex ddbb913ab2..2cd1d3b699 100644--- a/web/src/features/public-api/types/traces.ts+++ b/web/src/features/public-api/types/traces.ts@@ -4,6 +4,8 @@ import {paginationMetaResponseZod,orderBy,publicApiPaginationZod,+ singleFilter,+ InvalidRequestError,} from "@langfuse/shared";import { stringDateTime, TraceBody } from "@langfuse/shared/src/server";import { z } from "zod/v4";@@ -92,6 +94,20 @@ export const GetTracesV1Query = z.object({.filter((f) => TRACE_FIELD_GROUPS.includes(f as TraceFieldGroup));}).pipe(z.array(z.enum(TRACE_FIELD_GROUPS)).nullable()),+ filter: z+ .string()+ .optional()+ .transform((str) => {+ if (!str) return undefined;+ try {+ const parsed = JSON.parse(str);+ return parsed;+ } catch (e) {+ if (e instanceof InvalidRequestError) throw e;+ throw new InvalidRequestError("Invalid JSON in filter parameter");+ }+ })+ .pipe(z.array(singleFilter).optional()),});export const GetTracesV1Response = z.object({diff --git a/web/src/pages/api/public/traces/index.ts b/web/src/pages/api/public/traces/index.tsindex e74e659874..59d69b5bfd 100644--- a/web/src/pages/api/public/traces/index.ts+++ b/web/src/pages/api/public/traces/index.ts@@ -64,6 +64,7 @@ export default withMiddlewares({projectId: auth.scope.projectId,page: query.page ?? undefined,limit: query.limit ?? undefined,+ fields: query.fields ?? undefined,userId: query.userId ?? undefined,name: query.name ?? undefined,tags: query.tags ?? undefined,@@ -73,16 +74,17 @@ export default withMiddlewares({release: query.release ?? undefined,fromTimestamp: query.fromTimestamp ?? undefined,toTimestamp: query.toTimestamp ?? undefined,- fields: query.fields ?? undefined,};const [items, count] = await Promise.all([generateTracesForPublicApi({props: filterProps,+ advancedFilters: query.filter,orderBy: query.orderBy ?? null,}),getTracesCountForPublicApi({props: filterProps,+ advancedFilters: query.filter,}),]);