Skip to content

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

feat(api): add fields parameter to GetTraceById endpoint (#13015)

Valery Meleshkin19997064c1c8
diff --git a/.env.prod.example b/.env.prod.example
index e249f98ec2..8c43b4a717 100644
--- a/.env.prod.example
+++ b/.env.prod.example
@@ -235,6 +235,9 @@ LANGFUSE_ENABLE_BLOB_STORAGE_FILE_LOG=true
# Comma-separated default field groups for GET /api/public/traces when no fields param is provided
# Valid values: core, io, scores, observations, metrics
# LANGFUSE_API_TRACES_DEFAULT_FIELDS=
+# Comma-separated default field groups for GET /api/public/traces/{traceId} when no fields param is provided
+# Valid values: core, io, scores, observations, metrics
+# LANGFUSE_API_TRACEBYID_DEFAULT_FIELDS=
### START Enterprise Edition Configuration
diff --git a/fern/apis/server/definition/trace.yml b/fern/apis/server/definition/trace.yml
index 05fd48df4f..ec62a17675 100644
--- a/fern/apis/server/definition/trace.yml
+++ b/fern/apis/server/definition/trace.yml
@@ -10,6 +10,12 @@ service:
docs: Get a specific trace
method: GET
path: /traces/{traceId}
+ request:
+ name: GetTraceRequest
+ query-parameters:
+ 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'."
path-parameters:
traceId:
type: string
diff --git a/packages/shared/src/server/repositories/traces.ts b/packages/shared/src/server/repositories/traces.ts
index b72e3e2e81..ecdf90f022 100644
--- a/packages/shared/src/server/repositories/traces.ts
+++ b/packages/shared/src/server/repositories/traces.ts
@@ -550,13 +550,14 @@ export const getTraceById = async ({
: renderingProps.truncated
? `leftUTF8(output, ${env.LANGFUSE_SERVER_SIDE_IO_CHAR_LIMIT})`
: "output";
+ const metadataColumn = excludeInputOutput ? "'{}'" : "metadata";
const query = `
SELECT
id,
name as name,
user_id as user_id,
- metadata as metadata,
+ ${metadataColumn} as metadata,
release as release,
version as version,
project_id,
diff --git a/web/public/generated/api/openapi.yml b/web/public/generated/api/openapi.yml
index 9b1b4fa3e2..9173254736 100644
--- a/web/public/generated/api/openapi.yml
+++ b/web/public/generated/api/openapi.yml
@@ -5639,6 +5639,19 @@ paths:
required: true
schema:
type: string
+ - name: fields
+ in: query
+ 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'.
+ required: false
+ schema:
+ type: string
+ nullable: true
responses:
'200':
description: ''
diff --git a/web/src/__tests__/server/traces-api.servertest.ts b/web/src/__tests__/server/traces-api.servertest.ts
index b366152e3a..f48a5168fc 100644
--- a/web/src/__tests__/server/traces-api.servertest.ts
+++ b/web/src/__tests__/server/traces-api.servertest.ts
@@ -220,6 +220,139 @@ describe("/api/public/traces API Endpoint", () => {
);
});
+ it("should fetch a trace with core-only 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" }),
+ });
+
+ const observation = createObservation({
+ trace_id: traceId,
+ project_id: projectId,
+ name: "test-observation",
+ end_time: new Date().getTime(),
+ start_time: new Date().getTime() - 1000,
+ cost_details: { input: 0.02, output: 0.03, total: 0.05 },
+ });
+
+ 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 trace = await makeZodVerifiedAPICall(
+ GetTraceV1Response,
+ "GET",
+ `/api/public/traces/${traceId}?fields=core`,
+ );
+
+ expect(trace.body.id).toBe(traceId);
+ expect(trace.body.input).toBeNull();
+ expect(trace.body.output).toBeNull();
+ expect(trace.body.metadata).toEqual({});
+ expect(trace.body.observations).toEqual([]);
+ expect(trace.body.scores).toEqual([]);
+ expect(trace.body.totalCost).toBe(-1);
+ expect(trace.body.latency).toBe(-1);
+ });
+
+ it("should fetch a trace with core,scores,metrics fields", async () => {
+ const traceId = randomUUID();
+ const createdTrace = createTrace({
+ id: traceId,
+ name: "trace-with-scores-metrics",
+ project_id: projectId,
+ input: JSON.stringify({ prompt: "test" }),
+ output: JSON.stringify({ response: "test response" }),
+ });
+
+ const observation = createObservation({
+ trace_id: traceId,
+ project_id: projectId,
+ name: "test-observation",
+ end_time: new Date().getTime(),
+ start_time: new Date().getTime() - 1000,
+ cost_details: { input: 0.02, output: 0.03, total: 0.05 },
+ 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 trace = await makeZodVerifiedAPICall(
+ GetTraceV1Response,
+ "GET",
+ `/api/public/traces/${traceId}?fields=core,scores,metrics`,
+ );
+
+ expect(trace.body.id).toBe(traceId);
+ expect(trace.body.input).toBeNull();
+ expect(trace.body.output).toBeNull();
+ expect(trace.body.observations).toEqual([]);
+ expect(trace.body.scores).toHaveLength(1);
+ expect(trace.body.totalCost).toBe(0.05);
+ expect(trace.body.latency).toBeCloseTo(1);
+ });
+
+ it("should return all fields when fields param contains only invalid groups", async () => {
+ const traceId = randomUUID();
+ const createdTrace = createTrace({
+ id: traceId,
+ name: "trace-invalid-fields",
+ project_id: projectId,
+ input: JSON.stringify({ prompt: "test" }),
+ output: JSON.stringify({ response: "test response" }),
+ metadata: { key: "value" },
+ });
+
+ const observation = createObservation({
+ trace_id: traceId,
+ project_id: projectId,
+ name: "test-observation",
+ end_time: new Date().getTime(),
+ start_time: new Date().getTime() - 1000,
+ cost_details: { input: 0.01, output: 0.02, total: 0.03 },
+ });
+
+ await createTracesCh([createdTrace]);
+ await createObservationsCh([observation]);
+
+ const trace = await makeZodVerifiedAPICall(
+ GetTraceV1Response,
+ "GET",
+ `/api/public/traces/${traceId}?fields=invalid_group,also_invalid`,
+ );
+
+ // All invalid fields should fall back to returning all field groups
+ expect(trace.body.id).toBe(traceId);
+ expect(trace.body.input).not.toBeNull();
+ expect(trace.body.output).not.toBeNull();
+ expect(trace.body.observations).toHaveLength(1);
+ expect(trace.body.totalCost).toBeGreaterThanOrEqual(0);
+ expect(trace.body.latency).toBeGreaterThanOrEqual(0);
+ });
+
it("should fetch all traces", async () => {
const timestamp = new Date();
const createdTrace = createTrace({
diff --git a/web/src/env.mjs b/web/src/env.mjs
index 7abae4f861..d0cc51e0d2 100644
--- a/web/src/env.mjs
+++ b/web/src/env.mjs
@@ -399,6 +399,7 @@ export const env = createEnv({
.enum(["true", "false"])
.default("false"),
LANGFUSE_API_TRACES_DEFAULT_FIELDS: z.string().optional(),
+ LANGFUSE_API_TRACEBYID_DEFAULT_FIELDS: z.string().optional(),
// Events table migration
LANGFUSE_ENABLE_EVENTS_TABLE_OBSERVATIONS: z
@@ -781,6 +782,8 @@ export const env = createEnv({
process.env.LANGFUSE_API_TRACES_REJECT_NO_DATE_RANGE,
LANGFUSE_API_TRACES_DEFAULT_FIELDS:
process.env.LANGFUSE_API_TRACES_DEFAULT_FIELDS,
+ LANGFUSE_API_TRACEBYID_DEFAULT_FIELDS:
+ process.env.LANGFUSE_API_TRACEBYID_DEFAULT_FIELDS,
// Events table migration
LANGFUSE_ENABLE_EVENTS_TABLE_OBSERVATIONS:
process.env.LANGFUSE_ENABLE_EVENTS_TABLE_OBSERVATIONS,
diff --git a/web/src/features/public-api/types/traces.ts b/web/src/features/public-api/types/traces.ts
index 43b8969917..c84c1a69df 100644
--- a/web/src/features/public-api/types/traces.ts
+++ b/web/src/features/public-api/types/traces.ts
@@ -89,10 +89,11 @@ export const GetTracesV1Query = z.object({
.nullish()
.transform((v) => {
if (!v) return null;
- return v
+ const parsed = v
.split(",")
.map((f) => f.trim())
.filter((f) => TRACE_FIELD_GROUPS.includes(f as TraceFieldGroup));
+ return parsed.length > 0 ? parsed : null;
})
.pipe(z.array(z.enum(TRACE_FIELD_GROUPS)).nullable()),
useEventsTable: useEventsTableSchema,
@@ -125,6 +126,18 @@ export const PostTracesV1Response = z.object({ id: z.string() });
// GET /api/public/traces/{traceId}
export const GetTraceV1Query = z.object({
traceId: z.string(),
+ fields: z
+ .string()
+ .nullish()
+ .transform((v) => {
+ if (!v) return null;
+ const parsed = v
+ .split(",")
+ .map((f) => f.trim())
+ .filter((f) => TRACE_FIELD_GROUPS.includes(f as TraceFieldGroup));
+ return parsed.length > 0 ? parsed : null;
+ })
+ .pipe(z.array(z.enum(TRACE_FIELD_GROUPS)).nullable()),
});
export const GetTraceV1Response = APIExtendedTrace.extend({
scores: z.array(APIScoreSchemaV1),
diff --git a/web/src/pages/api/public/traces/[traceId].ts b/web/src/pages/api/public/traces/[traceId].ts
index fbd09bd70c..8dd07bf6de 100644
--- a/web/src/pages/api/public/traces/[traceId].ts
+++ b/web/src/pages/api/public/traces/[traceId].ts
@@ -6,7 +6,10 @@ import {
GetTraceV1Response,
DeleteTraceV1Query,
DeleteTraceV1Response,
+ TRACE_FIELD_GROUPS,
+ type TraceFieldGroup,
} from "@/src/features/public-api/types/traces";
+import { env } from "@/src/env.mjs";
import {
filterAndValidateDbTraceScoreList,
LangfuseNotFoundError,
@@ -29,11 +32,31 @@ export default withMiddlewares({
responseSchema: GetTraceV1Response,
fn: async ({ query, auth }) => {
const { traceId } = query;
+
+ let effectiveFields: readonly TraceFieldGroup[] =
+ query.fields ?? TRACE_FIELD_GROUPS;
+ if (!query.fields && env.LANGFUSE_API_TRACEBYID_DEFAULT_FIELDS) {
+ const parsed = env.LANGFUSE_API_TRACEBYID_DEFAULT_FIELDS.split(",")
+ .map((f) => f.trim())
+ .filter((f): f is TraceFieldGroup =>
+ TRACE_FIELD_GROUPS.includes(f as TraceFieldGroup),
+ );
+ if (parsed.length > 0) {
+ effectiveFields = parsed;
+ }
+ }
+ const requestedFields = effectiveFields;
+ const includeIO = requestedFields.includes("io");
+ const includeObservations = requestedFields.includes("observations");
+ const includeScores = requestedFields.includes("scores");
+ const includeMetrics = requestedFields.includes("metrics");
+
const trace = await getTraceById({
traceId,
projectId: auth.scope.projectId,
clickhouseFeatureTag: "tracing-public-api",
preferredClickhouseService: "ReadOnly",
+ excludeInputOutput: !includeIO,
});
if (!trace) {
@@ -43,19 +66,23 @@ export default withMiddlewares({
}
const [observations, scores] = await Promise.all([
- getObservationsForTrace({
- traceId,
- projectId: auth.scope.projectId,
- timestamp: trace?.timestamp,
- includeIO: true,
- preferredClickhouseService: "ReadOnly",
- }),
- getScoresForTraces({
- projectId: auth.scope.projectId,
- traceIds: [traceId],
- timestamp: trace?.timestamp,
- preferredClickhouseService: "ReadOnly",
- }),
+ includeObservations || includeMetrics
+ ? getObservationsForTrace({
+ traceId,
+ projectId: auth.scope.projectId,
+ timestamp: trace?.timestamp,
+ includeIO: includeObservations,
+ preferredClickhouseService: "ReadOnly",
+ })
+ : Promise.resolve([]),
+ includeScores
+ ? getScoresForTraces({
+ projectId: auth.scope.projectId,
+ traceIds: [traceId],
+ timestamp: trace?.timestamp,
+ preferredClickhouseService: "ReadOnly",
+ })
+ : Promise.resolve([]),
]);
const uniqueModels: string[] = Array.from(
@@ -129,16 +156,24 @@ export default withMiddlewares({
return {
...trace,
externalId: null,
- scores: validatedScores,
- latency: latencyMs !== undefined ? latencyMs / 1000 : 0,
- observations: outObservations,
+ metadata: includeIO ? trace.metadata : {},
+ scores: includeScores ? validatedScores : [],
+ latency: includeMetrics
+ ? latencyMs !== undefined
+ ? latencyMs / 1000
+ : 0
+ : -1,
+ observations: includeObservations ? outObservations : [],
htmlPath: `/project/${auth.scope.projectId}/traces/${traceId}`,
- totalCost: outObservations
- .reduce(
- (acc, obs) => acc.add(obs.calculatedTotalCost ?? new Decimal(0)),
- new Decimal(0),
- )
- .toNumber(),
+ totalCost: includeMetrics
+ ? outObservations
+ .reduce(
+ (acc, obs) =>
+ acc.add(obs.calculatedTotalCost ?? new Decimal(0)),
+ new Decimal(0),
+ )
+ .toNumber()
+ : -1,
};
},
}),