Skip to content

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

feat(tracing): map openinference, openai to new observation types (#8664)

Nimar9a38bdcce28c
diff --git a/web/src/__tests__/server/api/otel/otelMapping.servertest.ts b/web/src/__tests__/server/api/otel/otelMapping.servertest.ts
index 293106f94c..e01f9e96ec 100644
--- a/web/src/__tests__/server/api/otel/otelMapping.servertest.ts
+++ b/web/src/__tests__/server/api/otel/otelMapping.servertest.ts
@@ -1097,7 +1097,195 @@ describe("OTel Resource Span Mapping", () => {
expect(langfuseEvents).toHaveLength(2);
});
- it("should interpret openinference LLM calls as a generation", async () => {
+ it.each([
+ ["CHAIN", "chain-create"],
+ ["RETRIEVER", "retriever-create"],
+ ["LLM", "generation-create"],
+ ["EMBEDDING", "embedding-create"],
+ ["AGENT", "agent-create"],
+ ["TOOL", "tool-create"],
+ ["GUARDRAIL", "guardrail-create"],
+ ["EVALUATOR", "evaluator-create"],
+ ["", "span-create"],
+ ["UnknownKind", "span-create"],
+ ])(
+ "should map OpenInference %s span kind to %s event",
+ async (spanKind, expectedEventType) => {
+ const resourceSpan = {
+ scopeSpans: [
+ {
+ spans: [
+ {
+ ...defaultSpanProps,
+ attributes: [
+ {
+ key: "openinference.span.kind",
+ value: { stringValue: spanKind },
+ },
+ ],
+ },
+ ],
+ },
+ ],
+ };
+
+ // When
+ const langfuseEvents = await convertOtelSpanToIngestionEvent(
+ resourceSpan,
+ new Set(),
+ );
+
+ // Then
+ expect(langfuseEvents).toHaveLength(2); // Should create trace + observation
+ expect(
+ langfuseEvents.some((event) => event.type === expectedEventType),
+ ).toBe(true);
+
+ // Verify the observation has the correct type
+ const observationEvent = langfuseEvents.find(
+ (event) =>
+ event.type.endsWith("-create") && event.type !== "trace-create",
+ );
+ expect(observationEvent?.type).toBe(expectedEventType);
+ },
+ );
+
+ it.each([
+ ["chat", "generation-create"],
+ ["completion", "generation-create"],
+ ["generate_content", "generation-create"],
+ ["generate", "generation-create"],
+ ["embeddings", "embedding-create"],
+ ["invoke_agent", "agent-create"],
+ ["create_agent", "agent-create"],
+ ["execute_tool", "tool-create"],
+ ])(
+ "should map OTel GenAI %s operation to %s event",
+ async (operationName, expectedEventType) => {
+ const resourceSpan = {
+ scopeSpans: [
+ {
+ spans: [
+ {
+ ...defaultSpanProps,
+ attributes: [
+ {
+ key: "gen_ai.operation.name",
+ value: { stringValue: operationName },
+ },
+ ],
+ },
+ ],
+ },
+ ],
+ };
+
+ // When
+ const langfuseEvents = await convertOtelSpanToIngestionEvent(
+ resourceSpan,
+ new Set(),
+ );
+
+ // Then
+ expect(langfuseEvents).toHaveLength(2); // Should create trace + observation
+ expect(
+ langfuseEvents.some((event) => event.type === expectedEventType),
+ ).toBe(true);
+
+ // Verify the observation has the correct type
+ const observationEvent = langfuseEvents.find(
+ (event) =>
+ event.type.endsWith("-create") && event.type !== "trace-create",
+ );
+ expect(observationEvent?.type).toBe(expectedEventType);
+ },
+ );
+
+ it("should prioritize OpenInference over OTel GenAI and model detection", async () => {
+ const resourceSpan = {
+ scopeSpans: [
+ {
+ spans: [
+ {
+ ...defaultSpanProps,
+ attributes: [
+ {
+ key: "openinference.span.kind",
+ value: { stringValue: "TOOL" }, // Should be tool-create
+ },
+ {
+ key: "gen_ai.operation.name", // Would normally trigger generation
+ value: { stringValue: "chat" },
+ },
+ {
+ key: "gen_ai.request.model", // Would normally trigger generation
+ value: { stringValue: "gpt-4" },
+ },
+ ],
+ },
+ ],
+ },
+ ],
+ };
+
+ // When
+ const langfuseEvents = await convertOtelSpanToIngestionEvent(
+ resourceSpan,
+ new Set(),
+ );
+
+ // Then
+ expect(langfuseEvents).toHaveLength(2);
+ // Should be tool-create, NOT generation-create (OpenInference takes priority)
+ expect(langfuseEvents.some((event) => event.type === "tool-create")).toBe(
+ true,
+ );
+ expect(
+ langfuseEvents.some((event) => event.type === "generation-create"),
+ ).toBe(false);
+ });
+
+ it("should prioritize OTel GenAI over model-based detection", async () => {
+ const resourceSpan = {
+ scopeSpans: [
+ {
+ spans: [
+ {
+ ...defaultSpanProps,
+ attributes: [
+ {
+ key: "gen_ai.operation.name",
+ value: { stringValue: "embeddings" }, // Should be embedding-create
+ },
+ {
+ key: "gen_ai.request.model", // Would normally trigger generation
+ value: { stringValue: "gpt-4" },
+ },
+ ],
+ },
+ ],
+ },
+ ],
+ };
+
+ // When
+ const langfuseEvents = await convertOtelSpanToIngestionEvent(
+ resourceSpan,
+ new Set(),
+ );
+
+ // Then
+ expect(langfuseEvents).toHaveLength(2);
+ // Should be embedding-create, NOT generation-create (OTel GenAI takes priority over model detection)
+ expect(
+ langfuseEvents.some((event) => event.type === "embedding-create"),
+ ).toBe(true);
+ expect(
+ langfuseEvents.some((event) => event.type === "generation-create"),
+ ).toBe(false);
+ });
+
+ it("should trust Langfuse type over OpenInference or model detection", async () => {
const resourceSpan = {
scopeSpans: [
{
@@ -1105,9 +1293,20 @@ describe("OTel Resource Span Mapping", () => {
{
...defaultSpanProps,
attributes: [
+ // Explicit Langfuse type (should always win)
+ {
+ key: "langfuse.observation.type",
+ value: { stringValue: "span" },
+ },
+ // OpenInference span kind
{
key: "openinference.span.kind",
- value: { stringValue: "LLM" },
+ value: { stringValue: "Agent" },
+ },
+ // Model indicators
+ {
+ key: "gen_ai.request.model",
+ value: { stringValue: "gpt-4" },
},
],
},
@@ -1123,10 +1322,70 @@ describe("OTel Resource Span Mapping", () => {
);
// Then
- // Check that we create a generation
+ expect(langfuseEvents).toHaveLength(2);
+ // Explicit Langfuse type should always win over inferred types
+ expect(langfuseEvents.some((event) => event.type === "span-create")).toBe(
+ true,
+ );
+ expect(
+ langfuseEvents.some((event) => event.type === "agent-create"),
+ ).toBe(false);
expect(
langfuseEvents.some((event) => event.type === "generation-create"),
+ ).toBe(false);
+ });
+
+ it("should trust OpenInference over model detection but keep model attributes", async () => {
+ const resourceSpan = {
+ scopeSpans: [
+ {
+ spans: [
+ {
+ ...defaultSpanProps,
+ attributes: [
+ // OpenInference span kind (should take priority over model detection)
+ {
+ key: "openinference.span.kind",
+ value: { stringValue: "RETRIEVER" },
+ },
+ // Model indicators (would be fallback)
+ {
+ key: "gen_ai.request.model",
+ value: { stringValue: "text-embedding-ada-002" },
+ },
+ {
+ key: "gen_ai.usage.input_tokens",
+ value: { intValue: { low: 50, high: 0, unsigned: false } },
+ },
+ ],
+ },
+ ],
+ },
+ ],
+ };
+
+ // When
+ const langfuseEvents = await convertOtelSpanToIngestionEvent(
+ resourceSpan,
+ new Set(),
+ );
+
+ // Then
+ expect(langfuseEvents).toHaveLength(2);
+ // OpenInference should win over model detection
+ expect(
+ langfuseEvents.some((event) => event.type === "retriever-create"),
).toBe(true);
+ expect(
+ langfuseEvents.some((event) => event.type === "generation-create"),
+ ).toBe(false);
+
+ // Should still extract model and usage info
+ const retrieverEvent = langfuseEvents.find(
+ (event) => event.type === "retriever-create",
+ );
+ expect(retrieverEvent?.body.model).toBe("text-embedding-ada-002");
+ expect(retrieverEvent?.body.usageDetails.input).toBe(50);
});
it("should use logfire.msg as span name", async () => {
@@ -3474,5 +3733,70 @@ describe("OTel Resource Span Mapping", () => {
expect(generationEvents[0].body.name).toBe("test-llm-call");
expect(generationEvents[0].body.model).toBe("gpt-4");
});
+
+ it("should default to span-create when no mapper can handle the attributes", async () => {
+ const otelSpans = [
+ {
+ resource: { attributes: [] },
+ scopeSpans: [
+ {
+ scope: { name: "test-scope" },
+ spans: [
+ {
+ traceId: {
+ data: [
+ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
+ ],
+ },
+ spanId: {
+ data: [1, 2, 3, 4, 5, 6, 7, 8],
+ },
+ name: "unknown-operation",
+ startTimeUnixNano: 1000000000,
+ endTimeUnixNano: 2000000000,
+ attributes: [
+ // No openinference.span.kind, no model indicators, no explicit type
+ {
+ key: "custom.attribute",
+ value: { stringValue: "some-value" },
+ },
+ {
+ key: "service.name",
+ value: { stringValue: "my-service" },
+ },
+ {
+ key: "operation.type",
+ value: { stringValue: "unknown" },
+ },
+ ],
+ status: {},
+ },
+ ],
+ },
+ ],
+ },
+ ];
+
+ const events = await convertOtelSpanToIngestionEvent(
+ otelSpans[0],
+ new Set(),
+ publicKey,
+ );
+
+ // Should create a span-create event (default when no mapping found)
+ const spanEvents = events.filter((e) => e.type === "span-create");
+ expect(spanEvents.length).toBe(1);
+ expect(spanEvents[0].body.name).toBe("unknown-operation");
+
+ // Should not create any generation-create or other typed events
+ const nonSpanEvents = events.filter(
+ (e) => e.type !== "span-create" && e.type !== "trace-create",
+ );
+ expect(nonSpanEvents.length).toBe(0);
+
+ // Should still create a trace
+ const traceEvents = events.filter((e) => e.type === "trace-create");
+ expect(traceEvents.length).toBe(1);
+ });
});
});
diff --git a/web/src/features/otel/server/ObservationTypeMapper.ts b/web/src/features/otel/server/ObservationTypeMapper.ts
new file mode 100644
index 0000000000..407fc157e1
--- /dev/null
+++ b/web/src/features/otel/server/ObservationTypeMapper.ts
@@ -0,0 +1,171 @@
+import { LangfuseOtelSpanAttributes } from "./attributes";
+import { type ObservationType, ObservationTypeDomain } from "@langfuse/shared";
+
+type LangfuseObservationType = keyof typeof ObservationType;
+
+interface ObservationTypeMapper {
+ readonly name: string;
+ readonly priority: number; // Lower numbers = higher priority
+ canMap(attributes: Record<string, unknown>): boolean;
+ mapToObservationType(
+ attributes: Record<string, unknown>,
+ ): LangfuseObservationType | null;
+}
+
+/**
+ * Simple mapper for direct attribute key-value mappings.
+ */
+class SimpleAttributeMapper implements ObservationTypeMapper {
+ constructor(
+ public readonly name: string,
+ public readonly priority: number,
+ private readonly attributeKey: string,
+ private readonly mappings: Record<string, string>,
+ ) {}
+
+ canMap(attributes: Record<string, unknown>): boolean {
+ return (
+ this.attributeKey in attributes && attributes[this.attributeKey] != null
+ );
+ }
+
+ mapToObservationType(
+ attributes: Record<string, unknown>,
+ ): LangfuseObservationType | null {
+ const value = attributes[this.attributeKey] as string;
+ const mappedType = this.mappings[value];
+
+ if (
+ mappedType &&
+ ObservationTypeDomain.safeParse(mappedType.toUpperCase()).success
+ ) {
+ return mappedType as LangfuseObservationType;
+ }
+
+ return null;
+ }
+}
+
+/**
+ * Mapper allowing for conditional logic, multiple attribute checks
+ */
+class CustomAttributeMapper implements ObservationTypeMapper {
+ constructor(
+ public readonly name: string,
+ public readonly priority: number,
+ private readonly canMapFn: (attributes: Record<string, unknown>) => boolean,
+ private readonly mapFn: (
+ attributes: Record<string, unknown>,
+ ) => LangfuseObservationType | null,
+ ) {}
+
+ canMap(attributes: Record<string, unknown>): boolean {
+ return this.canMapFn(attributes);
+ }
+
+ mapToObservationType(
+ attributes: Record<string, unknown>,
+ ): LangfuseObservationType | null {
+ const result = this.mapFn(attributes);
+
+ if (
+ result &&
+ ObservationTypeDomain.safeParse(result.toUpperCase()).success
+ ) {
+ return result;
+ }
+
+ return null;
+ }
+}
+
+/**
+ * Registry to manage observation type mappers with a unified interface to map
+ * span attributes to observation types.
+ *
+ * Mappers are evaluated in priority order (lower number = higher priority).
+ *
+ * **NOTE**: This is the constructor to modify if you want to add new mappings.
+ */
+export class ObservationTypeMapperRegistry {
+ private readonly mappers: ObservationTypeMapper[] = [
+ new SimpleAttributeMapper("OpenInference", 1, "openinference.span.kind", {
+ CHAIN: "CHAIN",
+ RETRIEVER: "RETRIEVER",
+ LLM: "GENERATION",
+ EMBEDDING: "EMBEDDING",
+ AGENT: "AGENT",
+ TOOL: "TOOL",
+ GUARDRAIL: "GUARDRAIL",
+ EVALUATOR: "EVALUATOR",
+ }),
+
+ new SimpleAttributeMapper(
+ "OTel_GenAI_Operation",
+ 2,
+ "gen_ai.operation.name",
+ {
+ chat: "GENERATION",
+ completion: "GENERATION",
+ generate_content: "GENERATION",
+ generate: "GENERATION",
+ embeddings: "EMBEDDING",
+ invoke_agent: "AGENT",
+ create_agent: "AGENT",
+ execute_tool: "TOOL",
+ },
+ ),
+
+ new CustomAttributeMapper(
+ "ModelBased",
+ 3,
+ (attributes) => {
+ const modelKeys = [
+ LangfuseOtelSpanAttributes.OBSERVATION_MODEL,
+ "gen_ai.request.model",
+ "gen_ai.response.model",
+ "llm.model_name",
+ "model",
+ ];
+ return modelKeys.some((key) => attributes[key] != null);
+ },
+ () => "GENERATION",
+ ),
+ ];
+
+ private sortedMappersCache: ObservationTypeMapper[] | null = null;
+
+ private getSortedMappers(): ObservationTypeMapper[] {
+ if (!this.sortedMappersCache) {
+ this.sortedMappersCache = [...this.mappers].sort(
+ (a, b) => a.priority - b.priority,
+ );
+ }
+ return this.sortedMappersCache;
+ }
+
+ /**
+ * Maps span attributes to a Langfuse observation type.
+ * Returns null if no mapper can handle the attributes.
+ */
+ mapToObservationType(
+ attributes: Record<string, unknown>,
+ ): LangfuseObservationType | null {
+ const sortedMappers = this.getSortedMappers();
+
+ for (const mapper of sortedMappers) {
+ if (mapper.canMap(attributes)) {
+ const result = mapper.mapToObservationType(attributes);
+ if (result) {
+ return result;
+ }
+ }
+ }
+
+ return null;
+ }
+
+ getMappersForDebugging(): ReadonlyArray<ObservationTypeMapper> {
+ return [...this.mappers];
+ }
+}
diff --git a/web/src/features/otel/server/OtelIngestionProcessor.ts b/web/src/features/otel/server/OtelIngestionProcessor.ts
index bc04bc68b8..7b3292f36e 100644
--- a/web/src/features/otel/server/OtelIngestionProcessor.ts
+++ b/web/src/features/otel/server/OtelIngestionProcessor.ts
@@ -16,6 +16,7 @@ import {
} from "@langfuse/shared/src/server";
import { LangfuseOtelSpanAttributes } from "./attributes";
+import { ObservationTypeMapperRegistry } from "./ObservationTypeMapper";
// Type definitions for internal processor state
interface TraceState {
@@ -85,6 +86,8 @@ interface ResourceSpan {
}>;
}
+const observationTypeMapper = new ObservationTypeMapperRegistry();
+
/**
* Processor class that encapsulates all logic for converting OpenTelemetry
* resource spans into Langfuse ingestion events.
@@ -638,14 +641,17 @@ export class OtelIngestionProcessor {
}),
};
- const observationType = attributes[
+ let observationType = attributes[
LangfuseOtelSpanAttributes.OBSERVATION_TYPE
] as string;
- const isGeneration =
- observationType === "generation" ||
- Boolean(observation.model) ||
- ("openinference.span.kind" in attributes &&
- attributes["openinference.span.kind"] === "LLM");
+
+ // If no explicit observation type, try mapping from various frameworks
+ if (!observationType) {
+ const mappedType = observationTypeMapper.mapToObservationType(attributes);
+ if (mappedType) {
+ observationType = mappedType.toLowerCase();
+ }
+ }
const isKnownObservationType =
observationType &&
@@ -655,7 +661,6 @@ export class OtelIngestionProcessor {
if (isKnownObservationType) {
return `${observationType.toLowerCase()}-create`;
}
- if (isGeneration) return "generation-create";
return "span-create";
};