Skip to content

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

feat: select fields in get traces api route (#7356)

Steffen Schmitzd39855a2e3a5
diff --git a/fern/apis/server/definition/trace.yml b/fern/apis/server/definition/trace.yml
index e21216136b..192178cf70 100644
--- a/fern/apis/server/definition/trace.yml
+++ b/fern/apis/server/definition/trace.yml
@@ -63,6 +63,9 @@ service:
type: optional<string>
allow-multiple: true
docs: Optional filter for traces where the environment is one of the provided values.
+ fields:
+ type: optional<string>
+ docs: "Comma-separated list of fields to include in the response. Available field groups are 'core' (always included), 'io' (input, output, metadata), 'scores', 'observations', 'metrics'. If not provided, all fields are included. Example: 'core,scores,metrics'"
response: Traces
deleteMultiple:
docs: Delete multiple traces
diff --git a/web/public/generated/api/openapi.yml b/web/public/generated/api/openapi.yml
index 9d142c984a..e2da80c17d 100644
--- a/web/public/generated/api/openapi.yml
+++ b/web/public/generated/api/openapi.yml
@@ -4045,6 +4045,17 @@ paths:
items:
type: string
nullable: true
+ - name: fields
+ in: query
+ description: >-
+ Comma-separated list of fields to include in the response. Available
+ field groups are 'core' (always included), 'io' (input, output,
+ metadata), 'scores', 'observations', 'metrics'. If not provided, all
+ fields are included. Example: 'core,scores,metrics'
+ required: false
+ schema:
+ type: string
+ nullable: true
responses:
'200':
description: ''
diff --git a/web/public/generated/postman/collection.json b/web/public/generated/postman/collection.json
index 8160b02e0a..8141b4af15 100644
--- a/web/public/generated/postman/collection.json
+++ b/web/public/generated/postman/collection.json
@@ -2877,7 +2877,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=",
+ "raw": "{{baseUrl}}/api/public/traces?page=&limit=&userId=&name=&sessionId=&fromTimestamp=&toTimestamp=&orderBy=&tags=&version=&release=&environment=&fields=",
"host": [
"{{baseUrl}}"
],
@@ -2946,6 +2946,11 @@
"key": "environment",
"value": "",
"description": "Optional filter for traces where the environment is one of the provided values."
+ },
+ {
+ "key": "fields",
+ "value": "",
+ "description": "Comma-separated list of fields to include in the response. Available field groups are 'core' (always included), 'io' (input, output, metadata), 'scores', 'observations', 'metrics'. If not provided, all fields are included. Example: 'core,scores,metrics'"
}
],
"variable": []
diff --git a/web/src/__tests__/async/traces-api.servertest.ts b/web/src/__tests__/async/traces-api.servertest.ts
index b7664bbcea..8db758025e 100644
--- a/web/src/__tests__/async/traces-api.servertest.ts
+++ b/web/src/__tests__/async/traces-api.servertest.ts
@@ -601,4 +601,357 @@ describe("/api/public/traces API Endpoint", () => {
expect(trace2).toBeUndefined();
}, 40_000);
}, 60_000);
+
+ describe("Fields Filtering", () => {
+ it("should fetch traces with all fields by default", async () => {
+ const traceId = randomUUID();
+ const createdTrace = createTrace({
+ id: traceId,
+ name: "trace-with-all-fields",
+ user_id: "user-1",
+ project_id: projectId,
+ metadata: { key: "value" },
+ input: JSON.stringify({ prompt: "test" }),
+ output: JSON.stringify({ response: "test response" }),
+ release: "1.0.0",
+ version: "2.0.0",
+ });
+
+ const observation = createObservation({
+ trace_id: traceId,
+ project_id: projectId,
+ name: "test-observation",
+ end_time: new Date().getTime(),
+ start_time: new Date().getTime() - 1000,
+ input: "observation input",
+ output: "observation output",
+ });
+
+ const score = createTraceScore({
+ trace_id: traceId,
+ project_id: projectId,
+ name: "test-score",
+ value: 0.8,
+ });
+
+ await createTracesCh([createdTrace]);
+ await createObservationsCh([observation]);
+ await createScoresCh([score]);
+
+ const traces = await makeZodVerifiedAPICall(
+ GetTracesV1Response,
+ "GET",
+ "/api/public/traces",
+ );
+
+ const trace = traces.body.data.find((t) => t.id === traceId);
+ expect(trace).toBeTruthy();
+ if (!trace) return;
+
+ // All fields should be present by default
+ expect(trace.input).toEqual({ prompt: "test" });
+ expect(trace.output).toEqual({ response: "test response" });
+ expect(trace.metadata).toEqual({ key: "value" });
+ expect(trace.observations).toHaveLength(1);
+ expect(trace.scores).toHaveLength(1);
+ expect(trace.totalCost).toBeDefined();
+ expect(trace.latency).toBeCloseTo(1);
+ });
+
+ it("should fetch traces with only core fields when fields=core", async () => {
+ const traceId = randomUUID();
+ const createdTrace = createTrace({
+ id: traceId,
+ name: "trace-core-only",
+ user_id: "user-1",
+ project_id: projectId,
+ metadata: { key: "value" },
+ input: JSON.stringify({ prompt: "test" }),
+ output: JSON.stringify({ response: "test response" }),
+ release: "1.0.0",
+ version: "2.0.0",
+ });
+
+ const observation = createObservation({
+ trace_id: traceId,
+ project_id: projectId,
+ name: "test-observation",
+ end_time: new Date().getTime(),
+ start_time: new Date().getTime() - 1000,
+ });
+
+ const score = createTraceScore({
+ trace_id: traceId,
+ project_id: projectId,
+ name: "test-score",
+ value: 0.8,
+ });
+
+ await createTracesCh([createdTrace]);
+ await createObservationsCh([observation]);
+ await createScoresCh([score]);
+
+ const traces = await makeZodVerifiedAPICall(
+ GetTracesV1Response,
+ "GET",
+ "/api/public/traces?fields=core",
+ );
+
+ const trace = traces.body.data.find((t) => t.id === traceId);
+ expect(trace).toBeTruthy();
+ if (!trace) return;
+
+ // Core fields should be present
+ expect(trace.id).toBe(traceId);
+ expect(trace.name).toBe("trace-core-only");
+ expect(trace.userId).toBe("user-1");
+ expect(trace.projectId).toBe(projectId);
+ expect(trace.release).toBe("1.0.0");
+ expect(trace.version).toBe("2.0.0");
+
+ // Non-core fields should have default values
+ expect(trace.input).toBeNull();
+ expect(trace.output).toBeNull();
+ expect(trace.metadata).toEqual({});
+ expect(trace.observations).toBeUndefined();
+ expect(trace.scores).toBeUndefined();
+ expect(trace.totalCost).toBeUndefined();
+ expect(trace.latency).toBeUndefined();
+ });
+
+ it("should fetch traces with IO fields when fields=core,io", async () => {
+ const traceId = randomUUID();
+ const createdTrace = createTrace({
+ id: traceId,
+ name: "trace-with-io",
+ user_id: "user-1",
+ project_id: projectId,
+ metadata: { key: "value" },
+ input: JSON.stringify({ prompt: "test" }),
+ output: JSON.stringify({ response: "test response" }),
+ });
+
+ await createTracesCh([createdTrace]);
+
+ const traces = await makeZodVerifiedAPICall(
+ GetTracesV1Response,
+ "GET",
+ "/api/public/traces?fields=core,io",
+ );
+
+ const trace = traces.body.data.find((t) => t.id === traceId);
+ expect(trace).toBeTruthy();
+ if (!trace) return;
+
+ // Core and IO fields should be present
+ expect(trace.id).toBe(traceId);
+ expect(trace.name).toBe("trace-with-io");
+ expect(trace.input).toEqual({ prompt: "test" });
+ expect(trace.output).toEqual({ response: "test response" });
+ expect(trace.metadata).toEqual({ key: "value" });
+
+ // Other fields should have default values
+ expect(trace.observations).toBeUndefined();
+ expect(trace.scores).toBeUndefined();
+ expect(trace.totalCost).toBeUndefined();
+ expect(trace.latency).toBeUndefined();
+ });
+
+ it("should fetch traces with scores when fields=core,scores", async () => {
+ const traceId = randomUUID();
+ const createdTrace = createTrace({
+ id: traceId,
+ name: "trace-with-scores",
+ project_id: projectId,
+ });
+
+ const score = createTraceScore({
+ trace_id: traceId,
+ project_id: projectId,
+ name: "test-score",
+ value: 0.8,
+ });
+
+ await createTracesCh([createdTrace]);
+ await createScoresCh([score]);
+
+ const traces = await makeZodVerifiedAPICall(
+ GetTracesV1Response,
+ "GET",
+ "/api/public/traces?fields=core,scores",
+ );
+
+ const trace = traces.body.data.find((t) => t.id === traceId);
+ expect(trace).toBeTruthy();
+ if (!trace) return;
+
+ // Core fields and scores should be present
+ expect(trace.id).toBe(traceId);
+ expect(trace.scores).toHaveLength(1);
+
+ // Other fields should have default values
+ expect(trace.input).toBeNull();
+ expect(trace.output).toBeNull();
+ expect(trace.metadata).toEqual({});
+ expect(trace.observations).toBeUndefined();
+ expect(trace.totalCost).toBeUndefined();
+ expect(trace.latency).toBeUndefined();
+ });
+
+ it("should fetch traces with observations when fields=core,observations", async () => {
+ const traceId = randomUUID();
+ const createdTrace = createTrace({
+ id: traceId,
+ name: "trace-with-observations",
+ project_id: projectId,
+ });
+
+ const observation = createObservation({
+ trace_id: traceId,
+ project_id: projectId,
+ name: "test-observation",
+ end_time: new Date().getTime(),
+ start_time: new Date().getTime() - 1000,
+ });
+
+ await createTracesCh([createdTrace]);
+ await createObservationsCh([observation]);
+
+ const traces = await makeZodVerifiedAPICall(
+ GetTracesV1Response,
+ "GET",
+ "/api/public/traces?fields=core,observations",
+ );
+
+ const trace = traces.body.data.find((t) => t.id === traceId);
+ expect(trace).toBeTruthy();
+ if (!trace) return;
+
+ // Core fields and observations should be present
+ expect(trace.id).toBe(traceId);
+ expect(trace.observations).toHaveLength(1);
+
+ // Other fields should have default values
+ expect(trace.input).toBeNull();
+ expect(trace.output).toBeNull();
+ expect(trace.metadata).toEqual({});
+ expect(trace.scores).toBeUndefined();
+ expect(trace.totalCost).toBeUndefined();
+ expect(trace.latency).toBeUndefined();
+ });
+
+ it("should fetch traces with metrics when fields=core,metrics", async () => {
+ const traceId = randomUUID();
+ const createdTrace = createTrace({
+ id: traceId,
+ name: "trace-with-metrics",
+ project_id: projectId,
+ });
+
+ const observation = createObservation({
+ trace_id: traceId,
+ project_id: projectId,
+ name: "test-observation",
+ end_time: new Date().getTime(),
+ start_time: new Date().getTime() - 1000,
+ total_cost: 0.05,
+ });
+
+ await createTracesCh([createdTrace]);
+ await createObservationsCh([observation]);
+
+ const traces = await makeZodVerifiedAPICall(
+ GetTracesV1Response,
+ "GET",
+ "/api/public/traces?fields=core,metrics",
+ );
+
+ const trace = traces.body.data.find((t) => t.id === traceId);
+ expect(trace).toBeTruthy();
+ if (!trace) return;
+
+ // Core fields and metrics should be present
+ expect(trace.id).toBe(traceId);
+ expect(trace.totalCost).toBe(0.05);
+ expect(trace.latency).toBeCloseTo(1);
+
+ // Other fields should have default values
+ expect(trace.input).toBeNull();
+ expect(trace.output).toBeNull();
+ expect(trace.metadata).toEqual({});
+ expect(trace.observations).toBeUndefined();
+ expect(trace.scores).toBeUndefined();
+ });
+
+ it("should handle invalid field names gracefully", async () => {
+ const traces = await makeZodVerifiedAPICall(
+ GetTracesV1Response,
+ "GET",
+ "/api/public/traces?fields=core,invalid,scores",
+ );
+
+ // Should still work, just ignoring invalid field names
+ expect(traces.status).toBe(200);
+ expect(traces.body.data).toBeDefined();
+ });
+
+ it("should handle empty fields parameter", async () => {
+ const traceId = randomUUID();
+ const createdTrace = createTrace({
+ id: traceId,
+ name: "trace-with-all-fields",
+ user_id: "user-1",
+ project_id: projectId,
+ metadata: { key: "value" },
+ input: JSON.stringify({ prompt: "test" }),
+ output: JSON.stringify({ response: "test response" }),
+ release: "1.0.0",
+ version: "2.0.0",
+ });
+
+ const observation = createObservation({
+ trace_id: traceId,
+ project_id: projectId,
+ name: "test-observation",
+ end_time: new Date().getTime(),
+ start_time: new Date().getTime() - 1000,
+ input: "observation input",
+ output: "observation output",
+ });
+
+ const score = createTraceScore({
+ trace_id: traceId,
+ project_id: projectId,
+ name: "test-score",
+ value: 0.8,
+ });
+
+ await createTracesCh([createdTrace]);
+ await createObservationsCh([observation]);
+ await createScoresCh([score]);
+
+ const traces = await makeZodVerifiedAPICall(
+ GetTracesV1Response,
+ "GET",
+ "/api/public/traces?fields=",
+ );
+
+ // Should default to all fields when empty
+ expect(traces.status).toBe(200);
+ expect(traces.body.data).toBeDefined();
+
+ const trace = traces.body.data.find((t) => t.id === traceId);
+ expect(trace).toBeTruthy();
+ if (!trace) return;
+
+ // All fields should be present
+ expect(trace.input).toEqual({ prompt: "test" });
+ expect(trace.output).toEqual({ response: "test response" });
+ expect(trace.metadata).toEqual({ key: "value" });
+ expect(trace.observations).toHaveLength(1);
+ expect(trace.scores).toHaveLength(1);
+ expect(trace.totalCost).toBeDefined();
+ expect(trace.latency).toBeDefined();
+ });
+ });
});
diff --git a/web/src/features/public-api/server/traces.ts b/web/src/features/public-api/server/traces.ts
index de46130e5a..eb72ca786c 100644
--- a/web/src/features/public-api/server/traces.ts
+++ b/web/src/features/public-api/server/traces.ts
@@ -10,6 +10,10 @@ import {
} from "@langfuse/shared/src/server";
import { type OrderByState } from "@langfuse/shared";
import { snakeCase } from "lodash";
+import {
+ TRACE_FIELD_GROUPS,
+ type TraceFieldGroup,
+} from "@/src/features/public-api/types/traces";
export type TraceQueryType = {
page: number;
@@ -26,6 +30,7 @@ export type TraceQueryType = {
environment?: string | string[];
fromTimestamp?: string;
toTimestamp?: string;
+ fields?: TraceFieldGroup[];
};
export const generateTracesForPublicApi = async ({
@@ -35,6 +40,12 @@ export const generateTracesForPublicApi = async ({
props: TraceQueryType;
orderBy: OrderByState;
}) => {
+ const requestedFields = props.fields ?? TRACE_FIELD_GROUPS;
+ const includeIO = requestedFields.includes("io");
+ const includeScores = requestedFields.includes("scores");
+ const includeObservations = requestedFields.includes("observations");
+ const includeMetrics = requestedFields.includes("metrics");
+
const filter = convertApiProvidedFilterToClickhouseFilter(
props,
filterParams,
@@ -71,8 +82,12 @@ export const generateTracesForPublicApi = async ({
"ORDER BY t.timestamp desc") +
(shouldUseSkipIndexes ? ", t.event_ts desc" : "");
- const query = `
- WITH observation_stats AS (
+ // Build CTEs conditionally based on requested fields
+ const ctes = [];
+
+ if (includeObservations || includeMetrics) {
+ ctes.push(`
+ observation_stats AS (
SELECT
trace_id,
project_id,
@@ -84,7 +99,12 @@ export const generateTracesForPublicApi = async ({
${timeFilter ? `AND start_time >= {cteTimeFilter: DateTime64(3)} - ${TRACE_TO_OBSERVATIONS_INTERVAL}` : ""}
${environmentFilter.length() > 0 ? `AND ${appliedEnvironmentFilter.query}` : ""}
GROUP BY project_id, trace_id
- ), score_stats AS (
+ )`);
+ }
+
+ if (includeScores) {
+ ctes.push(`
+ score_stats AS (
SELECT
trace_id,
project_id,
@@ -96,19 +116,23 @@ export const generateTracesForPublicApi = async ({
${timeFilter ? `AND timestamp >= {cteTimeFilter: DateTime64(3)}` : ""}
${environmentFilter.length() > 0 ? `AND ${appliedEnvironmentFilter.query}` : ""}
GROUP BY project_id, trace_id
- )
+ )`);
+ }
+
+ const withClause = ctes.length > 0 ? `WITH ${ctes.join(", ")}` : "";
+
+ const query = `
+ ${withClause}
SELECT
+ -- Core fields (always included)
t.id as id,
CONCAT('/project/', t.project_id, '/traces/', t.id) as "htmlPath",
t.project_id as project_id,
t.timestamp as timestamp,
t.name as name,
t.environment as environment,
- t.input as input,
- t.output as output,
t.session_id as session_id,
- t.metadata as metadata,
t.user_id as user_id,
t.release as release,
t.version as version,
@@ -116,14 +140,18 @@ export const generateTracesForPublicApi = async ({
t.public as public,
t.tags as tags,
t.created_at as created_at,
- t.updated_at as updated_at,
- s.score_ids as scores,
- o.observation_ids as observations,
- COALESCE(o.latency_milliseconds / 1000, 0) as latency,
- COALESCE(o.total_cost, 0) as totalCost
+ t.updated_at as updated_at
+ -- IO fields (conditional)
+ ${includeIO ? ", t.input as input, t.output as output, t.metadata as metadata" : ""}
+ -- Scores (conditional)
+ ${includeScores ? ", s.score_ids as scores" : ""}
+ -- Observations (conditional)
+ ${includeObservations ? ", o.observation_ids as observations" : ""}
+ -- Metrics (conditional)
+ ${includeMetrics ? ", COALESCE(o.latency_milliseconds / 1000, 0) as latency, COALESCE(o.total_cost, 0) as totalCost" : ""}
FROM traces t ${shouldUseSkipIndexes ? "" : "FINAL"}
- LEFT JOIN observation_stats o ON t.id = o.trace_id AND t.project_id = o.project_id
- LEFT JOIN score_stats s ON t.id = s.trace_id AND t.project_id = s.project_id
+ ${includeObservations || includeMetrics ? "LEFT JOIN observation_stats o ON t.id = o.trace_id AND t.project_id = o.project_id" : ""}
+ ${includeScores ? "LEFT JOIN score_stats s ON t.id = s.trace_id AND t.project_id = s.project_id" : ""}
WHERE t.project_id = {projectId: String}
${filter.length() > 0 ? `AND ${appliedFilter.query}` : ""}
${chOrderBy}
@@ -133,10 +161,10 @@ export const generateTracesForPublicApi = async ({
const result = await queryClickhouse<
TraceRecordReadType & {
- observations: string[];
- scores: string[];
- totalCost: number;
- latency: number;
+ observations?: string[];
+ scores?: string[];
+ totalCost?: number;
+ latency?: number;
htmlPath: string;
}
>({
@@ -157,14 +185,19 @@ export const generateTracesForPublicApi = async ({
},
});
- return result.map((trace) => ({
- ...convertClickhouseToDomain(trace),
- observations: trace.observations,
- scores: trace.scores,
- totalCost: trace.totalCost,
- latency: trace.latency,
- htmlPath: trace.htmlPath,
- }));
+ return result.map((trace) => {
+ return {
+ ...convertClickhouseToDomain(trace),
+ // Conditionally include additional fields based on request
+ ...(includeObservations && { observations: trace.observations ?? null }),
+ ...(includeScores && { scores: trace.scores ?? null }),
+ ...(includeMetrics && {
+ totalCost: trace.totalCost ?? null,
+ latency: trace.latency ?? null,
+ }),
+ htmlPath: trace.htmlPath,
+ };
+ });
};
export const getTracesCountForPublicApi = async ({
diff --git a/web/src/features/public-api/types/traces.ts b/web/src/features/public-api/types/traces.ts
index b611c8cfd5..ddbb913ab2 100644
--- a/web/src/features/public-api/types/traces.ts
+++ b/web/src/features/public-api/types/traces.ts
@@ -8,6 +8,19 @@ import {
import { stringDateTime, TraceBody } from "@langfuse/shared/src/server";
import { z } from "zod/v4";
+/**
+ * Field groups for selective field fetching
+ */
+export const TRACE_FIELD_GROUPS = [
+ "core",
+ "io",
+ "scores",
+ "observations",
+ "metrics",
+] as const;
+
+export type TraceFieldGroup = (typeof TRACE_FIELD_GROUPS)[number];
+
/**
* Objects
*/
@@ -36,10 +49,10 @@ export const APITrace = z
.strict();
const APIExtendedTrace = APITrace.extend({
- observations: z.array(z.string()),
- scores: z.array(z.string()),
- totalCost: z.number(),
- latency: z.number(),
+ observations: z.array(z.string()).nullish(),
+ scores: z.array(z.string()).nullish(),
+ totalCost: z.number().nullish(),
+ latency: z.number().nullish(),
htmlPath: z.string(),
}).strict();
@@ -68,6 +81,17 @@ export const GetTracesV1Query = z.object({
return { column, order: order?.toUpperCase() };
})
.pipe(orderBy.nullable()),
+ fields: z
+ .string()
+ .nullish()
+ .transform((v) => {
+ if (!v) return null;
+ return v
+ .split(",")
+ .map((f) => f.trim())
+ .filter((f) => TRACE_FIELD_GROUPS.includes(f as TraceFieldGroup));
+ })
+ .pipe(z.array(z.enum(TRACE_FIELD_GROUPS)).nullable()),
});
export const GetTracesV1Response = z
.object({
diff --git a/web/src/pages/api/public/traces/index.ts b/web/src/pages/api/public/traces/index.ts
index b0c28c284f..2544f3f6b9 100644
--- a/web/src/pages/api/public/traces/index.ts
+++ b/web/src/pages/api/public/traces/index.ts
@@ -76,6 +76,7 @@ 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([