🪢 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
perf: filter input/output attributes from metadata attributes key in otel (#9707)
Steffen Schmitz982cc0466340
diff --git a/packages/shared/src/server/otel/OtelIngestionProcessor.ts b/packages/shared/src/server/otel/OtelIngestionProcessor.tsindex a44db0f26b..baab4c5cce 100644--- a/packages/shared/src/server/otel/OtelIngestionProcessor.ts+++ b/packages/shared/src/server/otel/OtelIngestionProcessor.ts@@ -42,7 +42,6 @@ interface CreateTraceEventParams {attributes: Record<string, unknown>;resourceAttributes: Record<string, unknown>;resourceAttributeMetadata: Record<string, unknown>;- spanAttributesInMetadata: Record<string, unknown>;scopeSpan: any;scopeAttributes: Record<string, unknown>;isLangfuseSDKSpans: boolean;@@ -60,7 +59,6 @@ interface CreateObservationEventParams {resourceAttributes: Record<string, unknown>;resourceAttributeMetadata: Record<string, unknown>;spanAttributeMetadata: Record<string, unknown>;- spanAttributesInMetadata: Record<string, unknown>;scopeSpan: any;scopeAttributes: Record<string, unknown>;isLangfuseSDKSpans: boolean;@@ -220,9 +218,17 @@ export class OtelIngestionProcessor {"trace",);+ // Extract input/output (filteredAttributes not needed as metadata.attributes is commented out)+ // Add filteredAttributes in case spanAttributes are included in the metadata block.+ const { input, output } = this.extractInputAndOutput({+ events: span?.events ?? [],+ attributes: spanAttributes,+ instrumentationScopeName: scopeSpan?.scope?.name ?? "",+ });+// Construct metadata object with the specified structureconst metadata = {- // attributes: spanAttributes,+ // attributes: filteredAttributes,resourceAttributes: resourceAttributes,scopeAttributes: scopeAttributes,...spanMetadata,@@ -329,11 +335,8 @@ export class OtelIngestionProcessor {userId: this.extractUserId(spanAttributes),sessionId: this.extractSessionId(spanAttributes),- ...this.extractInputAndOutput({- events: span?.events ?? [],- attributes: spanAttributes,- instrumentationScopeName: scopeSpan?.scope?.name ?? "",- }),+ input,+ output,// Metadatametadata,@@ -630,13 +633,6 @@ export class OtelIngestionProcessor {!parentObservationId ||String(attributes[LangfuseOtelSpanAttributes.AS_ROOT]) === "true";- const spanAttributesInMetadata = Object.fromEntries(- Object.entries(attributes).map(([key, value]) => [- key,- typeof value === "string" ? value : JSON.stringify(value),- ]),- );-const hasTraceUpdates = this.hasTraceUpdates(attributes);// Handle trace creation logic with internal seen traces management@@ -647,7 +643,6 @@ export class OtelIngestionProcessor {attributes,resourceAttributes,resourceAttributeMetadata,- spanAttributesInMetadata,scopeSpan,scopeAttributes,isLangfuseSDKSpans,@@ -671,7 +666,6 @@ export class OtelIngestionProcessor {resourceAttributes,resourceAttributeMetadata,spanAttributeMetadata,- spanAttributesInMetadata,scopeSpan,scopeAttributes,isLangfuseSDKSpans,@@ -690,7 +684,6 @@ export class OtelIngestionProcessor {attributes,resourceAttributes,resourceAttributeMetadata,- spanAttributesInMetadata,scopeSpan,scopeAttributes,isLangfuseSDKSpans,@@ -710,6 +703,14 @@ export class OtelIngestionProcessor {// Create full trace for root spans or spans with trace updatesif (isRootSpan) {+ // Extract input/output and get filtered attributes+ const { input, output, filteredAttributes } = this.extractInputAndOutput({+ events: span?.events ?? [],+ attributes,+ domain: "trace",+ instrumentationScopeName,+ });+trace = {...trace,name:@@ -719,9 +720,7 @@ export class OtelIngestionProcessor {...resourceAttributeMetadata,...this.extractMetadata(attributes, "trace"),...this.extractMetadata(attributes, "observation"),- ...(isLangfuseSDKSpans- ? {}- : { attributes: spanAttributesInMetadata }),+ ...(isLangfuseSDKSpans ? {} : { attributes: filteredAttributes }),resourceAttributes,scope: {...(scopeSpan.scope || {}),@@ -741,12 +740,8 @@ export class OtelIngestionProcessor {public: this.isTracePublic(attributes),tags: this.extractTags(attributes),environment: this.extractEnvironment(attributes, resourceAttributes),- ...this.extractInputAndOutput({- events: span?.events ?? [],- attributes,- domain: "trace",- instrumentationScopeName,- }),+ input,+ output,};}@@ -824,7 +819,6 @@ export class OtelIngestionProcessor {resourceAttributes,resourceAttributeMetadata,spanAttributeMetadata,- spanAttributesInMetadata,scopeSpan,scopeAttributes,isLangfuseSDKSpans,@@ -834,6 +828,13 @@ export class OtelIngestionProcessor {const instrumentationScopeName = scopeSpan?.scope?.name;+ // Extract input/output and get filtered attributes+ const { input, output, filteredAttributes } = this.extractInputAndOutput({+ events: span?.events ?? [],+ attributes,+ instrumentationScopeName,+ });+const observation = {id: this.parseId(span.spanId?.data ?? span.spanId),traceId,@@ -849,7 +850,7 @@ export class OtelIngestionProcessor {metadata: {...resourceAttributeMetadata,...spanAttributeMetadata,- ...(isLangfuseSDKSpans ? {} : { attributes: spanAttributesInMetadata }),+ ...(isLangfuseSDKSpans ? {} : { attributes: filteredAttributes }),resourceAttributes,scope: { ...scopeSpan.scope, attributes: scopeAttributes },},@@ -890,11 +891,8 @@ export class OtelIngestionProcessor {attributes,isLangfuseSDKSpans,) as any,- ...this.extractInputAndOutput({- events: span?.events ?? [],- attributes,- instrumentationScopeName,- }),+ input,+ output,};const mappedObservationType = observationTypeMapper.mapToObservationType(@@ -1076,11 +1074,88 @@ export class OtelIngestionProcessor {attributes: Record<string, unknown>;instrumentationScopeName: string;domain?: "trace" | "observation";- }): { input: any; output: any } {+ }): { input: any; output: any; filteredAttributes: Record<string, unknown> } {const { instrumentationScopeName, events, attributes, domain } = params;let input = null;let output = null;+ // Create a shallow copy of attributes to filter out used keys+ const rawFilteredAttributes = { ...attributes };++ // Pre-delete all potential input/output attribute keys to avoid duplicates+ // This ensures that if multiple frameworks' attributes are present, they're all filtered+ const potentialInputOutputKeys = [+ // Langfuse SDK+ LangfuseOtelSpanAttributes.TRACE_INPUT,+ LangfuseOtelSpanAttributes.TRACE_OUTPUT,+ LangfuseOtelSpanAttributes.OBSERVATION_INPUT,+ LangfuseOtelSpanAttributes.OBSERVATION_OUTPUT,+ // Vercel AI SDK+ "ai.prompt.messages",+ "ai.prompt",+ "ai.toolCall.args",+ "ai.response.text",+ "ai.result.text",+ "ai.toolCall.result",+ "ai.response.object",+ "ai.result.object",+ "ai.response.toolCalls",+ "ai.result.toolCalls",+ // Google Vertex AI+ "gcp.vertex.agent.llm_request",+ "gcp.vertex.agent.llm_response",+ "gcp.vertex.agent.tool_call_args",+ "gcp.vertex.agent.tool_response",+ // Logfire+ "prompt",+ "all_messages_events",+ "events",+ // LiveKit+ "lk.input_text",+ "lk.function_tool.output",+ "lk.response.text",+ // MLFlow+ "mlflow.spanInputs",+ "mlflow.spanOutputs",+ // TraceLoop+ "traceloop.entity.input",+ "traceloop.entity.output",+ // SmolAgents+ "input.value",+ "output.value",+ // Pydantic and Pipecat+ "input",+ "output",+ // OpenTelemetry+ "gen_ai.input.messages",+ "gen_ai.output.messages",+ "gen_ai.tool.call.arguments",+ "gen_ai.tool.call.result",+ ];++ // Delete simple keys+ potentialInputOutputKeys.forEach((key) => {+ delete rawFilteredAttributes[key];+ });++ // Delete gen_ai.prompt.* and gen_ai.completion.* keys+ Object.keys(attributes).forEach((key) => {+ if (+ key.startsWith("gen_ai.prompt") ||+ key.startsWith("gen_ai.completion")+ ) {+ delete rawFilteredAttributes[key];+ }+ });++ // Stringify non-string values in filteredAttributes to maintain backward compatibility+ // This matches the old spanAttributesInMetadata behavior+ const filteredAttributes = Object.fromEntries(+ Object.entries(rawFilteredAttributes).map(([key, value]) => [+ key,+ typeof value === "string" ? value : JSON.stringify(value),+ ]),+ );// Langfuseinput =@@ -1093,7 +1168,7 @@ export class OtelIngestionProcessor {: attributes[LangfuseOtelSpanAttributes.OBSERVATION_OUTPUT];if (input != null || output != null) {- return { input, output };+ return { input, output, filteredAttributes };}// Vercel AI SDK@@ -1124,7 +1199,7 @@ export class OtelIngestionProcessor {? attributes["ai.result.toolCalls"]: undefined;- return { input, output };+ return { input, output, filteredAttributes };}const inputEvents = events.filter(@@ -1179,6 +1254,7 @@ export class OtelIngestionProcessor {processedOutput && processedOutput.length === 1? processedOutput[0]: processedOutput,+ filteredAttributes, // No attribute keys used, events are used instead};}@@ -1215,21 +1291,25 @@ export class OtelIngestionProcessor {attributes: output,instrumentationScopeName,});- return { input: eventInput || input, output: eventOutput || output };+ return {+ input: eventInput || input,+ output: eventOutput || output,+ filteredAttributes, // No attribute keys used, events are used instead+ };}// Google Vertex AI Agent-Developer-Kit (ADK)input = attributes["gcp.vertex.agent.llm_request"];output = attributes["gcp.vertex.agent.llm_response"];if (input || output) {- return { input, output };+ return { input, output, filteredAttributes };}// Logfire uses `prompt` and `all_messages_events` property on spansinput = attributes["prompt"];output = attributes["all_messages_events"];if (input || output) {- return { input, output };+ return { input, output, filteredAttributes };}// LiveKit@@ -1237,7 +1317,7 @@ export class OtelIngestionProcessor {output =attributes["lk.function_tool.output"] || attributes["lk.response.text"];if (input || output) {- return { input, output };+ return { input, output, filteredAttributes };}// Logfire uses single `events` array for GenAI events@@ -1263,6 +1343,7 @@ export class OtelIngestionProcessor {return {input: inputEvents.length > 0 ? inputEvents : null,output: choiceEvent || null,+ filteredAttributes,};}}@@ -1271,35 +1352,35 @@ export class OtelIngestionProcessor {input = attributes["mlflow.spanInputs"];output = attributes["mlflow.spanOutputs"];if (input || output) {- return { input, output };+ return { input, output, filteredAttributes };}// TraceLoop sets traceloop.entity.input and traceloop.entity.outputinput = attributes["traceloop.entity.input"];output = attributes["traceloop.entity.output"];if (input || output) {- return { input, output };+ return { input, output, filteredAttributes };}// SmolAgents sets input.value and output.valueinput = attributes["input.value"];output = attributes["output.value"];if (input || output) {- return { input, output };+ return { input, output, filteredAttributes };}// Pydantic and Pipecat uses input and outputinput = attributes["input"];output = attributes["output"];if (input || output) {- return { input, output };+ return { input, output, filteredAttributes };}// GCP Vertex Agent Tool call input and outputinput = attributes["gcp.vertex.agent.tool_call_args"];output = attributes["gcp.vertex.agent.tool_response"];if (input || output) {- return { input, output };+ return { input, output, filteredAttributes };}// TraceLoop uses attributes property@@ -1321,6 +1402,7 @@ export class OtelIngestionProcessor {return {input: this.convertKeyPathToNestedObject(input, "gen_ai.prompt"),output: this.convertKeyPathToNestedObject(output, "gen_ai.completion"),+ filteredAttributes,};}@@ -1328,17 +1410,17 @@ export class OtelIngestionProcessor {input = attributes["gen_ai.input.messages"];output = attributes["gen_ai.output.messages"];if (input || output) {- return { input, output };+ return { input, output, filteredAttributes };}// OpenTelemetry tools (https://opentelemetry.io/docs/specs/semconv/gen-ai/gen-ai-spans)input = attributes["gen_ai.tool.call.arguments"];output = attributes["gen_ai.tool.call.result"];if (input || output) {- return { input, output };+ return { input, output, filteredAttributes };}- return { input: null, output: null };+ return { input: null, output: null, filteredAttributes };}private extractEnvironment(diff --git a/web/src/__tests__/server/api/otel/otelMapping.servertest.ts b/web/src/__tests__/server/api/otel/otelMapping.servertest.tsindex 9020e41099..16a41cc45f 100644--- a/web/src/__tests__/server/api/otel/otelMapping.servertest.ts+++ b/web/src/__tests__/server/api/otel/otelMapping.servertest.ts@@ -4248,4 +4248,361 @@ describe("OTel Resource Span Mapping", () => {expect(updatedTraceEvent.body.sessionId).toBe("new-session");});});++ describe("Input/Output attribute filtering from metadata", () => {+ it("should filter Langfuse SDK trace input/output attributes from trace metadata", async () => {+ const traceId = "abcdef1234567890abcdef1234567890";+ const rootSpanId = "1234567890abcdef";++ const rootSpan = {+ resource: {+ attributes: [+ {+ key: "service.name",+ value: { stringValue: "test-service" },+ },+ ],+ },+ scopeSpans: [+ {+ scope: {+ name: "test-scope",+ version: "1.0.0",+ },+ spans: [+ {+ traceId: Buffer.from(traceId, "hex"),+ spanId: Buffer.from(rootSpanId, "hex"),+ name: "root-span",+ kind: 1,+ startTimeUnixNano: { low: 0, high: 406528574, unsigned: true },+ endTimeUnixNano: {+ low: 1000000,+ high: 406528574,+ unsigned: true,+ },+ attributes: [+ // Trace-level input/output (should be filtered from trace metadata.attributes)+ {+ key: "langfuse.trace.input",+ value: { stringValue: '{"query": "hello"}' },+ },+ {+ key: "langfuse.trace.output",+ value: { stringValue: '{"response": "hi"}' },+ },+ // Custom attributes (should remain in metadata.attributes)+ {+ key: "custom_trace_attribute",+ value: { stringValue: "should_be_in_metadata" },+ },+ {+ key: "trace_metadata_field",+ value: { stringValue: "preserved_value" },+ },+ ],+ status: {},+ },+ ],+ },+ ],+ };++ const rootEvents = await convertOtelSpanToIngestionEvent(+ rootSpan,+ new Set(),+ );++ const traceEvent = rootEvents.find((e) => e.type === "trace-create");++ // Verify trace input/output are extracted (as JSON strings)+ expect(traceEvent?.body.input).toEqual('{"query": "hello"}');+ expect(traceEvent?.body.output).toEqual('{"response": "hi"}');++ // Verify trace input/output keys are NOT in metadata.attributes+ expect(+ traceEvent?.body.metadata?.attributes?.["langfuse.trace.input"],+ ).toBeUndefined();+ expect(+ traceEvent?.body.metadata?.attributes?.["langfuse.trace.output"],+ ).toBeUndefined();++ // Verify custom trace attributes ARE in metadata.attributes+ expect(+ traceEvent?.body.metadata?.attributes?.custom_trace_attribute,+ ).toBe("should_be_in_metadata");+ expect(traceEvent?.body.metadata?.attributes?.trace_metadata_field).toBe(+ "preserved_value",+ );+ });++ it("should filter Vercel AI SDK input/output attributes from observation metadata", async () => {+ const traceId = "abcdef1234567890abcdef1234567890";+ const rootSpanId = "1234567890abcdef";+ const childSpanId = "abcdef1234567890";++ const vercelAISpan = {+ resource: {+ attributes: [+ {+ key: "service.name",+ value: { stringValue: "test-service" },+ },+ ],+ },+ scopeSpans: [+ {+ scope: {+ name: "ai", // Vercel AI SDK scope name+ version: "4.0.0",+ },+ spans: [+ {+ traceId: Buffer.from(traceId, "hex"),+ spanId: Buffer.from(childSpanId, "hex"),+ parentSpanId: Buffer.from(rootSpanId, "hex"),+ name: "vercel-ai-generation",+ kind: 1,+ startTimeUnixNano: {+ low: 1000000,+ high: 406528574,+ unsigned: true,+ },+ endTimeUnixNano: {+ low: 2000000,+ high: 406528574,+ unsigned: true,+ },+ attributes: [+ // Vercel AI SDK input/output (should be filtered)+ {+ key: "ai.prompt.messages",+ value: {+ stringValue: '[{"role":"user","content":"test"}]',+ },+ },+ {+ key: "ai.response.text",+ value: { stringValue: "AI response text" },+ },+ // Custom attributes (should remain in metadata.attributes)+ {+ key: "custom_observation_attribute",+ value: { stringValue: "should_remain" },+ },+ {+ key: "request_id",+ value: { stringValue: "req-123" },+ },+ ],+ status: {},+ },+ ],+ },+ ],+ };++ const vercelEvents = await convertOtelSpanToIngestionEvent(+ vercelAISpan,+ new Set([traceId]),+ );++ const vercelObservation = vercelEvents.find(+ (e) => e.type === "span-create",+ );++ // Verify Vercel AI SDK input/output are extracted+ expect(vercelObservation?.body.input).toEqual(+ JSON.stringify([{ role: "user", content: "test" }]),+ );+ expect(vercelObservation?.body.output).toBe("AI response text");++ // Verify Vercel AI SDK keys are NOT in metadata.attributes+ expect(+ vercelObservation?.body.metadata?.attributes?.["ai.prompt.messages"],+ ).toBeUndefined();+ expect(+ vercelObservation?.body.metadata?.attributes?.["ai.response.text"],+ ).toBeUndefined();++ // Verify custom observation attributes ARE in metadata.attributes+ expect(+ vercelObservation?.body.metadata?.attributes+ ?.custom_observation_attribute,+ ).toBe("should_remain");+ expect(vercelObservation?.body.metadata?.attributes?.request_id).toBe(+ "req-123",+ );+ });++ it("should filter TraceLoop and MLFlow input/output attributes from observation metadata", async () => {+ const traceId = "abcdef1234567890abcdef1234567890";+ const rootSpanId = "1234567890abcdef";++ const traceLoopSpan = {+ resource: {+ attributes: [+ {+ key: "service.name",+ value: { stringValue: "test-service" },+ },+ ],+ },+ scopeSpans: [+ {+ scope: {+ name: "traceloop-scope",+ version: "1.0.0",+ },+ spans: [+ {+ traceId: Buffer.from(traceId, "hex"),+ spanId: Buffer.from("fedcba0987654321", "hex"),+ parentSpanId: Buffer.from(rootSpanId, "hex"),+ name: "traceloop-span",+ kind: 1,+ startTimeUnixNano: {+ low: 2000000,+ high: 406528574,+ unsigned: true,+ },+ endTimeUnixNano: {+ low: 3000000,+ high: 406528574,+ unsigned: true,+ },+ attributes: [+ // TraceLoop gen_ai attributes (should be filtered)+ {+ key: "gen_ai.prompt.0.content",+ value: { stringValue: "What is AI?" },+ },+ {+ key: "gen_ai.completion.0.content",+ value: { stringValue: "AI is..." },+ },+ // MLFlow attributes (should be filtered)+ {+ key: "mlflow.spanInputs",+ value: { stringValue: '{"question": "test"}' },+ },+ {+ key: "mlflow.spanOutputs",+ value: { stringValue: '{"answer": "response"}' },+ },+ // Custom attributes (should remain)+ {+ key: "span_custom_field",+ value: { stringValue: "custom_value" },+ },+ ],+ status: {},+ },+ ],+ },+ ],+ };++ const traceLoopEvents = await convertOtelSpanToIngestionEvent(+ traceLoopSpan,+ new Set([traceId]),+ );++ const traceLoopObservation = traceLoopEvents.find(+ (e) => e.type === "span-create",+ );++ // Verify TraceLoop input/output are extracted+ expect(traceLoopObservation?.body.input).toBeDefined();+ expect(traceLoopObservation?.body.output).toBeDefined();++ // Verify TraceLoop gen_ai keys are NOT in metadata.attributes+ expect(+ traceLoopObservation?.body.metadata?.attributes?.[+ "gen_ai.prompt.0.content"+ ],+ ).toBeUndefined();+ expect(+ traceLoopObservation?.body.metadata?.attributes?.[+ "gen_ai.completion.0.content"+ ],+ ).toBeUndefined();++ // Verify MLFlow keys are NOT in metadata.attributes+ expect(+ traceLoopObservation?.body.metadata?.attributes?.["mlflow.spanInputs"],+ ).toBeUndefined();+ expect(+ traceLoopObservation?.body.metadata?.attributes?.["mlflow.spanOutputs"],+ ).toBeUndefined();++ // Verify custom span attribute IS in metadata.attributes+ expect(+ traceLoopObservation?.body.metadata?.attributes?.span_custom_field,+ ).toBe("custom_value");+ });++ it("should stringify non-string attributes in observation metadata", async () => {+ const traceId = "abcdef1234567890abcdef1234567890";++ const spanWithNonStringAttrs = {+ resource: {+ attributes: [+ {+ key: "service.name",+ value: { stringValue: "test-service" },+ },+ ],+ },+ scopeSpans: [+ {+ scope: { name: "test-scope", version: "1.0.0" },+ spans: [+ {+ traceId: Buffer.from(traceId, "hex"),+ spanId: Buffer.from("1234567890abcdef", "hex"),+ name: "test-span",+ kind: 1,+ startTimeUnixNano: { low: 1000000, high: 406528574 },+ endTimeUnixNano: { low: 2000000, high: 406528574 },+ attributes: [+ // Add input to trigger extraction logic+ { key: "input", value: { stringValue: "test input" } },+ // Non-string attributes that should be stringified+ { key: "count", value: { intValue: { low: 42, high: 0 } } },+ { key: "temperature", value: { doubleValue: 0.7 } },+ { key: "is_streaming", value: { boolValue: true } },+ // String attribute should remain as-is+ {+ key: "custom_field",+ value: { stringValue: "custom-value" },+ },+ ],+ status: {},+ },+ ],+ },+ ],+ };++ const events = await convertOtelSpanToIngestionEvent(+ spanWithNonStringAttrs,+ new Set([traceId]),+ );++ const observation = events.find((e) => e.type === "span-create");++ // Verify input is extracted+ expect(observation?.body.input).toBe("test input");++ // Verify non-string values are stringified in metadata.attributes+ expect(observation?.body.metadata?.attributes?.count).toBe("42");+ expect(observation?.body.metadata?.attributes?.temperature).toBe("0.7");+ expect(observation?.body.metadata?.attributes?.is_streaming).toBe("true");+ // Verify string values remain strings+ expect(observation?.body.metadata?.attributes?.custom_field).toBe(+ "custom-value",+ );+ });+ });});