🪢 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
fix(otel): correctly map obs types for AI sdk for non-generation like… (#10333)
Nimara1706bdbc0a3
diff --git a/packages/shared/src/server/otel/ObservationTypeMapper.ts b/packages/shared/src/server/otel/ObservationTypeMapper.tsindex f246dd0c77..2cdcac77eb 100644--- a/packages/shared/src/server/otel/ObservationTypeMapper.ts+++ b/packages/shared/src/server/otel/ObservationTypeMapper.ts@@ -117,6 +117,31 @@ function hasMeaningfulValue(value: unknown): boolean {return true;}+// for Vercel AI SDK checks attributes operation.name with startsWith and ai.operationId with equals+function matchesVercelAiSdkOperation(+ attributes: Record<string, unknown>,+ prefixes: string[],+): boolean {+ const operationName = attributes["operation.name"];+ const operationId = attributes["ai.operationId"];++ if (hasMeaningfulValue(operationName)) {+ const opNameStr = operationName as string;+ if (prefixes.some((prefix) => opNameStr.startsWith(prefix))) {+ return true;+ }+ }++ if (hasMeaningfulValue(operationId)) {+ const opIdStr = operationId as string;+ if (prefixes.includes(opIdStr)) {+ return true;+ }+ }++ return false;+}+/*** Registry to manage observation type mappers with a unified interface to map* span attributes to observation types.@@ -226,9 +251,13 @@ export class ObservationTypeMapperRegistry {},),+ // Priority 4: Vercel AI SDK generation/embedding operations (require model information)new CustomAttributeMapper(- "Vercel_AI_SDK_Operation",+ // NAME+ "Vercel_AI_SDK_Operation_Generation_Like",+ // PRIORITY4,+ // CANMAP?(attributes) => {const modelKeys = [LangfuseOtelSpanAttributes.OBSERVATION_MODEL,@@ -238,40 +267,44 @@ export class ObservationTypeMapperRegistry {const hasModelInformation = modelKeys.some((key) =>hasMeaningfulValue(attributes[key]),);- const hasOperationName = hasMeaningfulValue(- attributes["operation.name"],- );- const isToolCall = Boolean(attributes["ai.toolCall"]);+ // Only handle generation and embedding operations+ const generationEmbeddingPrefixes = [+ "ai.generateText",+ "ai.streamText",+ "ai.generateObject",+ "ai.streamObject",+ "ai.embed",+ ];++ const isGenerationOrEmbedding = matchesVercelAiSdkOperation(+ attributes,+ generationEmbeddingPrefixes,+ );- return (hasModelInformation && hasOperationName) || isToolCall;+ return hasModelInformation && isGenerationOrEmbedding;},+ // MAPPER(attributes) => {- const operationName = attributes["operation.name"] as string;- // Format:- // Vercel AI SDK Value: Langfuse ObservationType// IMPORTANT: prefixes inversely ordered by length to avoid false matches- // AI SDK may append function ID after operation name (e.g., "ai.embed my-function"), first seen on 2025-10-29 in SDK v5- const prefixMappings: Array<[string, LangfuseObservationType]> = [- ["ai.generateText.doGenerate", "GENERATION"],- ["ai.generateText", "GENERATION"],- ["ai.streamText.doStream", "GENERATION"],- ["ai.streamText", "GENERATION"],- ["ai.generateObject.doGenerate", "GENERATION"],- ["ai.generateObject", "GENERATION"],- ["ai.streamObject.doStream", "GENERATION"],- ["ai.streamObject", "GENERATION"],- ["ai.embed.doEmbed", "EMBEDDING"],- ["ai.embedMany.doEmbed", "EMBEDDING"],- ["ai.embedMany", "EMBEDDING"],- ["ai.embed", "EMBEDDING"],- ["ai.toolCall", "TOOL"],+ // AI SDK may append function ID after operation name (e.g., "ai.embed my-function")+ const prefixMappings: Array<[string[], LangfuseObservationType]> = [+ [["ai.generateText.doGenerate"], "GENERATION"],+ [["ai.generateText"], "GENERATION"],+ [["ai.streamText.doStream"], "GENERATION"],+ [["ai.streamText"], "GENERATION"],+ [["ai.generateObject.doGenerate"], "GENERATION"],+ [["ai.generateObject"], "GENERATION"],+ [["ai.streamObject.doStream"], "GENERATION"],+ [["ai.streamObject"], "GENERATION"],+ [["ai.embed.doEmbed"], "EMBEDDING"],+ [["ai.embedMany.doEmbed"], "EMBEDDING"],+ [["ai.embedMany"], "EMBEDDING"],+ [["ai.embed"], "EMBEDDING"],];- // Check if operation.name starts with any known operation prefix- // instead of checking for exact match due to the potentially added functionId- for (const [prefix, type] of prefixMappings) {- if (operationName.startsWith(prefix)) {+ for (const [prefixes, type] of prefixMappings) {+ if (matchesVercelAiSdkOperation(attributes, prefixes)) {return type;}}@@ -280,9 +313,59 @@ export class ObservationTypeMapperRegistry {},),+ // Priority 5: Vercel AI SDK span-like operations (no model info)new CustomAttributeMapper(- "ModelBased",+ // NAME+ "Vercel_AI_SDK_Operation_Span_Like",+ // PRIORITY5,+ // CANMAP?+ (attributes) => {+ // Check if it's a Vercel AI SDK operation (starts with "ai.")+ const operationName = attributes["operation.name"];+ const operationId = attributes["ai.operationId"];++ const hasAiOperation =+ (hasMeaningfulValue(operationName) &&+ (operationName as string).startsWith("ai.")) ||+ (hasMeaningfulValue(operationId) &&+ (operationId as string).startsWith("ai."));++ if (!hasAiOperation) {+ return false;+ }++ // Exclude generation and embedding operations (handled by Generation_Like mapper)+ // technically, not required here because the generation-like mapper has higher priority+ // but to keep them interchangeable, we reject them here+ const generationEmbeddingPrefixes = [+ "ai.generateText",+ "ai.streamText",+ "ai.generateObject",+ "ai.streamObject",+ "ai.embed",+ ];++ const isGenerationOrEmbedding = matchesVercelAiSdkOperation(+ attributes,+ generationEmbeddingPrefixes,+ );++ return !isGenerationOrEmbedding;+ },+ // MAPPER+ (attributes) => {+ // for now, there are only tools. further mappings should be added here+ if (matchesVercelAiSdkOperation(attributes, ["ai.toolCall"])) {+ return "TOOL";+ }+ return null;+ },+ ),++ new CustomAttributeMapper(+ "ModelBased",+ 6,(attributes, _resourceAttributes, _scopeData) => {const modelKeys = [LangfuseOtelSpanAttributes.OBSERVATION_MODEL,diff --git a/web/src/__tests__/server/api/otel/otelMapping.servertest.ts b/web/src/__tests__/server/api/otel/otelMapping.servertest.tsindex 8f873885d7..7bd5701ed3 100644--- a/web/src/__tests__/server/api/otel/otelMapping.servertest.ts+++ b/web/src/__tests__/server/api/otel/otelMapping.servertest.ts@@ -4197,6 +4197,202 @@ describe("OTel Resource Span Mapping", () => {expect(traceEvents.length).toBe(1);});+ it("should map Vercel AI SDK toolCall to tool-create", async () => {+ const otelSpans = [+ {+ resource: { attributes: [] },+ scopeSpans: [+ {+ scope: { name: "ai" },+ 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: "ai.toolCall",+ startTimeUnixNano: 1000000000,+ endTimeUnixNano: 2000000000,+ attributes: [+ {+ key: "operation.name",+ value: {+ stringValue: "ai.toolCall MyAgent.MyLLM.myFunction",+ },+ },+ {+ key: "resource.name",+ value: { stringValue: "MyAgent.MyLLM.myFunction" },+ },+ {+ key: "ai.operationId",+ value: { stringValue: "ai.toolCall" },+ },+ {+ key: "ai.toolCall.name",+ value: { stringValue: "myTool" },+ },+ {+ key: "ai.toolCall.id",+ value: { stringValue: "call_abc123" },+ },+ ],+ status: {},+ },+ ],+ },+ ],+ },+ ];++ const events = await convertOtelSpanToIngestionEvent(+ otelSpans[0],+ new Set(),+ publicKey,+ );++ const toolEvents = events.filter((e) => e.type === "tool-create");+ expect(toolEvents.length).toBe(1);+ });++ it("should map Vercel AI SDK toolCall using ai.operationId alone (without operation.name)", async () => {+ const otelSpans = [+ {+ resource: { attributes: [] },+ scopeSpans: [+ {+ scope: { name: "ai" },+ 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: "tool-execution",+ startTimeUnixNano: 1000000000,+ endTimeUnixNano: 2000000000,+ attributes: [+ {+ key: "ai.operationId",+ value: { stringValue: "ai.toolCall" },+ },+ ],+ status: {},+ },+ ],+ },+ ],+ },+ ];++ const events = await convertOtelSpanToIngestionEvent(+ otelSpans[0],+ new Set(),+ publicKey,+ );++ const toolEvents = events.filter((e) => e.type === "tool-create");+ expect(toolEvents.length).toBe(1);+ });++ it("should map Vercel AI SDK generation WITH model to generation-create", async () => {+ const otelSpans = [+ {+ resource: { attributes: [] },+ scopeSpans: [+ {+ scope: { name: "ai" },+ 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: "text-generation",+ startTimeUnixNano: 1000000000,+ endTimeUnixNano: 2000000000,+ attributes: [+ {+ key: "operation.name",+ value: { stringValue: "ai.generateText" },+ },+ {+ key: "gen_ai.response.model",+ value: { stringValue: "gpt-4" },+ },+ ],+ status: {},+ },+ ],+ },+ ],+ },+ ];++ const events = await convertOtelSpanToIngestionEvent(+ otelSpans[0],+ new Set(),+ publicKey,+ );++ const generationEvents = events.filter(+ (e) => e.type === "generation-create",+ );+ expect(generationEvents.length).toBe(1);+ });++ it("should fallback to span-create for AI SDK generation WITHOUT model", async () => {+ const otelSpans = [+ {+ resource: { attributes: [] },+ scopeSpans: [+ {+ scope: { name: "ai" },+ 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: "text-generation",+ startTimeUnixNano: 1000000000,+ endTimeUnixNano: 2000000000,+ attributes: [+ {+ key: "operation.name",+ value: { stringValue: "ai.generateText" },+ },+ ],+ status: {},+ },+ ],+ },+ ],+ },+ ];++ const events = await convertOtelSpanToIngestionEvent(+ otelSpans[0],+ new Set(),+ publicKey,+ );++ const spanEvents = events.filter((e) => e.type === "span-create");+ const generationEvents = events.filter(+ (e) => e.type === "generation-create",+ );+ expect(spanEvents.length).toBe(1);+ expect(generationEvents.length).toBe(0);+ });+it("should override the observation type if it is declared as 'span' but holds generation-like attributes for python-sdk <= 3.3.0", async () => {// Issue: https://github.com/langfuse/langfuse/issues/8682const otelSpans = [