🪢 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
feat(otel): add Langfuse attribute parsing (#6692)
Hassieb Pakzade63cf84e4f3a
diff --git a/packages/shared/src/server/auth/types.ts b/packages/shared/src/server/auth/types.tsindex ed79e0c3f1..a9e25a31f9 100644--- a/packages/shared/src/server/auth/types.ts+++ b/packages/shared/src/server/auth/types.ts@@ -55,4 +55,5 @@ export type ApiAccessScope = {plan: Plan;rateLimitOverrides: z.infer<typeof CloudConfigRateLimit>;apiKeyId: string;+ publicKey: string;};diff --git a/web/src/__tests__/server/api/otel/otelMapping.servertest.ts b/web/src/__tests__/server/api/otel/otelMapping.servertest.tsindex 9b86ce09f3..6b173e9b9d 100644--- a/web/src/__tests__/server/api/otel/otelMapping.servertest.ts+++ b/web/src/__tests__/server/api/otel/otelMapping.servertest.ts@@ -5,6 +5,558 @@ import {import { ingestionEvent } from "@langfuse/shared/src/server";describe("OTel Resource Span Mapping", () => {+ describe("Langfuse OTEL SDK spans", () => {+ const publicKey = "pk-lf-1234567890";++ it("should convert LF-OTEL spans to LF-events", () => {+ const langfuseOtelSpans = [+ {+ resource: {+ attributes: [+ {+ key: "telemetry.sdk.language",+ value: { stringValue: "python" },+ },+ {+ key: "telemetry.sdk.name",+ value: { stringValue: "opentelemetry" },+ },+ {+ key: "telemetry.sdk.version",+ value: { stringValue: "1.32.0" },+ },+ {+ key: "langfuse.environment",+ value: { stringValue: "production" },+ },+ { key: "langfuse.release", value: { stringValue: "0.0.1" } },+ {+ key: "service.name",+ value: { stringValue: "unknown_service" },+ },+ ],+ },+ scopeSpans: [+ {+ scope: {+ name: "langfuse-sdk",+ version: "2.60.3",+ attributes: [+ {+ key: "public_key",+ value: { stringValue: "pk-lf-1234567890" },+ },+ ],+ },+ spans: [+ {+ traceId: {+ type: "Buffer",+ data: [+ 44, 206, 24, 247, 232, 205, 6, 90, 11, 78, 99, 78, 239,+ 114, 131, 145,+ ],+ },+ spanId: {+ type: "Buffer",+ data: [87, 240, 37, 84, 23, 151, 65, 189],+ },+ parentSpanId: {+ type: "Buffer",+ data: [223, 227, 135, 254, 167, 239, 59, 2],+ },+ name: "my-generation",+ kind: 1,+ startTimeUnixNano: {+ low: 466848096,+ high: 406528574,+ unsigned: true,+ },+ endTimeUnixNano: {+ low: 467248096,+ high: 406528574,+ unsigned: true,+ },+ attributes: [+ {+ key: "langfuse.observation.type",+ value: { stringValue: "generation" },+ },+ {+ key: "langfuse.observation.level",+ value: { stringValue: "WARNING" },+ },+ {+ key: "langfuse.observation.status_message",+ value: { stringValue: "nothing to report" },+ },+ {+ key: "langfuse.observation.input",+ value: {+ stringValue: '[{"role": "user", "content": "hello"}]',+ },+ },+ {+ key: "langfuse.observation.output",+ value: {+ stringValue:+ '{"role": "assistant", "content": "what\'s up?"}',+ },+ },+ {+ key: "langfuse.observation.model.name",+ value: { stringValue: "gpt-4o" },+ },+ {+ key: "langfuse.observation.prompt.name",+ value: { stringValue: "my-prompt" },+ },+ {+ key: "langfuse.observation.prompt.version",+ value: { intValue: { low: 1, high: 0, unsigned: false } },+ },+ {+ key: "langfuse.observation.usage_details",+ value: {+ stringValue:+ '{"input_tokens": 123, "output_tokens": 456}',+ },+ },+ {+ key: "langfuse.observation.cost_details",+ value: {+ stringValue:+ '{"input_tokens": 0.0001, "output_tokens": 0.002}',+ },+ },+ {+ key: "langfuse.observation.completion_start_time",+ value: { stringValue: '"2025-04-30T15:28:50.686390Z"' },+ },+ {+ key: "langfuse.observation.model_parameters",+ value: {+ stringValue: '{"temperature": 1, "top_p": "0.2"}',+ },+ },+ {+ key: "langfuse.observation.metadata.key1",+ value: { stringValue: '"value1"' },+ },+ {+ key: "langfuse.observation.metadata.key2",+ value: { stringValue: '"value2"' },+ },+ {+ key: "langfuse.trace.name",+ value: { stringValue: "test-trace" },+ },+ { key: "user.id", value: { stringValue: "my-user" } },+ { key: "session.id", value: { stringValue: "my-session" } },+ {+ key: "langfuse.version",+ value: { stringValue: "trace-0.0.1" },+ },+ {+ key: "langfuse.trace.input",+ value: {+ stringValue: '[{"role": "user", "content": "hello"}]',+ },+ },+ {+ key: "langfuse.trace.output",+ value: {+ stringValue:+ '{"role": "assistant", "content": "what\'s up?"}',+ },+ },+ {+ key: "langfuse.trace.tags",+ value: {+ arrayValue: { values: [{ stringValue: "tag2" }] },+ },+ },+ {+ key: "langfuse.trace.public",+ value: { boolValue: true },+ },+ {+ key: "langfuse.trace.metadata.trace-key1",+ value: { stringValue: '"value1"' },+ },+ {+ key: "langfuse.trace.metadata.trace-key2",+ value: { stringValue: '"value2"' },+ },+ ],+ status: {},+ },+ {+ traceId: {+ type: "Buffer",+ data: [+ 44, 206, 24, 247, 232, 205, 6, 90, 11, 78, 99, 78, 239,+ 114, 131, 145,+ ],+ },+ spanId: {+ type: "Buffer",+ data: [223, 227, 135, 254, 167, 239, 59, 2],+ },+ name: "my-span",+ kind: 1,+ startTimeUnixNano: {+ low: 205413096,+ high: 406528574,+ unsigned: true,+ },+ endTimeUnixNano: {+ low: 467608096,+ high: 406528574,+ unsigned: true,+ },+ attributes: [+ {+ key: "langfuse.observation.type",+ value: { stringValue: "span" },+ },+ {+ key: "langfuse.trace.tags",+ value: {+ arrayValue: { values: [{ stringValue: "tag1" }] },+ },+ },+ {+ key: "langfuse.trace.metadata.trace-key0",+ value: { stringValue: '"value1"' },+ },+ ],+ status: {},+ },+ ],+ },+ ],+ },+ ];++ const events = langfuseOtelSpans.flatMap((span) =>+ convertOtelSpanToIngestionEvent(span, publicKey),+ );+ const traceEvents = events.filter((e) => e.type === "trace-create");+ const generationEvents = events.filter(+ (e) => e.type === "generation-create",+ );+ const spanEvents = events.filter((e) => e.type === "span-create");++ expect(events.length).toBe(4);+ expect(traceEvents.length).toBe(2);+ expect(spanEvents.length).toBe(1);+ expect(generationEvents.length).toBe(1);++ const spanEvent = spanEvents[0];+ const generationEvent = generationEvents[0];++ const defaultMetadata = {+ resourceAttributes: {+ "langfuse.environment": "production",+ "langfuse.release": "0.0.1",+ "service.name": "unknown_service",+ "telemetry.sdk.language": "python",+ "telemetry.sdk.name": "opentelemetry",+ "telemetry.sdk.version": "1.32.0",+ },+ scope: {+ name: "langfuse-sdk",+ version: "2.60.3",+ },+ };++ expect(spanEvent.body).toMatchObject({+ id: "dfe387fea7ef3b02",+ traceId: "2cce18f7e8cd065a0b4e634eef728391",+ parentObservationId: null,+ name: "my-span",+ startTime: "2025-04-30T15:28:50.424Z",+ endTime: "2025-04-30T15:28:50.687Z",+ environment: "production",+ metadata: { ...defaultMetadata },+ level: "DEFAULT",+ version: null,+ modelParameters: {},+ model: undefined,+ promptName: null,+ promptVersion: null,+ usageDetails: {},+ costDetails: {},+ input: null,+ output: null,+ });++ expect(generationEvent.body).toMatchObject({+ id: "57f02554179741bd",+ traceId: "2cce18f7e8cd065a0b4e634eef728391",+ parentObservationId: "dfe387fea7ef3b02",+ name: "my-generation",+ startTime: "2025-04-30T15:28:50.686Z",+ endTime: "2025-04-30T15:28:50.686Z",+ environment: "production",+ metadata: { ...defaultMetadata },+ level: "WARNING",+ statusMessage: "nothing to report",+ version: "trace-0.0.1",+ modelParameters: {},+ model: "gpt-4o",+ promptName: "my-prompt",+ promptVersion: 1,+ usageDetails: { input_tokens: 123, output_tokens: 456 },+ costDetails: { input_tokens: 0.0001, output_tokens: 0.002 },+ input: '[{"role": "user", "content": "hello"}]',+ output: '{"role": "assistant", "content": "what\'s up?"}',+ });++ expect(traceEvents[0].body).toMatchObject({+ id: "2cce18f7e8cd065a0b4e634eef728391",+ name: "test-trace",+ tags: ["tag2"],+ userId: "my-user",+ sessionId: "my-session",+ input: '[{"role": "user", "content": "hello"}]',+ output: '{"role": "assistant", "content": "what\'s up?"}',+ version: "trace-0.0.1",+ environment: "production",+ public: true,+ metadata: {+ ...defaultMetadata,+ "trace-key1": '"value1"',+ "trace-key2": '"value2"',+ },+ });++ expect(traceEvents[1].body).toMatchObject({+ id: "2cce18f7e8cd065a0b4e634eef728391",+ timestamp: "2025-04-30T15:28:50.424Z",+ name: "my-span",+ metadata: {+ ...defaultMetadata,+ "trace-key0": '"value1"',+ },+ tags: ["tag1"],+ environment: "production",+ });+ });++ it("should create a trace when as_root has been specified", () => {+ const langfuseOtelSpans = [+ {+ resource: {+ attributes: [+ {+ key: "telemetry.sdk.language",+ value: { stringValue: "python" },+ },+ {+ key: "telemetry.sdk.name",+ value: { stringValue: "opentelemetry" },+ },+ {+ key: "telemetry.sdk.version",+ value: { stringValue: "1.32.0" },+ },+ {+ key: "langfuse.environment",+ value: { stringValue: "production" },+ },+ { key: "langfuse.release", value: { stringValue: "0.0.1" } },+ {+ key: "service.name",+ value: { stringValue: "unknown_service" },+ },+ ],+ },+ scopeSpans: [+ {+ scope: {+ name: "langfuse-sdk",+ version: "2.60.3",+ attributes: [+ {+ key: "public_key",+ value: { stringValue: "pk-lf-1234567890" },+ },+ ],+ },+ spans: [+ {+ traceId: {+ type: "Buffer",+ data: [+ 149, 243, 185, 38, 199, 208, 9, 146, 91, 203, 93, 188, 39,+ 49, 17, 32,+ ],+ },+ spanId: {+ type: "Buffer",+ data: [212, 62, 55, 183, 209, 126, 84, 118],+ },+ parentSpanId: {+ type: "Buffer",+ data: [131, 78, 40, 181, 145, 127, 190, 246],+ },+ name: "my-span-with-custom-trace-id",+ kind: 1,+ startTimeUnixNano: {+ low: 1047784088,+ high: 406627672,+ unsigned: true,+ },+ endTimeUnixNano: {+ low: 1149405088,+ high: 406627672,+ unsigned: true,+ },+ attributes: [+ {+ key: "langfuse.observation.type",+ value: { stringValue: "span" },+ },+ {+ key: "langfuse.internal.as_root",+ value: { boolValue: true },+ },+ ],+ status: {},+ },+ ],+ },+ ],+ },+ ];++ const events = langfuseOtelSpans.flatMap((span) =>+ convertOtelSpanToIngestionEvent(span, publicKey),+ );+ const traceEvents = events.filter((e) => e.type === "trace-create");+ const spanEvents = events.filter((e) => e.type === "span-create");++ expect(events.length).toBe(2);+ expect(traceEvents.length).toBe(1);+ expect(spanEvents.length).toBe(1);++ const spanEvent = spanEvents[0];+ const traceEvent = traceEvents[0];++ expect(spanEvent.body).toMatchObject({+ id: "d43e37b7d17e5476",+ traceId: "95f3b926c7d009925bcb5dbc27311120",+ parentObservationId: "834e28b5917fbef6",+ name: "my-span-with-custom-trace-id",+ startTime: "2025-05-05T13:42:33.936Z",+ endTime: "2025-05-05T13:42:34.038Z",+ environment: "production",+ level: "DEFAULT",+ });++ expect(traceEvent.body).toMatchObject({+ id: "95f3b926c7d009925bcb5dbc27311120",+ timestamp: "2025-05-05T13:42:33.936Z",+ name: "my-span-with-custom-trace-id",+ environment: "production",+ });+ });+ it("should throw an error if langfuse scope spans have wrong project ID", () => {+ const langfuseOtelSpans = [+ {+ resource: {+ attributes: [+ {+ key: "telemetry.sdk.language",+ value: {+ stringValue: "python",+ },+ },+ {+ key: "telemetry.sdk.name",+ value: {+ stringValue: "opentelemetry",+ },+ },+ {+ key: "telemetry.sdk.version",+ value: {+ stringValue: "1.32.0",+ },+ },+ {+ key: "service.name",+ value: {+ stringValue: "unknown_service",+ },+ },+ ],+ },+ scopeSpans: [+ {+ scope: {+ name: "langfuse-sdk",+ version: "2.60.3",+ attributes: [+ {+ key: "public_key",+ value: {+ stringValue: "pk-lf-another",+ },+ },+ ],+ },+ spans: [+ {+ traceId: {+ type: "Buffer",+ data: [+ 219, 242, 249, 255, 154, 168, 21, 165, 233, 52, 222, 186,+ 28, 97, 54, 95,+ ],+ },+ spanId: {+ type: "Buffer",+ data: [128, 191, 93, 22, 69, 180, 81, 135],+ },+ name: "t1",+ kind: 1,+ startTimeUnixNano: {+ low: -1422874264,+ high: 406650983,+ unsigned: true,+ },+ endTimeUnixNano: {+ low: -904695264,+ high: 406650983,+ unsigned: true,+ },+ attributes: [+ {+ key: "langfuse.observation.type",+ value: {+ stringValue: "span",+ },+ },+ ],+ status: {},+ },+ ],+ },+ ],+ },+ ];++ expect(() =>+ langfuseOtelSpans.flatMap((span) =>+ convertOtelSpanToIngestionEvent(span, publicKey),+ ),+ ).toThrowError("Langfuse OTEL SDK span has different public key");+ });+ });+describe("Vendor Spans", () => {it("should convert an OpenLit OTel Span to Langfuse Events", () => {// Setupdiff --git a/web/src/features/otel/server/attributes.ts b/web/src/features/otel/server/attributes.tsnew file mode 100644index 0000000000..134fdac874--- /dev/null+++ b/web/src/features/otel/server/attributes.ts@@ -0,0 +1,36 @@+export enum LangfuseOtelSpanAttributes {+ // Langfuse-Trace attributes+ TRACE_NAME = "langfuse.trace.name",+ TRACE_USER_ID = "user.id",+ TRACE_SESSION_ID = "session.id",+ TRACE_TAGS = "langfuse.trace.tags",+ TRACE_PUBLIC = "langfuse.trace.public",+ TRACE_METADATA = "langfuse.trace.metadata",+ TRACE_INPUT = "langfuse.trace.input",+ TRACE_OUTPUT = "langfuse.trace.output",++ // Langfuse-observation attributes+ OBSERVATION_TYPE = "langfuse.observation.type",+ OBSERVATION_METADATA = "langfuse.observation.metadata",+ OBSERVATION_LEVEL = "langfuse.observation.level",+ OBSERVATION_STATUS_MESSAGE = "langfuse.observation.status_message",+ OBSERVATION_INPUT = "langfuse.observation.input",+ OBSERVATION_OUTPUT = "langfuse.observation.output",++ // Langfuse-observation of type Generation attributes+ OBSERVATION_COMPLETION_START_TIME = "langfuse.observation.completion_start_time",+ OBSERVATION_MODEL = "langfuse.observation.model.name",+ OBSERVATION_MODEL_PARAMETERS = "langfuse.observation.model.parameters",+ OBSERVATION_USAGE_DETAILS = "langfuse.observation.usage_details",+ OBSERVATION_COST_DETAILS = "langfuse.observation.cost_details",+ OBSERVATION_PROMPT_NAME = "langfuse.observation.prompt.name",+ OBSERVATION_PROMPT_VERSION = "langfuse.observation.prompt.version",++ // General+ ENVIRONMENT = "langfuse.environment",+ RELEASE = "langfuse.release",+ VERSION = "langfuse.version",++ // Internal+ AS_ROOT = "langfuse.internal.as_root",+}diff --git a/web/src/features/otel/server/index.ts b/web/src/features/otel/server/index.tsindex 61d37d057f..7329499987 100644--- a/web/src/features/otel/server/index.ts+++ b/web/src/features/otel/server/index.ts@@ -1,6 +1,7 @@import { type IngestionEventType } from "@langfuse/shared/src/server";import { randomUUID } from "crypto";-import { ObservationLevel } from "@langfuse/shared";+import { ForbiddenError, ObservationLevel } from "@langfuse/shared";+import { LangfuseOtelSpanAttributes } from "./attributes";export const convertNanoTimestampToISO = (timestamp:@@ -126,15 +127,35 @@ const convertKeyPathToNestedObject = (const extractInputAndOutput = (events: any[],attributes: Record<string, unknown>,+ domain?: "trace" | "observation",): { input: any; output: any } => {+ let input = null;+ let output = null;++ // Langfuse+ input =+ domain === "trace"+ ? attributes[LangfuseOtelSpanAttributes.TRACE_INPUT]+ : attributes[LangfuseOtelSpanAttributes.OBSERVATION_INPUT];+ output =+ domain === "trace"+ ? attributes[LangfuseOtelSpanAttributes.TRACE_OUTPUT]+ : attributes[LangfuseOtelSpanAttributes.OBSERVATION_OUTPUT];++ if (input != null || output != null) {+ return { input, output };+ }+// Openlit uses events property- let input = events.find(+ input = events.find((event: Record<string, unknown>) => event.name === "gen_ai.content.prompt",)?.attributes;- let output = events.find(++ output = events.find((event: Record<string, unknown>) =>event.name === "gen_ai.content.completion",)?.attributes;+if (input || output) {input =input?.reduce((acc: any, attr: any) => {@@ -258,10 +279,11 @@ const extractEnvironment = (resourceAttributes: Record<string, unknown>,): string => {const environmentAttributeKeys = [- "langfuse.environment",+ LangfuseOtelSpanAttributes.ENVIRONMENT,"deployment.environment.name","deployment.environment",];+for (const key of environmentAttributeKeys) {if (resourceAttributes[key]) {return resourceAttributes[key] as string;@@ -270,6 +292,7 @@ const extractEnvironment = (return attributes[key] as string;}}+return "default";};@@ -285,23 +308,34 @@ const extractName = (: JSON.stringify(attributes[key]);}}+return spanName;};const extractMetadata = (attributes: Record<string, unknown>,+ domain: "trace" | "observation",): Record<string, unknown> => {// Extract top-level metadata object if availablelet metadata: Record<string, unknown> = {};- if (attributes["langfuse.metadata"]) {++ const metadataKeyPrefix =+ domain === "observation"+ ? LangfuseOtelSpanAttributes.OBSERVATION_METADATA+ : LangfuseOtelSpanAttributes.TRACE_METADATA;++ const langfuseMetadataAttribute =+ attributes[metadataKeyPrefix] || attributes["langfuse.metadata"];++ if (langfuseMetadataAttribute) {try {// If it's a string (JSON), parse it- if (typeof attributes["langfuse.metadata"] === "string") {- metadata = JSON.parse(attributes["langfuse.metadata"] as string);+ if (typeof langfuseMetadataAttribute === "string") {+ metadata = JSON.parse(langfuseMetadataAttribute as string);}// If it's already an object, use it- else if (typeof attributes["langfuse.metadata"] === "object") {- metadata = attributes["langfuse.metadata"] as Record<string, unknown>;+ else if (typeof langfuseMetadataAttribute === "object") {+ metadata = langfuseMetadataAttribute as Record<string, unknown>;}} catch (e) {// If parsing fails, continue with nested metadata extraction@@ -309,17 +343,20 @@ const extractMetadata = (}// Extract metadata from langfuse.metadata.* keys- const metadataAttributes = Object.keys(attributes).filter((key) =>- key.startsWith("langfuse.metadata."),- );+ const langfuseMetadata: Record<string, unknown> = {};++ for (const [key, value] of Object.entries(attributes)) {+ for (const prefix of [metadataKeyPrefix, "langfuse.metadata"]) {+ if (key.startsWith(`${prefix}.`)) {+ const newKey = key.replace(`${prefix}.`, "");+ langfuseMetadata[newKey] = value;+ }+ }+ }return {...metadata,- ...metadataAttributes.reduce((acc: Record<string, unknown>, key) => {- const metadataKey = key.replace("langfuse.metadata.", "");- acc[metadataKey] = attributes[key];- return acc;- }, {}),+ ...langfuseMetadata,};};@@ -327,6 +364,7 @@ const extractUserId = (attributes: Record<string, unknown>,): string | undefined => {const userIdKeys = ["langfuse.user.id", "user.id"];+for (const key of userIdKeys) {if (attributes[key]) {return typeof attributes[key] === "string"@@ -340,6 +378,7 @@ const extractSessionId = (attributes: Record<string, unknown>,): string | undefined => {const userIdKeys = ["langfuse.session.id", "session.id"];+for (const key of userIdKeys) {if (attributes[key]) {return typeof attributes[key] === "string"@@ -352,6 +391,17 @@ const extractSessionId = (const extractModelParameters = (attributes: Record<string, unknown>,): Record<string, unknown> => {+ // Langfuse+ if (attributes[LangfuseOtelSpanAttributes.OBSERVATION_MODEL_PARAMETERS]) {+ try {+ return JSON.parse(+ attributes[+ LangfuseOtelSpanAttributes.OBSERVATION_MODEL_PARAMETERS+ ] as string,+ );+ } catch {}+ }+// If we get invocation parameters, we use them as they areif (attributes["llm.invocation_parameters"]) {try {@@ -372,6 +422,7 @@ const extractModelParameters = (const modelParameters = Object.keys(attributes).filter((key) =>key.startsWith("gen_ai.request."),);+return modelParameters.reduce((acc: any, key) => {const modelParamKey = key.replace("gen_ai.request.", "");// avoid double-reporting the model name, already included in native model attribute@@ -386,6 +437,7 @@ const extractModelName = (attributes: Record<string, unknown>,): string | undefined => {const modelNameKeys = [+ LangfuseOtelSpanAttributes.OBSERVATION_MODEL,"gen_ai.request.model","gen_ai.response.model","llm.model_name",@@ -402,12 +454,24 @@ const extractModelName = (const extractUsageDetails = (attributes: Record<string, unknown>,+ isLangfuseSDKSpan: boolean,): Record<string, unknown> => {+ if (isLangfuseSDKSpan) {+ try {+ return JSON.parse(+ attributes[+ LangfuseOtelSpanAttributes.OBSERVATION_USAGE_DETAILS+ ] as string,+ );+ } catch {}+ }+const usageDetails = Object.keys(attributes).filter((key) =>(key.startsWith("gen_ai.usage.") && key !== "gen_ai.usage.cost") ||key.startsWith("llm.token_count"),);+const usageDetailKeyMapping: Record<string, string> = {prompt_tokens: "input",completion_tokens: "output",@@ -417,6 +481,7 @@ const extractUsageDetails = (prompt: "input",completion: "output",};+return usageDetails.reduce((acc: any, key) => {const usageDetailKey = key.replace("gen_ai.usage.", "")@@ -434,15 +499,40 @@ const extractUsageDetails = (const extractCostDetails = (attributes: Record<string, unknown>,+ isLangfuseSDKSpan: boolean,): Record<string, unknown> => {+ if (isLangfuseSDKSpan) {+ try {+ return JSON.parse(+ attributes[+ LangfuseOtelSpanAttributes.OBSERVATION_COST_DETAILS+ ] as string,+ );+ } catch {}+ }+if (attributes["gen_ai.usage.cost"]) {return { total: attributes["gen_ai.usage.cost"] };}return {};};+const extractCompletionStartTime = (attributes: Record<string, unknown>) => {+ try {+ return JSON.parse(+ attributes[+ LangfuseOtelSpanAttributes.OBSERVATION_COMPLETION_START_TIME+ ] as string,+ );+ } catch {}++ return null;+};+const extractTags = (attributes: Record<string, unknown>): string[] => {- const tagsValue = attributes["langfuse.tags"];+ const tagsValue =+ attributes[LangfuseOtelSpanAttributes.TRACE_TAGS] ||+ attributes["langfuse.tags"];// If no tags, return empty arrayif (tagsValue === undefined || tagsValue === null) {@@ -488,6 +578,7 @@ const extractTags = (attributes: Record<string, unknown>): string[] => {*/export const convertOtelSpanToIngestionEvent = (resourceSpan: any,+ publicKey?: string,): IngestionEventType[] => {const resourceAttributes =resourceSpan?.resource?.attributes?.reduce((acc: any, attr: any) => {@@ -498,6 +589,24 @@ export const convertOtelSpanToIngestionEvent = (const events: IngestionEventType[] = [];for (const scopeSpan of resourceSpan?.scopeSpans ?? []) {+ const isLangfuseSDKSpans = scopeSpan.scope?.name.startsWith("langfuse-sdk");++ const scopeAttributes =+ scopeSpan?.scope?.attributes?.reduce((acc: any, attr: any) => {+ acc[attr.key] = convertValueToPlainJavascript(attr.value);+ return acc;+ }, {}) ?? {};++ if (+ isLangfuseSDKSpans &&+ (!publicKey ||+ (scopeAttributes["public_key"] as unknown as string) !== publicKey)+ ) {+ throw new ForbiddenError(+ `Langfuse OTEL SDK span has different public key '${scopeAttributes["public_key"]}' than used for authentication '${publicKey}'. Discarding span.`,+ );+ }+for (const span of scopeSpan?.spans ?? []) {const attributes =span?.attributes?.reduce((acc: any, attr: any) => {@@ -511,29 +620,53 @@ export const convertOtelSpanToIngestionEvent = (): null;- const spanAttributeMetadata = extractMetadata(attributes);- const resourceAttributeMetadata = extractMetadata(resourceAttributes);- if (!parentObservationId) {+ const spanAttributeMetadata = extractMetadata(attributes, "observation");+ const resourceAttributeMetadata = extractMetadata(+ resourceAttributes,+ "trace",+ );+ const startTimeISO = convertNanoTimestampToISO(span.startTimeUnixNano);+ const endTimeISO = convertNanoTimestampToISO(span.endTimeUnixNano);+ const is_root_span =+ !parentObservationId ||+ String(attributes[LangfuseOtelSpanAttributes.AS_ROOT]) === "true";++ const hasTraceUpdates = [+ LangfuseOtelSpanAttributes.TRACE_NAME,+ LangfuseOtelSpanAttributes.TRACE_INPUT,+ LangfuseOtelSpanAttributes.TRACE_OUTPUT,+ LangfuseOtelSpanAttributes.TRACE_METADATA,+ LangfuseOtelSpanAttributes.TRACE_USER_ID,+ LangfuseOtelSpanAttributes.TRACE_SESSION_ID,+ LangfuseOtelSpanAttributes.TRACE_PUBLIC,+ LangfuseOtelSpanAttributes.TRACE_TAGS,+ ].some((traceAttribute) => Boolean(attributes[traceAttribute]));++ if (is_root_span || hasTraceUpdates) {// Create a trace for any root spanconst trace = {id: Buffer.from(span.traceId?.data ?? span.traceId).toString("hex"),- timestamp: convertNanoTimestampToISO(span.startTimeUnixNano),- name: extractName(span.name, attributes),+ timestamp: startTimeISO,+ name:+ attributes[LangfuseOtelSpanAttributes.TRACE_NAME] ??+ extractName(span.name, attributes),metadata: {...resourceAttributeMetadata,- ...spanAttributeMetadata,- attributes,+ ...extractMetadata(attributes, "trace"),+ ...(isLangfuseSDKSpans ? {} : { attributes }),resourceAttributes,- scope: scopeSpan?.scope,+ scope: { ...(scopeSpan.scope || {}), attributes: scopeAttributes },},version:- attributes?.["langfuse.version"] ??+ attributes?.[LangfuseOtelSpanAttributes.VERSION] ??resourceAttributes?.["service.version"] ??null,- release: attributes?.["langfuse.release"] ?? null,+ release: attributes?.[LangfuseOtelSpanAttributes.RELEASE] ?? null,userId: extractUserId(attributes),sessionId: extractSessionId(attributes),public:+ attributes?.[LangfuseOtelSpanAttributes.TRACE_PUBLIC] === true ||+ attributes?.[LangfuseOtelSpanAttributes.TRACE_PUBLIC] === "true" ||attributes?.["langfuse.public"] === true ||attributes?.["langfuse.public"] === "true",tags: extractTags(attributes),@@ -541,12 +674,12 @@ export const convertOtelSpanToIngestionEvent = (environment: extractEnvironment(attributes, resourceAttributes),// Input and Output- ...extractInputAndOutput(span?.events ?? [], attributes),+ ...extractInputAndOutput(span?.events ?? [], attributes, "trace"),};events.push({id: randomUUID(),type: "trace-create",- timestamp: new Date().toISOString(),+ timestamp: new Date(startTimeISO).toISOString(),body: trace,});}@@ -559,36 +692,50 @@ export const convertOtelSpanToIngestionEvent = (),parentObservationId,name: extractName(span.name, attributes),- startTime: convertNanoTimestampToISO(span.startTimeUnixNano),- endTime: convertNanoTimestampToISO(span.endTimeUnixNano),+ startTime: startTimeISO,+ endTime: endTimeISO,environment: extractEnvironment(attributes, resourceAttributes),// Additional fields+ completionStartTime: extractCompletionStartTime(attributes),metadata: {...resourceAttributeMetadata,...spanAttributeMetadata,- attributes,+ ...(isLangfuseSDKSpans ? {} : { attributes }),resourceAttributes,- scope: scopeSpan?.scope,+ scope: { ...scopeSpan.scope, attributes: scopeAttributes },},level:- span.status?.code === 2+ attributes[LangfuseOtelSpanAttributes.OBSERVATION_LEVEL] ??+ (span.status?.code === 2? ObservationLevel.ERROR- : ObservationLevel.DEFAULT,- statusMessage: span.status?.message ?? null,+ : ObservationLevel.DEFAULT),+ statusMessage:+ attributes[LangfuseOtelSpanAttributes.OBSERVATION_STATUS_MESSAGE] ??+ span.status?.message ??+ null,version:- attributes?.["langfuse.version"] ??+ attributes[LangfuseOtelSpanAttributes.VERSION] ??resourceAttributes?.["service.version"] ??null,modelParameters: extractModelParameters(attributes) as any,model: extractModelName(attributes),- promptName: attributes?.["langfuse.prompt.name"] ?? null,- promptVersion: attributes?.["langfuse.prompt.version"] ?? null,+ promptName:+ attributes?.[LangfuseOtelSpanAttributes.OBSERVATION_PROMPT_NAME] ??+ attributes["langfuse.prompt.name"] ??+ null,+ promptVersion:+ attributes?.[LangfuseOtelSpanAttributes.OBSERVATION_PROMPT_VERSION] ??+ attributes["langfuse.prompt.version"] ??+ null,- usageDetails: extractUsageDetails(attributes) as any,- costDetails: extractCostDetails(attributes) as any,+ usageDetails: extractUsageDetails(+ attributes,+ isLangfuseSDKSpans,+ ) as any,+ costDetails: extractCostDetails(attributes, isLangfuseSDKSpans) as any,// Input and Output...extractInputAndOutput(span?.events ?? [], attributes),@@ -598,9 +745,12 @@ export const convertOtelSpanToIngestionEvent = (// Just checking for llm.* or gen_ai.* attributes leads to overreporting and wrong// aggregations for costs.const isGeneration =+ attributes[LangfuseOtelSpanAttributes.OBSERVATION_TYPE] ===+ "generation" ||Boolean(observation.model) ||("openinference.span.kind" in attributes &&attributes["openinference.span.kind"] === "LLM");+events.push({id: randomUUID(),type: isGeneration ? "generation-create" : "span-create",@@ -609,5 +759,6 @@ export const convertOtelSpanToIngestionEvent = (});}}+return events;};diff --git a/web/src/features/public-api/server/apiAuth.ts b/web/src/features/public-api/server/apiAuth.tsindex 2dfd4aa6ad..34d5602a16 100644--- a/web/src/features/public-api/server/apiAuth.ts+++ b/web/src/features/public-api/server/apiAuth.ts@@ -219,6 +219,7 @@ export class ApiAuthService {rateLimitOverrides: finalApiKey.rateLimitOverrides ?? [],apiKeyId: finalApiKey.id,scope: finalApiKey.scope,+ publicKey,},};}@@ -249,6 +250,7 @@ export class ApiAuthService {rateLimitOverrides: cloudConfig?.rateLimitOverrides ?? [],apiKeyId: dbKey.id,scope: dbKey.scope,+ publicKey,},};}diff --git a/web/src/pages/api/public/otel/v1/traces/index.ts b/web/src/pages/api/public/otel/v1/traces/index.tsindex 92be76136e..0615c49610 100644--- a/web/src/pages/api/public/otel/v1/traces/index.ts+++ b/web/src/pages/api/public/otel/v1/traces/index.ts@@ -90,7 +90,8 @@ export default withMiddlewares({}const events: IngestionEventType[] = resourceSpans.flatMap(- convertOtelSpanToIngestionEvent,+ (span: unknown) =>+ convertOtelSpanToIngestionEvent(span, auth.scope.publicKey),);// We set a delay of 0 for OTel, as we never expect updates.return processEventBatch(events, auth, 0, false);