🪢 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
chore(fetch-llm-completion): add AI SDK OpenAI adapter (#14791)
Hassieb Pakzad001fa88108d7
diff --git a/packages/shared/package.json b/packages/shared/package.jsonindex 417bf4c6d3..4e0e212f3e 100644--- a/packages/shared/package.json+++ b/packages/shared/package.json@@ -97,6 +97,7 @@"@anthropic-ai/tokenizer": "^0.0.4","@anthropic-ai/vertex-sdk": "^0.17.1","@aws-sdk/client-cloudwatch": "^3.1013.0",+ "@ai-sdk/openai": "^4.0.0","@aws-sdk/client-lambda": "^3.1046.0","@aws-sdk/client-s3": "^3.1013.0","@aws-sdk/client-sesv2": "^3.1013.0",@@ -112,6 +113,9 @@"@langchain/google": "^0.1.11","@langchain/openai": "^1.4.2","@opentelemetry/api": ">=1.0.0 <1.10.0",+ "@opentelemetry/otlp-transformer": "^0.219.0",+ "@opentelemetry/resources": "^2.8.0",+ "@opentelemetry/sdk-trace-base": "^2.8.0","@prisma/client": "^6.19.3","@react-email/components": "^0.5.1","@react-email/render": "^1.2.1",@@ -119,6 +123,7 @@"@slack/web-api": "^7.15.0","@smithy/node-http-handler": "4.5.1","@types/bcryptjs": "^2.4.6",+ "ai": "^7.0.0","ajv": "^8.18.0","ajv-formats": "^3.0.1","bcryptjs": "^2.4.3",@@ -148,6 +153,7 @@"zod": "^4.3.6"},"devDependencies": {+ "@opentelemetry/context-async-hooks": "^2.8.0","@repo/eslint-config": "workspace:*","@repo/typescript-config": "workspace:*","@types/lodash": "^4.17.24",diff --git a/packages/shared/src/env.ts b/packages/shared/src/env.tsindex abaeeadfc3..d71c33f3d3 100644--- a/packages/shared/src/env.ts+++ b/packages/shared/src/env.ts@@ -443,6 +443,20 @@ const EnvSchema = z.object({.positive().default(120_000), // 2 minutes+ // Comma-separated list of LLM adapters (e.g. "openai") whose completions run+ // on the AI SDK execution engine instead of LangChain+ LANGFUSE_LLM_COMPLETION_AI_SDK_ADAPTERS: z+ .string()+ .optional()+ .transform((s) =>+ s+ ? s+ .split(",")+ .map((v) => v.trim().toLowerCase())+ .filter(Boolean)+ : [],+ ),+LANGFUSE_AWS_BEDROCK_REGION: z.string().optional(),LANGFUSE_AWS_BEDROCK_SMALL_MODEL: z.string().optional(),LANGFUSE_IN_APP_AGENT_AWS_PROFILE: z.string().optional(),diff --git a/packages/shared/src/server/llm/ai-sdk/executeAiSdkCompletion.ts b/packages/shared/src/server/llm/ai-sdk/executeAiSdkCompletion.tsnew file mode 100644index 0000000000..e1340d91ff--- /dev/null+++ b/packages/shared/src/server/llm/ai-sdk/executeAiSdkCompletion.ts@@ -0,0 +1,287 @@+import { ZodType } from "zod";++import { IterableReadableStream } from "@langchain/core/utils/stream";+import {+ generateText,+ jsonSchema,+ Output,+ streamText,+ tool,+ type JSONValue,+ type LanguageModel,+ type ModelMessage,+ type TelemetryOptions,+ type ToolSet,+} from "ai";++import {+ hasTimeoutAbortInCauseChain,+ mapToLLMCompletionError,+} from "../completionErrorMapping";+import { LLMCompletionError } from "../errors";+import {+ ChatMessage,+ LLMJSONSchema,+ LLMToolDefinition,+ ModelParams,+ ToolCallResponse,+ ToolCallResponseSchema,+ TraceSinkParams,+} from "../types";+import { mapChatMessagesToModelMessages } from "./messages";+import { buildOpenAIModel, type OpenAIApiMode } from "./providers/openai";+import {+ createAiSdkTelemetryCapture,+ type AiSdkTelemetryCapture,+} from "./telemetry";++type CompletionWithReasoning = { text: string; reasoning?: string };++type BaseCallOptions = {+ model: LanguageModel;+ messages: ModelMessage[];+ allowSystemInMessages: boolean;+ maxOutputTokens?: number;+ temperature?: number;+ topP?: number;+ maxRetries?: number;+ timeout: number;+ providerOptions?: Record<string, Record<string, JSONValue>>;+ telemetry?: TelemetryOptions;+};++export type AiSdkCompletionParams = {+ messages: ChatMessage[];+ tools?: LLMToolDefinition[];+ modelParams: ModelParams;+ streaming: boolean;+ structuredOutputSchema?: ZodType | LLMJSONSchema;+ apiKey: string;+ baseURL?: string | null;+ extraHeaders?: Record<string, string>;+ maxRetries?: number;+ timeoutMs: number;+ fetch: typeof fetch;+ apiMode: OpenAIApiMode;+ translatedProviderOptions?: Record<string, unknown>;+ traceSinkParams?: TraceSinkParams;+};++/**+ * AI SDK execution engine for `fetchLLMCompletion`. Preserves the external+ * contracts of the LangChain engine: same return shapes per mode, same+ * `LLMCompletionError` classification (via `mapToLLMCompletionError`), and the+ * same runtime-timeout message that the retry classification keys on.+ */+export async function executeAiSdkCompletion(+ params: AiSdkCompletionParams,+): Promise<+ | string+ | CompletionWithReasoning+ | IterableReadableStream<Uint8Array>+ | Record<string, unknown>+ | ToolCallResponse+> {+ const {+ messages,+ tools,+ modelParams,+ streaming,+ structuredOutputSchema,+ maxRetries,+ timeoutMs,+ translatedProviderOptions,+ traceSinkParams,+ } = params;++ // Setup runs outside the main try/finally (the streaming branch returns+ // before it, and no telemetry exists yet to flush), but its failures must+ // still honor the LLMCompletionError retryability contract.+ let model: LanguageModel;+ let modelMessages: ModelMessage[];+ let capture: AiSdkTelemetryCapture | undefined;+ try {+ model = buildOpenAIModel(params);+ modelMessages = mapChatMessagesToModelMessages(messages);+ capture = traceSinkParams+ ? createAiSdkTelemetryCapture({+ traceSinkParams,+ rootInput: messages,+ })+ : undefined;+ } catch (e) {+ throw toCompletionError(e, timeoutMs);+ }++ const runInTraceContext = <T>(fn: () => T): T =>+ capture ? capture.run(fn) : fn();++ const baseOptions: BaseCallOptions = {+ model,+ messages: modelMessages,+ // The message mapper keeps the first system/developer message as a system+ // message inside `messages` (LangChain-parity). AI SDK v7 rejects that by+ // default with InvalidPromptError — which silently failed every prompt+ // experiment, since compiled prompts are system-first.+ allowSystemInMessages: true,+ maxOutputTokens: modelParams.max_tokens,+ temperature: modelParams.temperature,+ topP: modelParams.top_p,+ maxRetries,+ timeout: timeoutMs,+ ...(translatedProviderOptions+ ? {+ providerOptions: {+ openai: translatedProviderOptions as Record<string, JSONValue>,+ },+ }+ : {}),+ ...(capture ? { telemetry: capture.telemetry } : {}),+ };++ if (streaming) {+ return executeStreaming({+ baseOptions,+ timeoutMs,+ capture,+ runInTraceContext,+ });+ }++ try {+ if (structuredOutputSchema) {+ const result = await runInTraceContext(() =>+ generateText({+ ...baseOptions,+ output: Output.object({+ schema: toFlexibleSchema(structuredOutputSchema),+ }),+ }),+ );++ const output = result.output as Record<string, unknown>;+ capture?.setRootOutput(output);++ return output;+ }++ if (tools && tools.length > 0) {+ const result = await runInTraceContext(() =>+ generateText({ ...baseOptions, tools: buildToolSet(tools) }),+ );++ const parsed = ToolCallResponseSchema.safeParse({+ content: result.text,+ tool_calls: result.toolCalls.map((toolCall) => ({+ name: toolCall.toolName,+ id: toolCall.toolCallId,+ args: toolCall.input ?? {},+ })),+ });++ if (!parsed.success) throw Error("Failed to parse LLM tool call result");++ const reasoning = result.finalStep?.reasoningText;+ const toolCallResponse = {+ ...parsed.data,+ ...(reasoning ? { reasoning } : {}),+ };+ capture?.setRootOutput(toolCallResponse);++ return toolCallResponse;+ }++ const result = await runInTraceContext(() => generateText(baseOptions));++ const reasoning = result.finalStep?.reasoningText;+ const completion = reasoning+ ? { text: result.text, reasoning }+ : result.text;+ capture?.setRootOutput(completion);++ return completion;+ } catch (e) {+ const completionError = toCompletionError(e, timeoutMs);+ capture?.setRootError(completionError);+ throw completionError;+ } finally {+ await capture?.flush();+ }+}++/**+ * Normalizes AI SDK failures to `LLMCompletionError`. Native SDK timeouts+ * (DOMException "TimeoutError" without status or message pattern) are mapped+ * to the canonical runtime-timeout error so the shared retry classification+ * keeps treating timeouts as non-retryable, exactly like the LangChain+ * engine's `executeWithRuntimeTimeout`.+ */+function toCompletionError(e: unknown, timeoutMs: number): LLMCompletionError {+ if (hasTimeoutAbortInCauseChain(e)) {+ return new LLMCompletionError({+ message: `Request timed out after ${timeoutMs}ms`,+ responseStatusCode: 500,+ isRetryable: false,+ cause: e,+ });+ }++ return mapToLLMCompletionError(e);+}++function buildToolSet(tools: LLMToolDefinition[]): ToolSet {+ // No `execute` functions: the SDK returns tool calls to the caller instead+ // of running a tool loop, matching the LangChain bindTools behavior.+ return Object.fromEntries(+ tools.map((toolDefinition) => [+ toolDefinition.name,+ tool({+ description: toolDefinition.description,+ inputSchema: jsonSchema(+ toolDefinition.parameters as Parameters<typeof jsonSchema>[0],+ ),+ }),+ ]),+ );+}++function toFlexibleSchema(schema: ZodType | LLMJSONSchema) {+ // The standard-schema marker also catches zod schemas constructed from a+ // different zod copy, where instanceof would fail.+ const isStandardSchema =+ schema instanceof ZodType || "~standard" in (schema as object);+ return isStandardSchema+ ? (schema as ZodType)+ : jsonSchema(schema as Parameters<typeof jsonSchema>[0]);+}++function executeStreaming(args: {+ baseOptions: BaseCallOptions;+ timeoutMs: number;+ capture: AiSdkTelemetryCapture | undefined;+ runInTraceContext: <T>(fn: () => T) => T;+}): IterableReadableStream<Uint8Array> {+ const { baseOptions, timeoutMs, capture, runInTraceContext } = args;++ async function* byteStream(): AsyncGenerator<Uint8Array> {+ const encoder = new TextEncoder();+ let completedText = "";+ try {+ const result = runInTraceContext(() => streamText(baseOptions));+ for await (const textChunk of result.textStream) {+ completedText += textChunk;++ yield encoder.encode(textChunk);+ }+ capture?.setRootOutput(completedText);+ } catch (e) {+ const completionError = toCompletionError(e, timeoutMs);+ capture?.setRootError(completionError);+ throw completionError;+ } finally {+ await capture?.flush();+ }+ }++ return IterableReadableStream.fromAsyncGenerator(byteStream());+}diff --git a/packages/shared/src/server/llm/ai-sdk/messages.ts b/packages/shared/src/server/llm/ai-sdk/messages.tsnew file mode 100644index 0000000000..87e430e940--- /dev/null+++ b/packages/shared/src/server/llm/ai-sdk/messages.ts@@ -0,0 +1,121 @@+import type { AssistantContent, ModelMessage } from "ai";++import { LLMCompletionError } from "../errors";+import {+ ChatMessage,+ ChatMessageRole,+ ChatMessageType,+ LLMToolCall,+} from "../types";++// Helper function to safely stringify content+const safeStringify = (content: unknown): string => {+ try {+ return JSON.stringify(content);+ } catch {+ return "[Unserializable content]";+ }+};++const toSafeContent = (content: unknown): string =>+ typeof content === "string" ? content : safeStringify(content);++/**+ * Maps Langfuse `ChatMessage[]` to AI SDK `ModelMessage[]`, mirroring the+ * LangChain mapping in `fetchLLMCompletion`:+ * - the first system/developer message becomes `system`, later ones `user`+ * - non-string content is safely JSON-stringified+ * - messages with empty content are dropped unless they carry tool calls+ * - tool results resolve their `toolName` from the preceding assistant+ * tool-call messages; orphan tool results fail fast as a non-retryable+ * error instead of a provider-side 400+ */+export function mapChatMessagesToModelMessages(+ messages: ChatMessage[],+): ModelMessage[] {+ const toolCallIdToName = new Map<string, string>();+ for (const message of messages) {+ if (message.type === ChatMessageType.AssistantToolCall) {+ for (const toolCall of message.toolCalls as LLMToolCall[]) {+ toolCallIdToName.set(toolCall.id, toolCall.name);+ }+ }+ }++ const modelMessages: ModelMessage[] = [];++ messages.forEach((message, idx) => {+ const safeContent = toSafeContent(message.content);++ if (message.type === ChatMessageType.AssistantToolCall) {+ const content: AssistantContent = [+ ...(safeContent.length > 0+ ? [{ type: "text" as const, text: safeContent }]+ : []),+ ...(message.toolCalls as LLMToolCall[]).map((toolCall) => ({+ type: "tool-call" as const,+ toolCallId: toolCall.id,+ toolName: toolCall.name,+ input: toolCall.args,+ })),+ ];+ if (content.length === 0) return; // mirror empty-content filter+ modelMessages.push({ role: "assistant", content });++ return;+ }++ if (message.type === ChatMessageType.ToolResult) {+ const toolName = toolCallIdToName.get(message.toolCallId);++ if (toolName === undefined) {+ throw new LLMCompletionError({+ message: `Tool result references unknown tool call id: ${message.toolCallId}`,+ responseStatusCode: 400,+ isRetryable: false,+ });+ }++ if (safeContent.length === 0) return; // mirror empty-content filter++ modelMessages.push({+ role: "tool",+ content: [+ {+ type: "tool-result",+ toolCallId: message.toolCallId,+ toolName,+ output: { type: "text", value: safeContent },+ },+ ],+ });++ return;+ }++ if (safeContent.length === 0) return; // mirror empty-content filter++ if (message.role === ChatMessageRole.User) {+ modelMessages.push({ role: "user", content: safeContent });++ return;+ }++ if (+ message.role === ChatMessageRole.System ||+ message.role === ChatMessageRole.Developer+ ) {+ modelMessages.push(+ idx === 0+ ? { role: "system", content: safeContent }+ : { role: "user", content: safeContent },+ );++ return;+ }++ modelMessages.push({ role: "assistant", content: safeContent });+ });++ return modelMessages;+}diff --git a/packages/shared/src/server/llm/ai-sdk/providers/openai.test.ts b/packages/shared/src/server/llm/ai-sdk/providers/openai.test.tsnew file mode 100644index 0000000000..e668057853--- /dev/null+++ b/packages/shared/src/server/llm/ai-sdk/providers/openai.test.ts@@ -0,0 +1,72 @@+import { describe, expect, it } from "vitest";++import { translateOpenAIProviderOptions } from "./openai";++describe("translateOpenAIProviderOptions", () => {+ it("returns undefined for empty input", () => {+ expect(translateOpenAIProviderOptions(undefined)).toEqual({+ ok: true,+ value: undefined,+ });+ expect(translateOpenAIProviderOptions({})).toEqual({+ ok: true,+ value: undefined,+ });+ });++ it("translates snake_case OpenAI body params to AI SDK camelCase", () => {+ const result = translateOpenAIProviderOptions({+ reasoning_effort: "high",+ service_tier: "flex",+ parallel_tool_calls: false,+ store: true,+ });++ expect(result).toEqual({+ ok: true,+ value: {+ reasoningEffort: "high",+ serviceTier: "flex",+ parallelToolCalls: false,+ store: true,+ },+ });+ });++ it("passes through camelCase keys unchanged", () => {+ const result = translateOpenAIProviderOptions({+ reasoningEffort: "low",+ textVerbosity: "high",+ });++ expect(result).toEqual({+ ok: true,+ value: { reasoningEffort: "low", textVerbosity: "high" },+ });+ });++ it("merges a nested openai object verbatim", () => {+ const result = translateOpenAIProviderOptions({+ openai: { reasoningEffort: "medium", store: false },+ reasoning_effort: "high",+ });++ expect(result).toEqual({+ ok: true,+ value: { reasoningEffort: "high", store: false },+ });+ });++ it("rejects unknown keys instead of silently dropping them", () => {+ const result = translateOpenAIProviderOptions({+ reasoning_effort: "high",+ response_format: { type: "json_object" },+ some_custom_param: 1,+ });++ expect(result).toEqual({+ ok: false,+ unknownKeys: ["response_format", "some_custom_param"],+ });+ });+});diff --git a/packages/shared/src/server/llm/ai-sdk/providers/openai.ts b/packages/shared/src/server/llm/ai-sdk/providers/openai.tsnew file mode 100644index 0000000000..284b28e46d--- /dev/null+++ b/packages/shared/src/server/llm/ai-sdk/providers/openai.ts@@ -0,0 +1,108 @@+import { createOpenAI } from "@ai-sdk/openai";+import type { LanguageModel } from "ai";++import type { ModelParams } from "../../types";+import { processOpenAIBaseURL } from "../../utils";++export type OpenAIApiMode = "responses" | "chat-completions";++export function buildOpenAIModel(params: {+ modelParams: ModelParams;+ apiKey: string;+ baseURL?: string | null;+ extraHeaders?: Record<string, string>;+ apiMode: OpenAIApiMode;+ fetch: typeof fetch;+}): LanguageModel {+ const { apiKey, baseURL, extraHeaders, apiMode, modelParams } = params;++ const processedBaseURL = processOpenAIBaseURL({+ url: baseURL,+ modelName: modelParams.model,+ });++ const provider = createOpenAI({+ apiKey,+ baseURL: processedBaseURL ?? undefined,+ headers: extraHeaders,+ fetch: params.fetch,+ });++ // Chat Completions is the default; the Responses API is opt-in via the+ // connection's useResponsesApi config. The provider maps maxOutputTokens to+ // max_completion_tokens for reasoning models (o*/gpt-5*) on its own.+ return apiMode === "responses"+ ? provider.responses(modelParams.model)+ : provider.chat(modelParams.model);+}++/**+ * Translation of Langfuse `modelParams.providerOptions` to AI SDK OpenAI+ * provider options.+ *+ * The LangChain engine merges `providerOptions` verbatim into the request body+ * (`modelKwargs`), so users configured snake_case OpenAI body params. The AI+ * SDK instead accepts a typed, camelCase whitelist under+ * `providerOptions.openai` and silently drops unknown keys. Silent dropping is+ * unacceptable: any key we cannot translate makes the dispatcher decline to+ * LangChain (with a recorded reason) instead.+ */+const OPENAI_PROVIDER_OPTION_KEY_MAP: Record<string, string> = {+ // snake_case (OpenAI request body, as used with LangChain modelKwargs)+ reasoning_effort: "reasoningEffort",+ service_tier: "serviceTier",+ parallel_tool_calls: "parallelToolCalls",+ logit_bias: "logitBias",+ max_completion_tokens: "maxCompletionTokens",+ text_verbosity: "textVerbosity",+ verbosity: "textVerbosity",+ store: "store",+ user: "user",+ // camelCase (already AI SDK-shaped)+ reasoningEffort: "reasoningEffort",+ serviceTier: "serviceTier",+ parallelToolCalls: "parallelToolCalls",+ logitBias: "logitBias",+ maxCompletionTokens: "maxCompletionTokens",+ textVerbosity: "textVerbosity",+};++export type TranslatedProviderOptions =+ | { ok: true; value: Record<string, unknown> | undefined }+ | { ok: false; unknownKeys: string[] };++export function translateOpenAIProviderOptions(+ providerOptions: Record<string, unknown> | undefined,+): TranslatedProviderOptions {+ if (!providerOptions || Object.keys(providerOptions).length === 0) {+ return { ok: true, value: undefined };+ }++ const translated: Record<string, unknown> = {};+ const unknownKeys: string[] = [];++ for (const [key, value] of Object.entries(providerOptions)) {+ if (key === "openai" && typeof value === "object" && value !== null) {+ // Nested `openai` object is treated as already AI SDK-shaped.+ Object.assign(translated, value);+ continue;+ }++ const mappedKey = OPENAI_PROVIDER_OPTION_KEY_MAP[key];+ if (mappedKey === undefined) {+ unknownKeys.push(key);+ continue;+ }++ translated[mappedKey] = value;+ }++ if (unknownKeys.length > 0) {+ return { ok: false, unknownKeys };+ }++ return {+ ok: true,+ value: Object.keys(translated).length > 0 ? translated : undefined,+ };+}diff --git a/packages/shared/src/server/llm/ai-sdk/resolveLlmExecutionDecision.ts b/packages/shared/src/server/llm/ai-sdk/resolveLlmExecutionDecision.tsnew file mode 100644index 0000000000..c4d6046484--- /dev/null+++ b/packages/shared/src/server/llm/ai-sdk/resolveLlmExecutionDecision.ts@@ -0,0 +1,82 @@+import { getCurrentSpan } from "../../instrumentation";+import { OpenAIConfigSchema } from "../../../interfaces/customLLMProviderConfigSchemas";+import type { LLMConnectionConfig } from "../../../interfaces/customLLMProviderConfigSchemas";+import { LLMAdapter } from "../types";+import {+ translateOpenAIProviderOptions,+ type OpenAIApiMode,+} from "./providers/openai";+import { logger } from "../../logger";++export type LlmExecutionDecision =+ | {+ engine: "ai-sdk";+ aiSdkAdapter: "openai";+ openAIApiMode: OpenAIApiMode;+ translatedProviderOptions?: Record<string, unknown>;+ }+ | {+ engine: "langchain-js";+ };++/**+ * Decides which execution engine handles an LLM completion. AI SDK is only+ * selected when the adapter is rolled out via+ * `LANGFUSE_LLM_COMPLETION_AI_SDK_ADAPTERS` AND the call has no requirement+ * the AI SDK path cannot honor yet. Every decline for a rolled-out adapter+ * carries a reason for observability.+ */+export function resolveLlmExecutionDecision(params: {+ adapter: LLMAdapter;+ providerOptions?: Record<string, unknown>;+ llmConnectionConfig?: LLMConnectionConfig | null;+ enabledAdapters: readonly string[];+}): LlmExecutionDecision {+ const { adapter, providerOptions, llmConnectionConfig, enabledAdapters } =+ params;++ if (adapter !== LLMAdapter.OpenAI || !enabledAdapters.includes("openai")) {+ return { engine: "langchain-js" };+ }++ const translated = translateOpenAIProviderOptions(providerOptions);+ if (!translated.ok) {+ logger.warn(+ `Cannot translate provider options: ${translated.unknownKeys.join(",")}`,+ );++ return { engine: "langchain-js" };+ }++ const openAIConfig = OpenAIConfigSchema.parse(llmConnectionConfig ?? {});++ return {+ engine: "ai-sdk",+ aiSdkAdapter: "openai",+ // Chat Completions stays the default: flipping to the Responses API would+ // break OpenAI-compatible proxies configured via custom baseURL.+ openAIApiMode: openAIConfig.useResponsesApi+ ? "responses"+ : "chat-completions",+ translatedProviderOptions: translated.value,+ };+}++/**+ * Records the execution-engine decision on the current active span (e.g. the+ * worker's `eval.call-llm` span), so engine rollout can be sliced in+ * observability tooling without re-deriving the decision at call sites.+ */+export function recordLlmExecutionDecision(+ decision: LlmExecutionDecision,+): void {+ const span = getCurrentSpan();+ if (!span) return;++ span.setAttribute("langfuse.llm.execution_engine", decision.engine);++ if (decision.engine === "ai-sdk") {+ span.setAttribute("langfuse.llm.ai_sdk.adapter", decision.aiSdkAdapter);+ span.setAttribute("langfuse.llm.openai.api_mode", decision.openAIApiMode);+ }+}diff --git a/packages/shared/src/server/llm/ai-sdk/telemetry.test.ts b/packages/shared/src/server/llm/ai-sdk/telemetry.test.tsnew file mode 100644index 0000000000..4c42515e0c--- /dev/null+++ b/packages/shared/src/server/llm/ai-sdk/telemetry.test.ts@@ -0,0 +1,148 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++import type { TraceSinkParams } from "../types";+import { createAiSdkTelemetryCapture } from "./telemetry";++const publishToOtelIngestionQueue = vi.fn().mockResolvedValue(undefined);+const processorConstructor = vi.fn();++vi.mock("../../otel/OtelIngestionProcessor", () => ({+ OtelIngestionProcessor: class {+ constructor(config: unknown) {+ processorConstructor(config);+ }+ publishToOtelIngestionQueue = publishToOtelIngestionQueue;+ },+}));++const VALID_TRACE_ID = "0af7651916cd43dd8448eb211c80319c";++const traceSinkParams: TraceSinkParams = {+ targetProjectId: "project-1",+ traceId: VALID_TRACE_ID,+ traceName: "Execute evaluator: helpfulness",+ environment: "langfuse-llm-judge",+ userId: "user-1",+ metadata: { jobId: "job-1" },+};++beforeEach(() => {+ vi.clearAllMocks();+});++describe("createAiSdkTelemetryCapture", () => {+ it("refuses non-langfuse environments (eval-loop safeguard)", () => {+ expect(+ createAiSdkTelemetryCapture({+ traceSinkParams: { ...traceSinkParams, environment: "production" },+ }),+ ).toBeUndefined();+ });++ it("refuses invalid W3C trace ids", () => {+ expect(+ createAiSdkTelemetryCapture({+ traceSinkParams: { ...traceSinkParams, traceId: "not-a-trace-id" },+ }),+ ).toBeUndefined();++ expect(+ createAiSdkTelemetryCapture({+ traceSinkParams: { ...traceSinkParams, traceId: "0".repeat(32) },+ }),+ ).toBeUndefined();+ });++ it("publishes the root span with the Langfuse trace id and attributes", async () => {+ const capture = createAiSdkTelemetryCapture({+ traceSinkParams: {+ ...traceSinkParams,+ prompt: { name: "p", version: 3 },+ },+ });+ expect(capture).toBeDefined();++ await capture!.run(async () => "done");+ await capture!.flush();++ expect(processorConstructor).toHaveBeenCalledWith(+ expect.objectContaining({+ projectId: "project-1",+ sdkName: "langfuse-internal-ai-sdk",+ // Ensures the queue consumer parses these events with the internal+ // ingestion schema; the public schema strips the "langfuse-"+ // environment prefix and would bypass the eval-loop guard.+ isLangfuseInternal: true,+ // Ensures the direct events write runs, which is the only path that+ // materializes langfuse.experiment.* into experiment_* columns.+ ingestionVersion: "4",+ }),+ );+ expect(publishToOtelIngestionQueue).toHaveBeenCalledTimes(1);++ const resourceSpans = publishToOtelIngestionQueue.mock.calls[0][0];+ const spans = resourceSpans.flatMap((rs: any) =>+ rs.scopeSpans.flatMap((ss: any) => ss.spans),+ );+ expect(spans).toHaveLength(1);++ const rootSpan = spans[0];+ expect(rootSpan.traceId.toLowerCase()).toBe(VALID_TRACE_ID);+ expect(rootSpan.name).toBe("Execute evaluator: helpfulness");+ expect(rootSpan.parentSpanId ?? "").toBe("");++ const attributes = Object.fromEntries(+ rootSpan.attributes.map((attr: any) => [+ attr.key,+ attr.value.stringValue ?? attr.value,+ ]),+ );+ expect(attributes["langfuse.environment"]).toBe("langfuse-llm-judge");+ expect(attributes["langfuse.trace.name"]).toBe(+ "Execute evaluator: helpfulness",+ );+ expect(attributes["user.id"]).toBe("user-1");+ expect(attributes["langfuse.trace.metadata"]).toBe(+ JSON.stringify({ jobId: "job-1" }),+ );+ });++ it("is idempotent and never publishes twice", async () => {+ const capture = createAiSdkTelemetryCapture({+ traceSinkParams,+ });++ await capture!.flush();+ await capture!.flush();++ expect(publishToOtelIngestionQueue).toHaveBeenCalledTimes(1);+ });++ it("never throws when publishing fails", async () => {+ publishToOtelIngestionQueue.mockRejectedValueOnce(new Error("queue down"));++ const capture = createAiSdkTelemetryCapture({+ traceSinkParams,+ });++ await expect(capture!.flush()).resolves.toBeUndefined();+ });++ it("marks the root span as errored via setRootError", async () => {+ const capture = createAiSdkTelemetryCapture({+ traceSinkParams,+ });++ capture!.setRootError(new Error("completion failed"));+ await capture!.flush();++ const resourceSpans = publishToOtelIngestionQueue.mock.calls[0][0];+ const rootSpan = resourceSpans[0].scopeSpans[0].spans[0];++ // OTLP JSON status code 2 = ERROR+ expect(rootSpan.status).toMatchObject({+ code: 2,+ message: "completion failed",+ });+ });+});diff --git a/packages/shared/src/server/llm/ai-sdk/telemetry.ts b/packages/shared/src/server/llm/ai-sdk/telemetry.tsnew file mode 100644index 0000000000..cabf52ca23--- /dev/null+++ b/packages/shared/src/server/llm/ai-sdk/telemetry.ts@@ -0,0 +1,475 @@+import { randomBytes } from "node:crypto";++import type { Telemetry } from "ai";++import {+ type Attributes,+ type Tracer,+ context,+ ROOT_CONTEXT,+ SpanStatusCode,+ trace,+ type Span,+} from "@opentelemetry/api";+import { JsonTraceSerializer } from "@opentelemetry/otlp-transformer";+import { resourceFromAttributes } from "@opentelemetry/resources";+import {+ BasicTracerProvider,+ InMemorySpanExporter,+ SimpleSpanProcessor,+} from "@opentelemetry/sdk-trace-base";+import type { TelemetryOptions } from "ai";++import { stringifyValue } from "../../../utils/stringChecks";+import { traceException } from "../../instrumentation";+import { logger } from "../../logger";+import { LangfuseOtelSpanAttributes } from "../../otel/attributes";+import { OtelIngestionProcessor } from "../../otel/OtelIngestionProcessor";+import type { InternalTraceExperimentContext } from "../internalTraceEvents";+import type { TraceSinkParams } from "../types";++const W3C_TRACE_ID_PATTERN = /^[0-9a-f]{32}$/;+const INTERNAL_SDK_NAME = "langfuse-internal-ai-sdk";+const INTERNAL_TRACER_SCOPE = "langfuse-internal-llm-completion";++export type AiSdkTelemetryCapture = {+ /** Pass to `generateText`/`streamText` as the `telemetry` option. */+ telemetry: TelemetryOptions;+ /**+ * Runs `fn` with the internal root span active, so AI SDK telemetry spans+ * nest under it. Requires a registered OTel context manager for propagation+ * across awaits (present in web and worker runtimes).+ */+ run: <T>(fn: () => T) => T;+ /**+ * Records the completion result as the root span's (and trace's) output.+ * Call before `flush`. The root observation's input/output feed eval+ * variable mapping for experiment run items, mirroring the root event+ * record of the LangChain internal-tracing path.+ */+ setRootOutput: (output: unknown) => void;+ /**+ * Marks the root span (and thus the internal trace) as failed. Call before+ * `flush`, so a failed completion is visible as an ERROR-level root+ * observation instead of a bare 0-duration span.+ */+ setRootError: (error: unknown) => void;+ /**+ * Ends the root span and publishes all captured spans to the regular OTel+ * ingestion pipeline (same S3 + queue path as the public+ * /api/public/otel/v1/traces endpoint). Idempotent; never throws.+ */+ flush: () => Promise<void>;+};++/**+ * Per-call isolated OTel capture for AI SDK executions.+ *+ * A dedicated `BasicTracerProvider` (never globally registered) buffers spans+ * in memory. Its id generator returns `traceSinkParams.traceId` for root+ * spans, so the internal root span carries the Langfuse trace ID without any+ * span rewriting, and all child spans inherit it via context. After the call,+ * spans are serialized to OTLP JSON and submitted through+ * `OtelIngestionProcessor.publishToOtelIngestionQueue` — internal traces get+ * exactly the same ingestion treatment as user traces.+ *+ * For experiment run items (`eventsWriter.experimentContext` present), the+ * `langfuse.experiment.*` attributes are set on every captured span with the+ * root span as `experiment_item_root_observation_id`, so the OTel ingestion+ * pipeline materializes the same experiment linkage as the LangChain path's+ * `buildInternalTraceEventInputs` — including queue-side scheduling of+ * experiment observation evals.+ *+ * Returns `undefined` (no tracing) when the environment is not+ * langfuse-prefixed — the same eval-loop safeguard as the LangChain path —+ * or when the trace ID is not a valid W3C trace ID.+ */+export function createAiSdkTelemetryCapture(params: {+ traceSinkParams: TraceSinkParams;+ /** Recorded as the root span's (and trace's) input. */+ rootInput?: unknown;+}): AiSdkTelemetryCapture | undefined {+ const { traceSinkParams, rootInput } = params;++ // Safeguard: All internal traces must use LangfuseInternalTraceEnvironment enum values+ // This prevents infinite eval loops (user trace → eval → eval trace → another eval)+ // See corresponding check in worker/src/features/evaluation/evalService.ts createEvalJobs()+ if (!traceSinkParams.environment?.startsWith("langfuse")) {+ logger.warn(+ "Skipping trace creation: internal traces must use LangfuseInternalTraceEnvironment enum",+ {+ environment: traceSinkParams.environment,+ traceId: traceSinkParams.traceId,+ },+ );+ return undefined;+ }++ const traceId = traceSinkParams.traceId.toLowerCase();+ if (!W3C_TRACE_ID_PATTERN.test(traceId) || traceId === "0".repeat(32)) {+ logger.warn(+ "Skipping trace creation: trace id is not a valid W3C trace id",+ { traceId: traceSinkParams.traceId },+ );+ return undefined;+ }++ const exporter = new InMemorySpanExporter();+ const tracerProvider = new BasicTracerProvider({+ // The environment must reach every captured span (not just the root), or+ // the resulting observations fall back to the "default" environment and+ // leak into user-facing views.+ resource: resourceFromAttributes({+ [LangfuseOtelSpanAttributes.ENVIRONMENT]: traceSinkParams.environment,+ }),+ spanProcessors: [new SimpleSpanProcessor(exporter)],+ // Root spans (no parent in context) receive the Langfuse trace ID; child+ // spans inherit it through context propagation.+ idGenerator: {+ generateTraceId: () => traceId,+ generateSpanId: () => randomBytes(8).toString("hex"),+ },+ });+ const tracer = tracerProvider.getTracer(INTERNAL_TRACER_SCOPE);++ const serializedInput =+ rootInput !== undefined ? stringifyValue(rootInput) : undefined;++ const rootSpan: Span = tracer.startSpan(+ traceSinkParams.traceName,+ {+ attributes: {+ [LangfuseOtelSpanAttributes.TRACE_NAME]: traceSinkParams.traceName,+ [LangfuseOtelSpanAttributes.ENVIRONMENT]: traceSinkParams.environment,+ ...(traceSinkParams.userId+ ? {+ [LangfuseOtelSpanAttributes.TRACE_USER_ID]:+ traceSinkParams.userId,+ }+ : {}),+ ...(traceSinkParams.metadata+ ? {+ [LangfuseOtelSpanAttributes.TRACE_METADATA]: JSON.stringify(+ traceSinkParams.metadata,+ ),+ }+ : {}),+ ...(serializedInput !== undefined+ ? {+ [LangfuseOtelSpanAttributes.OBSERVATION_INPUT]: serializedInput,+ }+ : {}),+ },+ },+ // ROOT_CONTEXT detaches from the server's own observability trace.+ ROOT_CONTEXT,+ );+ const activeContext = trace.setSpan(ROOT_CONTEXT, rootSpan);++ const experimentContext = traceSinkParams.eventsWriter?.experimentContext;+ const experimentAttributes = experimentContext+ ? buildExperimentAttributes(+ experimentContext,+ rootSpan.spanContext().spanId,+ )+ : undefined;+ if (experimentAttributes) {+ rootSpan.setAttributes(experimentAttributes);+ }++ const promptAttributes = traceSinkParams.prompt+ ? {+ // Link the LLM generation spans to the resolved Langfuse prompt,+ // mirroring prepareInternalTraceEvents on the LangChain path.+ [LangfuseOtelSpanAttributes.OBSERVATION_PROMPT_NAME]:+ traceSinkParams.prompt.name,+ [LangfuseOtelSpanAttributes.OBSERVATION_PROMPT_VERSION]:+ traceSinkParams.prompt.version,+ }+ : undefined;++ const otelIntegration = createGenerationSpanTelemetry({+ tracer,+ attributes: {+ // Experiment linkage goes on every span, matching the LangChain path+ // where buildInternalTraceEventInputs tags all event records.+ ...(experimentAttributes ?? {}),+ ...(promptAttributes ?? {}),+ [LangfuseOtelSpanAttributes.TRACE_NAME]: traceSinkParams.traceName,+ [LangfuseOtelSpanAttributes.ENVIRONMENT]: traceSinkParams.environment,+ ...(traceSinkParams.userId+ ? {+ [LangfuseOtelSpanAttributes.TRACE_USER_ID]: traceSinkParams.userId,+ }+ : {}),+ },+ });++ let flushed = false;++ const setRootOutput = (output: unknown): void => {+ if (flushed || output === undefined) return;+ const serializedOutput = stringifyValue(output);++ rootSpan.setAttribute(+ LangfuseOtelSpanAttributes.OBSERVATION_OUTPUT,+ serializedOutput,+ );+ };++ const setRootError = (error: unknown): void => {+ if (flushed) return;+ rootSpan.setStatus({+ code: SpanStatusCode.ERROR,+ message: error instanceof Error ? error.message : String(error),+ });+ if (error instanceof Error) rootSpan.recordException(error);+ };++ const flush = async (): Promise<void> => {+ if (flushed) return;+ flushed = true;++ try {+ rootSpan.end();+ await tracerProvider.forceFlush();++ const spans = exporter.getFinishedSpans();+ // Without a registered OTel context manager, AI SDK spans lose the+ // active root span and land on a random trace ID. Publish only spans on+ // the expected trace so nothing leaks into foreign traces.+ const matchingSpans = spans.filter(+ (span) => span.spanContext().traceId === traceId,+ );++ if (matchingSpans.length < spans.length) {+ logger.warn(+ "Dropping AI SDK telemetry spans outside the internal trace; is an OTel context manager registered?",+ {+ traceId,+ droppedSpans: spans.length - matchingSpans.length,+ },+ );+ }+ if (matchingSpans.length === 0) return;++ const serialized = JsonTraceSerializer.serializeRequest(matchingSpans);+ if (!serialized) return;++ const { resourceSpans } = JSON.parse(+ new TextDecoder().decode(serialized),+ );++ if (!resourceSpans || resourceSpans.length === 0) return;++ const processor = new OtelIngestionProcessor({+ projectId: traceSinkParams.targetProjectId,+ publicKey: "", // internal ingestion has no API key; mirrors internal event writes+ sdkName: INTERNAL_SDK_NAME,+ sdkVersion: "unknown",+ // Opt into the v4-native direct events write like a modern SDK batch:+ // only that path runs processToEvent -> createEventRecord, which is+ // the sole extractor of langfuse.experiment.* into experiment_*+ // columns. Without it, dual-write mode routes internal batches+ // (unknown SDK, no scope version) through legacy forwarding and+ // experiment run items lose their linkage in events_full/v4 views.+ // Legacy tables are still dual-written per v4WritesToLegacyTables.+ ingestionVersion: "4",+ // The consumer must parse these events with the internal ingestion+ // schema; the public schema strips the "langfuse-" environment prefix,+ // exposing internal traces as user environments and bypassing the+ // trace-upsert eval-loop guard.+ isLangfuseInternal: true,+ });++ await processor.publishToOtelIngestionQueue(resourceSpans);+ } catch (e) {+ traceException(e);+ logger.error("Failed to publish AI SDK internal telemetry", {+ error: e,+ traceId,+ projectId: traceSinkParams.targetProjectId,+ });+ } finally {+ await tracerProvider.shutdown().catch(() => undefined);+ }+ };++ return {+ telemetry: { isEnabled: true, integrations: [otelIntegration] },+ run: (fn) => context.with(activeContext, fn),+ setRootOutput,+ setRootError,+ flush,+ };+}++/**+ * Minimal AI SDK telemetry integration for Langfuse-internal LLM completions.+ */+export function createGenerationSpanTelemetry(params: {+ tracer: Tracer;+ /**+ * Extra attributes for every generation span (Langfuse prompt link,+ * experiment linkage).+ */+ attributes?: Attributes;+}): Telemetry {+ const { tracer, attributes } = params;+ const openSpans = new Map<string, Span>();++ const endAllOpenSpans = (error?: unknown): void => {+ for (const span of openSpans.values()) {+ if (error !== undefined) {+ span.setStatus({+ code: SpanStatusCode.ERROR,+ message: error instanceof Error ? error.message : String(error),+ });++ if (error instanceof Error) span.recordException(error);+ }+ span.end();+ }+ openSpans.clear();+ };++ return {+ onLanguageModelCallStart(event) {+ // Defensive: a lingering span for this call id means its end event never+ // fired (e.g. a retried attempt) — close it before starting the next.+ openSpans.get(event.callId)?.end();++ const span = tracer.startSpan(+ `chat ${event.modelId}`,+ {+ attributes: {+ "gen_ai.provider.name": event.provider,+ "gen_ai.request.model": event.modelId,+ ...definedNumberAttributes({+ "gen_ai.request.max_tokens": event.maxOutputTokens,+ "gen_ai.request.temperature": event.temperature,+ "gen_ai.request.top_p": event.topP,+ }),+ ...(event.messages !== undefined+ ? { "gen_ai.input.messages": safeJsonStringify(event.messages) }+ : {}),+ ...(event.tools && event.tools.length > 0+ ? { "gen_ai.tool.definitions": safeJsonStringify(event.tools) }+ : {}),+ ...attributes,+ },+ },+ context.active(),+ );++ openSpans.set(event.callId, span);+ },++ onLanguageModelCallEnd(event) {+ const span = openSpans.get(event.callId);++ if (!span) return;++ openSpans.delete(event.callId);++ span.setAttributes({+ "gen_ai.response.finish_reasons": [event.finishReason],+ ...(event.responseId ? { "gen_ai.response.id": event.responseId } : {}),+ ...definedNumberAttributes({+ "gen_ai.usage.input_tokens": event.usage.inputTokens,+ "gen_ai.usage.output_tokens": event.usage.outputTokens,+ "gen_ai.usage.cache_read.input_tokens":+ event.usage.inputTokenDetails?.cacheReadTokens,+ "gen_ai.usage.cache_creation.input_tokens":+ event.usage.inputTokenDetails?.cacheWriteTokens,+ }),+ "gen_ai.output.messages": safeJsonStringify([+ { role: "assistant", content: event.content },+ ]),+ });+ span.end();+ },++ onError(error) {+ endAllOpenSpans(error);+ },++ onAbort() {+ endAllOpenSpans();+ },++ // Run the provider call with the generation span active, so any future+ // nested instrumentation parents correctly.+ executeLanguageModelCall({ callId, execute }) {+ const span = openSpans.get(callId);+ if (!span) return execute();++ return context.with(trace.setSpan(context.active(), span), execute);+ },+ };+}++function definedNumberAttributes(+ attributes: Record<string, number | undefined>,+): Attributes {+ return Object.fromEntries(+ Object.entries(attributes).filter(([, value]) => value !== undefined),+ ) as Attributes;+}++function safeJsonStringify(value: unknown): string {+ try {+ return JSON.stringify(value);+ } catch {+ return "[Unserializable content]";+ }+}+/**+ * Maps the internal experiment context to the `langfuse.experiment.*` span+ * attributes that `OtelIngestionProcessor.extractExperimentFields` reads,+ * producing the same event-record fields as the LangChain path's+ * `buildInternalTraceEventInputs`.+ */+function buildExperimentAttributes(+ experimentContext: InternalTraceExperimentContext,+ rootSpanId: string,+): Record<string, string> {+ return {+ [LangfuseOtelSpanAttributes.EXPERIMENT_ID]: experimentContext.id,+ [LangfuseOtelSpanAttributes.EXPERIMENT_NAME]: experimentContext.name,+ [LangfuseOtelSpanAttributes.EXPERIMENT_DATASET_ID]:+ experimentContext.datasetId,+ [LangfuseOtelSpanAttributes.EXPERIMENT_ITEM_ID]: experimentContext.itemId,+ [LangfuseOtelSpanAttributes.EXPERIMENT_ITEM_VERSION]:+ experimentContext.itemVersion,+ [LangfuseOtelSpanAttributes.EXPERIMENT_ITEM_ROOT_OBSERVATION_ID]:+ rootSpanId,+ ...(experimentContext.description+ ? {+ [LangfuseOtelSpanAttributes.EXPERIMENT_DESCRIPTION]:+ experimentContext.description,+ }+ : {}),+ ...(experimentContext.itemExpectedOutput !== undefined &&+ experimentContext.itemExpectedOutput !== null+ ? {+ [LangfuseOtelSpanAttributes.EXPERIMENT_ITEM_EXPECTED_OUTPUT]:+ stringifyValue(experimentContext.itemExpectedOutput),+ }+ : {}),+ ...(experimentContext.metadata+ ? {+ [LangfuseOtelSpanAttributes.EXPERIMENT_METADATA]: JSON.stringify(+ experimentContext.metadata,+ ),+ }+ : {}),+ ...(experimentContext.itemMetadata+ ? {+ [LangfuseOtelSpanAttributes.EXPERIMENT_ITEM_METADATA]: JSON.stringify(+ experimentContext.itemMetadata,+ ),+ }+ : {}),+ };+}diff --git a/packages/shared/src/server/llm/ai-sdk/telemetryIntegration.test.ts b/packages/shared/src/server/llm/ai-sdk/telemetryIntegration.test.tsnew file mode 100644index 0000000000..39444b32ea--- /dev/null+++ b/packages/shared/src/server/llm/ai-sdk/telemetryIntegration.test.ts@@ -0,0 +1,289 @@+import {+ afterAll,+ beforeAll,+ beforeEach,+ describe,+ expect,+ it,+ vi,+} from "vitest";++import { context } from "@opentelemetry/api";+import { AsyncLocalStorageContextManager } from "@opentelemetry/context-async-hooks";+import { MockLanguageModelV4 } from "ai/test";+import { createOpenAI } from "@ai-sdk/openai";++import {+ ChatMessage,+ ChatMessageRole,+ ChatMessageType,+ LLMAdapter,+ type ModelParams,+ type TraceSinkParams,+} from "../types";+import { executeAiSdkCompletion } from "./executeAiSdkCompletion";++const publishToOtelIngestionQueue = vi.fn().mockResolvedValue(undefined);++vi.mock("../../otel/OtelIngestionProcessor", async (importOriginal) => {+ const actual =+ await importOriginal<typeof import("../../otel/OtelIngestionProcessor")>();+ return {+ ...actual,+ OtelIngestionProcessor: class {+ publishToOtelIngestionQueue = publishToOtelIngestionQueue;+ },+ };+});++vi.mock("@ai-sdk/openai", () => ({+ createOpenAI: vi.fn(),+}));++const VALID_TRACE_ID = "0af7651916cd43dd8448eb211c80319c";++const traceSinkParams: TraceSinkParams = {+ targetProjectId: "project-1",+ traceId: VALID_TRACE_ID,+ traceName: "Execute evaluator: helpfulness",+ environment: "langfuse-llm-judge",+};++const modelParams: ModelParams = {+ provider: "openai",+ adapter: LLMAdapter.OpenAI,+ model: "gpt-4o",+ max_tokens: 128,+};++// System-first message lists are the norm for compiled experiment prompts and+// playground calls; AI SDK v7 rejects system messages in `messages` unless+// allowSystemInMessages is set, so this shape must go through the REAL+// generateText here (regression: every experiment item failed instantly with+// InvalidPromptError and undefined output).+const messages: ChatMessage[] = [+ {+ type: ChatMessageType.System,+ role: ChatMessageRole.System,+ content: "You answer in a single word.",+ },+ { type: ChatMessageType.User, role: ChatMessageRole.User, content: "Hi" },+];++// The AI SDK OTel integration parents its spans through the active OTel+// context; production web/worker runtimes register a context manager as part+// of their tracing setup, which this test mirrors.+const contextManager = new AsyncLocalStorageContextManager();++beforeAll(() => {+ context.setGlobalContextManager(contextManager.enable());+});++afterAll(() => {+ context.disable();+});++beforeEach(() => {+ vi.clearAllMocks();+ vi.mocked(createOpenAI).mockReturnValue({+ chat: () =>+ new MockLanguageModelV4({+ provider: "openai",+ modelId: "gpt-4o",+ doGenerate: {+ content: [{ type: "text", text: "Hello there" }],+ finishReason: { unified: "stop", raw: "stop" },+ usage: {+ inputTokens: {+ total: 3,+ noCache: 3,+ cacheRead: undefined,+ cacheWrite: undefined,+ },+ outputTokens: { total: 5, text: 5, reasoning: undefined },+ },+ warnings: [],+ },+ }),+ } as never);+});++describe("AI SDK telemetry integration", () => {+ it("captures generateText spans under the Langfuse trace and converts them via the OTel ingestion pipeline", async () => {+ const result = await executeAiSdkCompletion({+ messages,+ modelParams,+ streaming: false,+ apiKey: "sk-test",+ timeoutMs: 10_000,+ fetch: globalThis.fetch,+ apiMode: "chat-completions",+ traceSinkParams,+ });++ expect(result).toBe("Hello there");+ expect(publishToOtelIngestionQueue).toHaveBeenCalledTimes(1);++ const resourceSpans = publishToOtelIngestionQueue.mock.calls[0][0];+ const spans = resourceSpans.flatMap((rs: any) =>+ rs.scopeSpans.flatMap((ss: any) => ss.spans),+ );++ // Exactly two spans: the internal root and one generation per model call+ // (the minimal telemetry integration emits no operation/step spans).+ expect(spans).toHaveLength(2);+ for (const span of spans) {+ expect(span.traceId.toLowerCase()).toBe(VALID_TRACE_ID);+ }++ const rootSpans = spans.filter((span: any) => !span.parentSpanId);+ expect(rootSpans).toHaveLength(1);+ expect(rootSpans[0].name).toBe("Execute evaluator: helpfulness");++ const generationSpan = spans.find((span: any) => span.parentSpanId);+ expect(generationSpan.name).toBe("chat gpt-4o");+ expect(generationSpan.parentSpanId).toBe(rootSpans[0].spanId);++ // The captured spans convert through the real OTel ingestion processor —+ // the same code path the public /api/public/otel/v1/traces endpoint uses.+ const { OtelIngestionProcessor } = await vi.importActual<+ typeof import("../../otel/OtelIngestionProcessor")+ >("../../otel/OtelIngestionProcessor");+ const processor = new OtelIngestionProcessor({+ projectId: "project-1",+ publicKey: "",+ sdkName: "langfuse-internal-ai-sdk",+ sdkVersion: "unknown",+ });+ // The seen-traces dedup cache is Redis-backed; CI runs shared tests+ // without a Redis service, so the lookup would hang until test timeout.+ vi.spyOn(+ processor as unknown as { getSeenTracesSet: () => Promise<Set<string>> },+ "getSeenTracesSet",+ ).mockResolvedValue(new Set());+ const events = await processor.processToIngestionEvents(resourceSpans);++ expect(events.length).toBeGreaterThan(0);++ const traceEvents = events.filter((event) =>+ event.type.startsWith("trace-"),+ );+ expect(traceEvents.length).toBeGreaterThan(0);+ const fullTraceEvent = traceEvents.find(+ (event) => (event.body as { name?: string }).name,+ );+ expect(fullTraceEvent).toBeDefined();+ expect(fullTraceEvent!.body).toMatchObject({+ id: VALID_TRACE_ID,+ name: "Execute evaluator: helpfulness",+ environment: "langfuse-llm-judge",+ });++ // The model call span materializes as a generation with usage — and it is+ // the ONLY costed observation. This is the double-costing regression+ // guard: @ai-sdk/otel put gen_ai.usage on both the operation and the+ // model-call span, doubling every internal trace's cost.+ const observationEvents = events.filter(+ (event) => !event.type.startsWith("trace-"),+ );+ const costedObservations = observationEvents.filter((event) => {+ const body = event.body as {+ model?: string;+ usageDetails?: Record<string, unknown>;+ };+ return (+ body.model !== undefined ||+ Object.keys(body.usageDetails ?? {}).length > 0+ );+ });+ expect(costedObservations).toHaveLength(1);+ const generation = costedObservations[0];+ expect(generation.type).toBe("generation-create");+ expect(generation.body).toMatchObject({+ name: "chat gpt-4o",+ model: "gpt-4o",+ usageDetails: { input: 3, output: 5 },+ environment: "langfuse-llm-judge",+ });+ });++ it("tags experiment run items so the ingestion pipeline can schedule experiment evals", async () => {+ const experimentTraceId = "1af7651916cd43dd8448eb211c80319d";++ const result = await executeAiSdkCompletion({+ messages,+ modelParams,+ streaming: false,+ apiKey: "sk-test",+ timeoutMs: 10_000,+ fetch: globalThis.fetch,+ apiMode: "chat-completions",+ traceSinkParams: {+ targetProjectId: "project-1",+ traceId: experimentTraceId,+ traceName: "dataset-run-item-abc12",+ environment: "langfuse-prompt-experiment",+ eventsWriter: {+ experimentContext: {+ id: "run-1",+ name: "run name",+ datasetId: "dataset-1",+ itemId: "item-1",+ itemVersion: "2026-01-01T00:00:00.000Z",+ itemExpectedOutput: { answer: 42 },+ metadata: { source: "test" },+ },+ write: async () => {},+ },+ },+ });++ expect(result).toBe("Hello there");+ expect(publishToOtelIngestionQueue).toHaveBeenCalledTimes(1);+ const resourceSpans = publishToOtelIngestionQueue.mock.calls[0][0];++ // Convert through the real processor exactly like the OTel ingestion+ // queue's eval-scheduling step (processToEvent -> createEventRecord).+ const { OtelIngestionProcessor } = await vi.importActual<+ typeof import("../../otel/OtelIngestionProcessor")+ >("../../otel/OtelIngestionProcessor");+ const eventInputs = new OtelIngestionProcessor({+ projectId: "project-1",+ publicKey: "",+ sdkName: "langfuse-internal-ai-sdk",+ sdkVersion: "unknown",+ }).processToEvent(resourceSpans);++ const roots = eventInputs.filter((input: any) => !input.parentSpanId);+ expect(roots).toHaveLength(1);+ const root = roots[0];++ // The run-item root observation is self-referencing, which is what the+ // queue-side guard requires to schedule experiment observation evals.+ expect(root.environment).toBe("langfuse-prompt-experiment");+ expect(root.experimentId).toBe("run-1");+ expect(root.experimentDatasetId).toBe("dataset-1");+ expect(root.experimentItemId).toBe("item-1");+ expect(root.experimentItemRootSpanId).toBe(root.spanId);+ expect(root.experimentItemExpectedOutput).toBe(+ JSON.stringify({ answer: 42 }),+ );++ // The root observation carries the completion IO that experiment eval+ // variable mapping reads.+ expect(root.input).toBeDefined();+ expect(root.output).toBeDefined();+ expect(String(root.output)).toContain("Hello there");++ // Child spans point at the root and never at themselves, so only the+ // run-item root can pass the queue-side eval guard. With the minimal+ // telemetry integration there is exactly one child: the generation.+ const children = eventInputs.filter((input: any) => input.parentSpanId);+ expect(children).toHaveLength(1);+ for (const child of children) {+ expect(child.environment).toBe("langfuse-prompt-experiment");+ expect(child.experimentItemRootSpanId).toBe(root.spanId);+ expect(child.spanId).not.toBe(root.spanId);+ }+ });+});diff --git a/packages/shared/src/server/llm/completionErrorMapping.ts b/packages/shared/src/server/llm/completionErrorMapping.tsnew file mode 100644index 0000000000..7d6ef36449--- /dev/null+++ b/packages/shared/src/server/llm/completionErrorMapping.ts@@ -0,0 +1,179 @@+import { ContextOverflowError } from "@langchain/core/errors";++import { LLMCompletionError } from "./errors";++const NON_RETRYABLE_LLM_ERROR_PATTERNS = [+ "Request timed out",+ "is not valid JSON",+ "Unterminated string in JSON at position",+ "TypeError",+ "reached the end of its life",+ "prompt is too long",+ // secureLlmFetch validation failures: synchronous, status-less errors that+ // would otherwise default to 500 + retryable and burn the eval-retry budget+ // on permanent config or redirect-target failures.+ "Only HTTP and HTTPS protocols are allowed",+ "Only HTTPS base URLs are allowed",+ "Blocked hostname detected",+ "Blocked IP address detected",+ "Redirect validation failed",+ "Maximum redirects",+ "Circular redirect detected",+] as const;++// Walks an error and its `.cause` chain (cycle-safe), yielding each link.+function* walkCauseChain(error: unknown): Generator<unknown> {+ const visited = new Set<unknown>();+ for (+ let current: unknown = error;+ current && !visited.has(current);+ current = (current as any).cause+ ) {+ visited.add(current);+ yield current;+ }+}++/**+ * Detects AI SDK native timeouts. `AbortSignal.timeout` (used by the SDK's+ * `timeout` option) aborts with `DOMException(..., "TimeoutError")`, which+ * carries neither a status code nor the "Request timed out" message the+ * shared retry classification keys on — callers must normalize it to the+ * canonical non-retryable timeout error.+ */+export function hasTimeoutAbortInCauseChain(error: unknown): boolean {+ for (const current of walkCauseChain(error)) {+ if ((current as { name?: string } | null)?.name === "TimeoutError") {+ return true;+ }+ }+ return false;+}++function findNonRetryableCauseMessage(error: unknown): string | undefined {+ for (const current of walkCauseChain(error)) {+ if (!(current instanceof Error)) continue;+ const message = extractCleanErrorMessage(current.message);+ if (NON_RETRYABLE_LLM_ERROR_PATTERNS.some((p) => message.includes(p))) {+ return message;+ }+ }+ return undefined;+}++function getErrorResponseStatusCode(error: unknown): number | undefined {+ for (const current of walkCauseChain(error)) {+ if (!current || typeof current !== "object") continue;+ const errorLike = current as any;+ const statusCode = [+ errorLike.response?.status,+ errorLike.status,+ errorLike.statusCode,+ // Bedrock errors have status code in $metadata.httpStatusCode.+ errorLike.$metadata?.httpStatusCode,+ ]+ .map(toHttpStatusCode)+ .find((code) => code !== undefined);+ if (statusCode !== undefined) return statusCode;+ }+ return undefined;+}++function toHttpStatusCode(value: unknown): number | undefined {+ return typeof value === "number" &&+ Number.isInteger(value) &&+ value >= 100 &&+ value <= 599+ ? value+ : undefined;+}++function extractCleanErrorMessage(rawMessage: string): string {+ // Try to parse JSON error format (common in Google/Vertex AI errors)+ // Example: '[{"error":{"code":404,"message":"Model not found..."}}]'+ try {+ // Check if the message starts with [ or { indicating JSON+ const trimmed = rawMessage.trim();+ if (trimmed.startsWith("[") || trimmed.startsWith("{")) {+ const parsed = JSON.parse(trimmed);++ // Handle array format: [{"error": {"message": "..."}}]+ if (Array.isArray(parsed) && parsed[0]?.error?.message) {+ return parsed[0].error.message;+ }++ // Handle object format: {"error": {"message": "..."}}+ if (parsed?.error?.message) {+ return parsed.error.message;+ }++ // Handle direct message format: {"message": "..."}+ if (parsed?.message) {+ return parsed.message;+ }+ }+ } catch {+ // Not valid JSON, return as-is+ }++ return rawMessage;+}++/**+ * Maps any error thrown during an LLM completion (LangChain or AI SDK engine)+ * to an `LLMCompletionError` with a clean user-visible message and the shared+ * retryability classification. Both execution engines MUST use this mapper so+ * eval retry budgets behave identically regardless of engine.+ */+export function mapToLLMCompletionError(e: unknown): LLMCompletionError {+ if (e instanceof LLMCompletionError) return e;++ const responseStatusCode = getErrorResponseStatusCode(e) ?? 500;+ const rawMessage = e instanceof Error ? e.message : String(e);+ // Anthropic/OpenAI/Azure SDKs wrap synchronous fetch errors as+ // `APIConnectionError { message: "Connection error.", cause: original }`,+ // hiding the actual secureLlmFetch validation reason. Walk the `.cause`+ // chain for both retryability classification and the user-visible message+ // so operators see "Blocked hostname detected" / "Redirect validation+ // failed ..." instead of the unhelpful wrapper text.+ const nonRetryableCauseMessage = findNonRetryableCauseMessage(e);+ const message =+ nonRetryableCauseMessage ?? extractCleanErrorMessage(rawMessage);++ const hasNonRetryablePattern = nonRetryableCauseMessage !== undefined;++ // Determine retryability:+ // - 429 (rate limit): retryable with custom delay+ // - 5xx (server errors): retryable with custom delay+ // - 4xx (client errors): not retryable+ // - Non-retryable patterns: not retryable+ let isRetryable = false;++ if (ContextOverflowError.isInstance(e)) {+ isRetryable = false;+ } else if (+ e instanceof Error &&+ (e.name === "InsufficientQuotaError" || e.name === "ThrottlingException")+ ) {+ // Explicit 429 handling+ isRetryable = true;+ } else if (responseStatusCode >= 500) {+ // 5xx errors are retryable (server issues)+ isRetryable = true;+ } else if (responseStatusCode === 429) {+ // Rate limit is retryable+ isRetryable = true;+ }++ // Override if error message indicates non-retryable issue+ if (hasNonRetryablePattern) {+ isRetryable = false;+ }++ return new LLMCompletionError({+ message,+ responseStatusCode,+ isRetryable,+ cause: e,+ });+}diff --git a/packages/shared/src/server/llm/fetchLLMCompletion.ts b/packages/shared/src/server/llm/fetchLLMCompletion.tsindex 02fdeecbb5..8089914a0b 100644--- a/packages/shared/src/server/llm/fetchLLMCompletion.ts+++ b/packages/shared/src/server/llm/fetchLLMCompletion.ts@@ -16,7 +16,6 @@ import {SystemMessage,ToolMessage,} from "@langchain/core/messages";-import { ContextOverflowError } from "@langchain/core/errors";import {BytesOutputParser,StringOutputParser,@@ -56,10 +55,16 @@ import { decrypt } from "../../encryption";import {decryptAndParseExtraHeaders,executeWithRuntimeTimeout,+ processOpenAIBaseURL,RUNTIME_TIMEOUT_ADAPTERS,} from "./utils";import { logger } from "../logger";-import { LLMCompletionError } from "./errors";+import { executeAiSdkCompletion } from "./ai-sdk/executeAiSdkCompletion";+import {+ recordLlmExecutionDecision,+ resolveLlmExecutionDecision,+} from "./ai-sdk/resolveLlmExecutionDecision";+import { mapToLLMCompletionError } from "./completionErrorMapping";import {createSecureGoogleAIStudioApiClient,createSecureVertexAIApiClient,@@ -76,25 +81,6 @@ type SplitAIMessageContent = {reasoning?: string;};-const NON_RETRYABLE_LLM_ERROR_PATTERNS = [- "Request timed out",- "is not valid JSON",- "Unterminated string in JSON at position",- "TypeError",- "reached the end of its life",- "prompt is too long",- // secureLlmFetch validation failures: synchronous, status-less errors that- // would otherwise default to 500 + retryable and burn the eval-retry budget- // on permanent config or redirect-target failures.- "Only HTTP and HTTPS protocols are allowed",- "Only HTTPS base URLs are allowed",- "Blocked hostname detected",- "Blocked IP address detected",- "Redirect validation failed",- "Maximum redirects",- "Circular redirect detected",-] as const;-const isLangfuseCloud = Boolean(env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION);const AZURE_OPENAI_API_KEY_HEADER = "api-key";const ANTHROPIC_API_KEY_HEADER = "x-api-key";@@ -370,6 +356,55 @@ export async function fetchLLMCompletion(const apiKey = decrypt(llmConnection.secretKey); // the apiKey must never be printed to the consoleconst extraHeaders = decryptAndParseExtraHeaders(llmConnection.extraHeaders);+ // Common proxy configuration for all adapters+ const proxyUrl = env.HTTPS_PROXY;+ const proxyDispatcher = proxyUrl ? new ProxyAgent(proxyUrl) : undefined;+ const timeoutMs = env.LANGFUSE_FETCH_LLM_COMPLETION_TIMEOUT_MS;+ const secureLlmFetch = (+ logContext: string,+ additionalSensitiveHeaders?: string[],+ ) =>+ createSecureLlmFetch({+ logContext,+ additionalSensitiveHeaders,+ dispatcher: proxyDispatcher,+ });++ // Execution engine dispatch: adapters rolled out via+ // LANGFUSE_LLM_COMPLETION_AI_SDK_ADAPTERS run on the AI SDK engine, which+ // preserves all return shapes and error classification of the LangChain+ // engine. Caller-provided LangChain callbacks are not invoked on this path;+ // internal tracing is captured natively and routed through the regular OTel+ // ingestion pipeline instead of the LangChain callback handler.+ const executionDecision = resolveLlmExecutionDecision({+ adapter: modelParams.adapter,+ providerOptions: modelParams.providerOptions,+ llmConnectionConfig: config,+ enabledAdapters: env.LANGFUSE_LLM_COMPLETION_AI_SDK_ADAPTERS,+ });+ recordLlmExecutionDecision(executionDecision);++ logger.debug(`LLM Completion Execution engine: ${executionDecision.engine}`);++ if (executionDecision.engine === "ai-sdk") {+ return executeAiSdkCompletion({+ messages,+ tools,+ modelParams,+ streaming,+ structuredOutputSchema: params.structuredOutputSchema,+ apiKey,+ baseURL,+ extraHeaders,+ maxRetries,+ timeoutMs,+ fetch: secureLlmFetch("OpenAI LLM base URL"),+ apiMode: executionDecision.openAIApiMode,+ translatedProviderOptions: executionDecision.translatedProviderOptions,+ traceSinkParams,+ });+ }+let finalCallbacks: BaseCallbackHandler[] | undefined = callbacks ?? [];let processTracedEvents: ProcessTracedEvents = () => Promise.resolve();@@ -451,20 +486,6 @@ export async function fetchLLMCompletion((m) => m.content.length > 0 || "tool_calls" in m,);- // Common proxy configuration for all adapters- const proxyUrl = env.HTTPS_PROXY;- const proxyDispatcher = proxyUrl ? new ProxyAgent(proxyUrl) : undefined;- const timeoutMs = env.LANGFUSE_FETCH_LLM_COMPLETION_TIMEOUT_MS;- const secureLlmFetch = (- logContext: string,- additionalSensitiveHeaders?: string[],- ) =>- createSecureLlmFetch({- logContext,- additionalSensitiveHeaders,- dispatcher: proxyDispatcher,- });-let chatModel: ChatOpenAI | ChatAnthropic | ChatBedrockConverse | ChatGoogle;let usesOpenAIResponsesApi = false;if (modelParams.adapter === LLMAdapter.Anthropic) {@@ -880,54 +901,7 @@ export async function fetchLLMCompletion(return completion;} catch (e) {- const responseStatusCode = getErrorResponseStatusCode(e) ?? 500;- const rawMessage = e instanceof Error ? e.message : String(e);- // Anthropic/OpenAI/Azure SDKs wrap synchronous fetch errors as- // `APIConnectionError { message: "Connection error.", cause: original }`,- // hiding the actual secureLlmFetch validation reason. Walk the `.cause`- // chain for both retryability classification and the user-visible message- // so operators see "Blocked hostname detected" / "Redirect validation- // failed ..." instead of the unhelpful wrapper text.- const nonRetryableCauseMessage = findNonRetryableCauseMessage(e);- const message =- nonRetryableCauseMessage ?? extractCleanErrorMessage(rawMessage);-- const hasNonRetryablePattern = nonRetryableCauseMessage !== undefined;-- // Determine retryability:- // - 429 (rate limit): retryable with custom delay- // - 5xx (server errors): retryable with custom delay- // - 4xx (client errors): not retryable- // - Non-retryable patterns: not retryable- let isRetryable = false;-- if (ContextOverflowError.isInstance(e)) {- isRetryable = false;- } else if (- e instanceof Error &&- (e.name === "InsufficientQuotaError" || e.name === "ThrottlingException")- ) {- // Explicit 429 handling- isRetryable = true;- } else if (responseStatusCode >= 500) {- // 5xx errors are retryable (server issues)- isRetryable = true;- } else if (responseStatusCode === 429) {- // Rate limit is retryable- isRetryable = true;- }-- // Override if error message indicates non-retryable issue- if (hasNonRetryablePattern) {- isRetryable = false;- }-- throw new LLMCompletionError({- message,- responseStatusCode,- isRetryable,- cause: e,- });+ throw mapToLLMCompletionError(e);} finally {await processTracedEvents();}@@ -1006,104 +980,3 @@ function splitAIMessage(: {}),};}--/**- * Process baseURL template for OpenAI adapter only.- * Replaces {model} placeholder with actual model name.- * This is a workaround for proxies that require the model name in the URL azureOpenAIBasePath- * while having OpenAI compliance otherwise- */-function processOpenAIBaseURL(params: {- url: string | null | undefined;- modelName: string;-}): string | null | undefined {- const { url, modelName } = params;-- if (!url || !url.includes("{model}")) {- return url;- }-- return url.replace("{model}", modelName);-}--// Walks an error and its `.cause` chain (cycle-safe), yielding each link.-function* walkCauseChain(error: unknown): Generator<unknown> {- const visited = new Set<unknown>();- for (- let current: unknown = error;- current && !visited.has(current);- current = (current as any).cause- ) {- visited.add(current);- yield current;- }-}--function findNonRetryableCauseMessage(error: unknown): string | undefined {- for (const current of walkCauseChain(error)) {- if (!(current instanceof Error)) continue;- const message = extractCleanErrorMessage(current.message);- if (NON_RETRYABLE_LLM_ERROR_PATTERNS.some((p) => message.includes(p))) {- return message;- }- }- return undefined;-}--function getErrorResponseStatusCode(error: unknown): number | undefined {- for (const current of walkCauseChain(error)) {- if (!current || typeof current !== "object") continue;- const errorLike = current as any;- const statusCode = [- errorLike.response?.status,- errorLike.status,- errorLike.statusCode,- // Bedrock errors have status code in $metadata.httpStatusCode.- errorLike.$metadata?.httpStatusCode,- ]- .map(toHttpStatusCode)- .find((code) => code !== undefined);- if (statusCode !== undefined) return statusCode;- }- return undefined;-}--function toHttpStatusCode(value: unknown): number | undefined {- return typeof value === "number" &&- Number.isInteger(value) &&- value >= 100 &&- value <= 599- ? value- : undefined;-}--function extractCleanErrorMessage(rawMessage: string): string {- // Try to parse JSON error format (common in Google/Vertex AI errors)- // Example: '[{"error":{"code":404,"message":"Model not found..."}}]'- try {- // Check if the message starts with [ or { indicating JSON- const trimmed = rawMessage.trim();- if (trimmed.startsWith("[") || trimmed.startsWith("{")) {- const parsed = JSON.parse(trimmed);-- // Handle array format: [{"error": {"message": "..."}}]- if (Array.isArray(parsed) && parsed[0]?.error?.message) {- return parsed[0].error.message;- }-- // Handle object format: {"error": {"message": "..."}}- if (parsed?.error?.message) {- return parsed.error.message;- }-- // Handle direct message format: {"message": "..."}- if (parsed?.message) {- return parsed.message;- }- }- } catch {- // Not valid JSON, return as-is- }-- return rawMessage;-}diff --git a/packages/shared/src/server/llm/utils.ts b/packages/shared/src/server/llm/utils.tsindex 967e0d3498..d586a995fa 100644--- a/packages/shared/src/server/llm/utils.ts+++ b/packages/shared/src/server/llm/utils.ts@@ -50,3 +50,22 @@ export function decryptAndParseExtraHeaders(return ExtraHeaderSchema.parse(JSON.parse(decrypt(extraHeaders)));}++/**+ * Process baseURL template for OpenAI adapter only.+ * Replaces {model} placeholder with actual model name.+ * This is a workaround for proxies that require the model name in the URL azureOpenAIBasePath+ * while having OpenAI compliance otherwise+ */+export function processOpenAIBaseURL(params: {+ url: string | null | undefined;+ modelName: string;+}): string | null | undefined {+ const { url, modelName } = params;++ if (!url || !url.includes("{model}")) {+ return url;+ }++ return url.replace("{model}", modelName);+}diff --git a/packages/shared/src/server/otel/OtelIngestionProcessor.ts b/packages/shared/src/server/otel/OtelIngestionProcessor.tsindex 9fa0b661ae..548b7c81c8 100644--- a/packages/shared/src/server/otel/OtelIngestionProcessor.ts+++ b/packages/shared/src/server/otel/OtelIngestionProcessor.ts@@ -42,6 +42,14 @@ export interface OtelIngestionProcessorConfig {sdkName: string;sdkVersion: string;ingestionVersion?: string;+ /**+ * Marks Langfuse-internal telemetry (e.g. LLM-as-a-judge /+ * prompt-experiment executions). Propagated through the ingestion queue so+ * the consumer parses these events with the internal ingestion schema,+ * preserving the reserved "langfuse-" environment prefix that the public+ * schema strips.+ */+ isLangfuseInternal?: boolean;}interface CreateTraceEventParams {@@ -156,6 +164,7 @@ export class OtelIngestionProcessor {private readonly sdkName: string;private readonly sdkVersion: string;private readonly ingestionVersion?: string;+ private readonly isLangfuseInternal?: boolean;constructor(config: OtelIngestionProcessorConfig) {this.projectId = config.projectId;@@ -169,6 +178,7 @@ export class OtelIngestionProcessor {// Ingestion protocol version from x-langfuse-ingestion-version. This is// only used as a write-path hint, not as SDK attribution.this.ingestionVersion = config.ingestionVersion;+ this.isLangfuseInternal = config.isLangfuseInternal;}/**@@ -217,6 +227,7 @@ export class OtelIngestionProcessor {sdkName: this.sdkName,sdkVersion: this.sdkVersion,ingestionVersion: this.ingestionVersion,+ ...(this.isLangfuseInternal ? { isLangfuseInternal: true } : {}),},}): Promise.reject("Failed to instantiate otel ingestion queue");diff --git a/packages/shared/src/server/queues.ts b/packages/shared/src/server/queues.tsindex c04ff94c64..ea3cf2064e 100644--- a/packages/shared/src/server/queues.ts+++ b/packages/shared/src/server/queues.ts@@ -67,6 +67,13 @@ export const OtelIngestionEvent = z.object({sdkName: z.string().optional(),sdkVersion: z.string().optional(),ingestionVersion: z.string().optional(),+ // Langfuse-internal telemetry (e.g. LLM-as-a-judge / prompt-experiment+ // executions published via fetchLLMCompletion's AI SDK engine). The+ // consumer must parse these events with the INTERNAL ingestion schema:+ // the public schema strips the reserved "langfuse-" environment prefix,+ // which would expose internal traces as user environments and bypass the+ // trace-upsert eval-loop guard. Optional for in-flight job compatibility.+ isLangfuseInternal: z.boolean().optional(),});export const BatchExportJobSchema = z.object({diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex baa89e135f..680746e0d4 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -151,6 +151,9 @@ importers:packages/shared:dependencies:+ '@ai-sdk/openai':+ specifier: ^4.0.0+ version: 4.0.4([email protected])'@anthropic-ai/tokenizer':specifier: ^0.0.4version: 0.0.4@@ -205,6 +208,15 @@ importers:'@opentelemetry/api':specifier: '>=1.0.0 <1.10.0'version: 1.9.1+ '@opentelemetry/otlp-transformer':+ specifier: ^0.219.0+ version: 0.219.0(@opentelemetry/[email protected])+ '@opentelemetry/resources':+ specifier: ^2.8.0+ version: 2.8.0(@opentelemetry/[email protected])+ '@opentelemetry/sdk-trace-base':+ specifier: ^2.8.0+ version: 2.8.0(@opentelemetry/[email protected])'@prisma/client':specifier: ^6.19.3@@ -226,6 +238,9 @@ importers:'@types/bcryptjs':specifier: ^2.4.6version: 2.4.6+ ai:+ specifier: ^7.0.0+ version: 7.0.8([email protected])ajv:specifier: ^8.18.0version: 8.20.0@@ -311,6 +326,9 @@ importers:specifier: 4.3.6version: 4.3.6devDependencies:+ '@opentelemetry/context-async-hooks':+ specifier: ^2.8.0+ version: 2.8.0(@opentelemetry/[email protected])'@repo/eslint-config':specifier: workspace:*version: link:../config-eslint@@ -1214,6 +1232,12 @@ packages:peerDependencies:zod: 4.3.6+ '@ai-sdk/[email protected]':+ resolution: {integrity: sha512-8GjssUxXeTd8tst2fYXNOFbtNNZFv3sG7aq7wKnQYrU2eB3JFR7np6o4F3Snp/fy/rJZSeH28LvjSWq5wkdL8Q==}+ engines: {node: '>=22'}+ peerDependencies:+ zod: 4.3.6+'@ai-sdk/[email protected]':resolution: {integrity: sha512-Lhw1742RXc+4pRIvqVXa0jdl5+qdpmw8lj0lm6OchUg9rVGHzymlaxe7CDiYX5U2af4jbjKeTY22LDi3bIycgQ==}engines: {node: '>=18'}@@ -1232,12 +1256,24 @@ packages:peerDependencies:zod: 4.3.6+ '@ai-sdk/[email protected]':+ resolution: {integrity: sha512-p6VDEzEx52PIzRnFoUpiw6ABn07h4Rt+atL+M51W9SqwhselaZFRnz/pzv7LF9D1Gok5qfzOmR+JwvDDvDWS3w==}+ engines: {node: '>=22'}+ peerDependencies:+ zod: 4.3.6+'@ai-sdk/[email protected]':resolution: {integrity: sha512-ubkAJ+xODouwtmN1tYlvTPphH1hPOBfZaEQe8U7skGvFAnIRs9PPpsq57bC2+Ky/MB4yzhd6YOsxTAx9sGpazw==}engines: {node: '>=18'}peerDependencies:zod: 4.3.6+ '@ai-sdk/[email protected]':+ resolution: {integrity: sha512-EcmdjJb7yggsZPCbS3MFBpvAUnKaPW+QvanU5GzF00XCq0bqqAmvJ3MN19ejlmOETbW8sJNiq6qam48wTcbUNw==}+ engines: {node: '>=22'}+ peerDependencies:+ zod: 4.3.6+'@ai-sdk/[email protected]':resolution: {integrity: sha512-qZMxYJ0qqX/RfnuIaab+zp8UAeJn/ygXXAffR5I4N0n1IrvA6qBsjc8hXLmBiMV2zoXlifkacF7sEFnYnjBcqg==}engines: {node: '>=18'}@@ -1258,6 +1294,10 @@ packages:resolution: {integrity: sha512-oGMAgGoQdBXbZqNG0Ze56CHjDZ1IDYOwGYxYjO5KLSlz5HiNQ9udIXsPZ61VWaHGZ5XW/jyjmr6t2xz2jGVwbQ==}engines: {node: '>=18'}+ '@ai-sdk/[email protected]':+ resolution: {integrity: sha512-6p3C/vGqVIjcptBu1DnVd/BZJ2wWmV9TUv9192vT6ZvT9KNED8EwRTqyqFpoQZKgSbMDSvBSq3dqR524Nt/Crw==}+ engines: {node: '>=22'}+'@ai-sdk/[email protected]':resolution: {integrity: sha512-3zcwCc8ezzFlwp3ZD15wAPjf2Au4s3vAbKsXQVyhxODHcmu0iyPO2Eua6D/vicq/AUm/BAo60r97O6HU+EI0+w==}engines: {node: '>=18'}@@ -6130,6 +6170,10 @@ packages:resolution: {integrity: sha512-Fw28YZpRnA3cAHHDlkt7xQHiJ0fcL+NRcIqsocZQUSmbzeIKRpwttJjik5ZGanXP+vlA4SbTg+AbA3bP363l+w==}engines: {node: '>= 20'}+ '@vercel/[email protected]':+ resolution: {integrity: sha512-UycprH3T6n3jH0k44NHMa7pnFHGu/N05MjojYr+Mc6I7obkoLIJujSWwin1pCvdy/eOxrI/l3uDLQsmcrOb4ug==}+ engines: {node: '>= 20'}+'@vitejs/[email protected]':resolution: {integrity: sha512-gUu9hwfWvvEDBBmgtAowQCojwZmJ5mcLn3aufeCsitijs3+f2NsrPtlAWIR6OPiqljl96GVCUbLe0HyqIpVaoA==}engines: {node: ^14.18.0 || >=16.0.0}@@ -6269,6 +6313,9 @@ packages:resolution: {integrity: sha512-kMwLlxUbduttIgaPdSkmEarFpP+mSY8FEm+QWMBRJwxOHWkri+cxd8KZHO9EMrB9vgUuz+5WEaCawaL5wGVoXg==}engines: {node: '>=18.0.0'}+ '@workflow/[email protected]':+ resolution: {integrity: sha512-pav4F2BoirECWR7Nf1TKt+2eETcBj7jj4cBefQ8VXQCA6NPkaKeLfj/zMgi+3zYV5ZIBT4GuUiphsj0/b9hPQQ==}+'@workflow/[email protected]':resolution: {integrity: sha512-8kkeoQKLDaKXefjV5dbhBj2aErfKp1Mc4pb6tj8144cF+Em5SPbyMbyLCHp+BVrFfFVCBluCtMx+jjvaFVZGww==}@@ -6327,6 +6374,12 @@ packages:peerDependencies:zod: 4.3.6+ resolution: {integrity: sha512-vTEKl6fDBZ2IxBXTRaZOajf9W2Ev57Ju8iKtUvqlmDk8Z9BrEP4c22SWJsg1RcWHSFmJMSBa/s5dlUBHUq3YwA==}+ engines: {node: '>=22'}+ peerDependencies:+ zod: 4.3.6+resolution: {integrity: sha512-Wx0Kx52hxE7C18hkMEggYlEifqWZtYaRgouJor+WMdPnQyEK13vgEWyVNup7SoeeoLMsr4kf5h6dOW11I15MUA==}peerDependencies:@@ -11884,6 +11937,13 @@ snapshots:'@vercel/oidc': 3.1.0zod: 4.3.6+ '@ai-sdk/[email protected]([email protected])':+ dependencies:+ '@ai-sdk/provider': 4.0.1+ '@ai-sdk/provider-utils': 5.0.2([email protected])+ '@vercel/oidc': 3.2.0+ zod: 4.3.6+'@ai-sdk/[email protected]([email protected])':dependencies:'@ai-sdk/provider': 2.0.3@@ -11903,6 +11963,12 @@ snapshots:'@ai-sdk/provider-utils': 4.0.27([email protected])zod: 4.3.6+ '@ai-sdk/[email protected]([email protected])':+ dependencies:+ '@ai-sdk/provider': 4.0.1+ '@ai-sdk/provider-utils': 5.0.2([email protected])+ zod: 4.3.6+'@ai-sdk/[email protected]([email protected])':dependencies:'@ai-sdk/provider': 3.0.10@@ -11910,6 +11976,14 @@ snapshots:eventsource-parser: 3.0.8zod: 4.3.6+ '@ai-sdk/[email protected]([email protected])':+ dependencies:+ '@ai-sdk/provider': 4.0.1+ '@standard-schema/spec': 1.1.0+ '@workflow/serde': 4.1.0+ eventsource-parser: 3.0.8+ zod: 4.3.6+'@ai-sdk/[email protected]':dependencies:json-schema: 0.4.0@@ -11930,6 +12004,10 @@ snapshots:dependencies:json-schema: 0.4.0+ '@ai-sdk/[email protected]':+ dependencies:+ json-schema: 0.4.0+'@ai-sdk/[email protected]([email protected])':dependencies:'@ai-sdk/provider': 1.1.3@@ -17479,6 +17557,8 @@ snapshots:'@vercel/[email protected]': {}+ '@vercel/[email protected]': {}+'@vitejs/[email protected]([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))':dependencies:'@babel/core': 7.29.6@@ -17712,6 +17792,8 @@ snapshots:'@whatwg-node/promise-helpers': 1.3.2tslib: 2.8.1+ '@workflow/[email protected]': {}+'@workflow/[email protected]': {}'@xtuc/[email protected]': {}@@ -17762,6 +17844,13 @@ snapshots:'@opentelemetry/api': 1.9.0zod: 4.3.6+ dependencies:+ '@ai-sdk/gateway': 4.0.6([email protected])+ '@ai-sdk/provider': 4.0.1+ '@ai-sdk/provider-utils': 5.0.2([email protected])+ zod: 4.3.6+optionalDependencies:ajv: 8.20.0diff --git a/worker/src/features/evaluation/observationEval/__tests__/isObservationAllowedForQueuedObservationEvals.test.ts b/worker/src/features/evaluation/observationEval/__tests__/isObservationAllowedForQueuedObservationEvals.test.tsnew file mode 100644index 0000000000..49526689fd--- /dev/null+++ b/worker/src/features/evaluation/observationEval/__tests__/isObservationAllowedForQueuedObservationEvals.test.ts@@ -0,0 +1,91 @@+import { describe, expect, it } from "vitest";++import { isObservationAllowedForQueuedObservationEvals } from "../scheduleObservationEvals";++const ROOT_SPAN_ID = "aaaaaaaaaaaaaaaa";+const CHILD_SPAN_ID = "bbbbbbbbbbbbbbbb";++describe("isObservationAllowedForQueuedObservationEvals", () => {+ it("allows user environments", () => {+ expect(+ isObservationAllowedForQueuedObservationEvals({+ environment: "default",+ span_id: CHILD_SPAN_ID,+ experiment_item_root_span_id: null,+ }),+ ).toBe(true);+ expect(+ isObservationAllowedForQueuedObservationEvals({+ environment: "production",+ span_id: CHILD_SPAN_ID,+ experiment_item_root_span_id: null,+ }),+ ).toBe(true);+ });++ it("blocks LLM-as-a-judge observations to prevent eval-on-eval recursion", () => {+ // LLM-as-a-judge executions publish their telemetry through the OTel+ // ingestion pipeline; scheduling evals on those observations would spawn+ // evals of evals indefinitely.+ expect(+ isObservationAllowedForQueuedObservationEvals({+ environment: "langfuse-llm-as-a-judge",+ span_id: ROOT_SPAN_ID,+ experiment_item_root_span_id: ROOT_SPAN_ID,+ }),+ ).toBe(false);+ });++ it("blocks other internal langfuse environments", () => {+ for (const environment of [+ "langfuse-code-eval",+ "langfuse-in-app-agent",+ "langfuse",+ ]) {+ expect(+ isObservationAllowedForQueuedObservationEvals({+ environment,+ span_id: ROOT_SPAN_ID,+ experiment_item_root_span_id: ROOT_SPAN_ID,+ }),+ ).toBe(false);+ }+ });++ it("allows experiment run-item root observations only", () => {+ expect(+ isObservationAllowedForQueuedObservationEvals({+ environment: "langfuse-prompt-experiment",+ span_id: ROOT_SPAN_ID,+ experiment_item_root_span_id: ROOT_SPAN_ID,+ }),+ ).toBe(true);+ });++ it("blocks experiment child observations", () => {+ expect(+ isObservationAllowedForQueuedObservationEvals({+ environment: "langfuse-prompt-experiment",+ span_id: CHILD_SPAN_ID,+ experiment_item_root_span_id: ROOT_SPAN_ID,+ }),+ ).toBe(false);+ });++ it("blocks experiment observations without root linkage", () => {+ expect(+ isObservationAllowedForQueuedObservationEvals({+ environment: "langfuse-prompt-experiment",+ span_id: ROOT_SPAN_ID,+ experiment_item_root_span_id: null,+ }),+ ).toBe(false);+ expect(+ isObservationAllowedForQueuedObservationEvals({+ environment: "langfuse-prompt-experiment",+ span_id: ROOT_SPAN_ID,+ experiment_item_root_span_id: undefined,+ }),+ ).toBe(false);+ });+});diff --git a/worker/src/features/evaluation/observationEval/index.ts b/worker/src/features/evaluation/observationEval/index.tsindex c6b75f2ed1..b52a73a0ea 100644--- a/worker/src/features/evaluation/observationEval/index.ts+++ b/worker/src/features/evaluation/observationEval/index.ts@@ -1,4 +1,7 @@-export { scheduleObservationEvals } from "./scheduleObservationEvals";+export {+ isObservationAllowedForQueuedObservationEvals,+ scheduleObservationEvals,+} from "./scheduleObservationEvals";export { fetchObservationEvalConfigs } from "./fetchObservationEvalConfigs";export { createObservationEvalSchedulerDeps } from "./createSchedulerDeps";export {diff --git a/worker/src/features/evaluation/observationEval/scheduleObservationEvals.ts b/worker/src/features/evaluation/observationEval/scheduleObservationEvals.tsindex 4cdadf5016..fbed795a5e 100644--- a/worker/src/features/evaluation/observationEval/scheduleObservationEvals.ts+++ b/worker/src/features/evaluation/observationEval/scheduleObservationEvals.ts@@ -4,7 +4,11 @@ import {type ObservationEvalSchedulerDeps,} from "./types";import { shouldSampleObservation } from "./shouldSampleObservation";-import { InMemoryFilterService, logger } from "@langfuse/shared/src/server";+import {+ InMemoryFilterService,+ LangfuseInternalTraceEnvironment,+ logger,+} from "@langfuse/shared/src/server";import {EvalTargetObject,JobExecutionStatus,@@ -22,6 +26,43 @@ interface ScheduleObservationEvalsParams {executionMode?: JobConfigExecutionMode;}+/**+ * Whether queue-driven (asynchronous OTel ingestion) observation-eval+ * scheduling is allowed for an observation.+ *+ * Internal Langfuse environments are excluded: LLM-as-a-judge executions+ * publish their own telemetry through the OTel ingestion pipeline+ * (fetchLLMCompletion AI SDK engine), and scheduling evals on eval+ * observations would recurse indefinitely — the observation-eval counterpart+ * of the trace-upsert safeguard in evalService.ts createEvalJobs().+ *+ * Single exception: prompt-experiment run-item ROOT observations+ * (span_id === experiment_item_root_span_id), so experiments executed on the+ * AI SDK engine get their evals scheduled from the queue — the async+ * equivalent of the LangChain path's synchronous onRootEventRecordReady+ * scheduling, which only ever offered the root record. Loop safety holds+ * because evals triggered on experiment roots execute in the+ * langfuse-llm-as-a-judge environment, which stays blocked here, and+ * experiment child spans carry the root's span id, so they never match.+ */+export function isObservationAllowedForQueuedObservationEvals(+ observation: Pick<+ ObservationForEval,+ "environment" | "span_id" | "experiment_item_root_span_id"+ >,+): boolean {+ if (!observation.environment?.startsWith("langfuse")) {+ return true;+ }++ return (+ observation.environment ===+ LangfuseInternalTraceEnvironment.PromptExperiments &&+ observation.experiment_item_root_span_id != null &&+ observation.span_id === observation.experiment_item_root_span_id+ );+}+/*** Schedule observation evals for a given observation.*diff --git a/worker/src/queues/otelIngestionQueue.ts b/worker/src/queues/otelIngestionQueue.tsindex ea8ab81329..7c7e50c486 100644--- a/worker/src/queues/otelIngestionQueue.ts+++ b/worker/src/queues/otelIngestionQueue.ts@@ -42,6 +42,7 @@ import {} from "@langfuse/shared";import {fetchObservationEvalConfigs,+ isObservationAllowedForQueuedObservationEvals,scheduleObservationEvals,createObservationEvalSchedulerDeps,} from "../features/evaluation/observationEval";@@ -214,6 +215,7 @@ export const otelIngestionQueueProcessorBuilder = (const publicKey = job.data.payload.data.publicKey ?? "";const fileKey = job.data.payload.data.fileKey;const auth = job.data.payload.authCheck;+ const isLangfuseInternal = job.data.payload.isLangfuseInternal === true;const attribution: IngestionAttribution = {ingestionApiKey: publicKey,ingestionSdkName:@@ -321,7 +323,7 @@ export const otelIngestionQueueProcessorBuilder = ((e) => getClickhouseEntityType(e.type) !== "observation",);// We need to parse each incoming observation through our ingestion schema to make use of its included transformations.- const ingestionSchema = createIngestionEventSchema();+ const ingestionSchema = createIngestionEventSchema(isLangfuseInternal);const observations = events.filter((e) => getClickhouseEntityType(e.type) === "observation").map((o) => ingestionSchema.safeParse(o))@@ -467,6 +469,7 @@ export const otelIngestionQueueProcessorBuilder = (source: "otel",forwardToEventsTable: shouldForwardToEventsTable,attribution,+ isLangfuseInternal,}),]);}@@ -531,17 +534,22 @@ export const otelIngestionQueueProcessorBuilder = (return;}- // Step 2: Schedule observation evals (independent of event writes)+ // Step 2: Schedule observation evals (independent of event writes).+ // Internal langfuse-* environments are excluded to prevent+ // eval-on-eval recursion, except experiment run-item roots; see+ // isObservationAllowedForQueuedObservationEvals.if (hasEvalConfigs && evalSchedulerDeps) {try {const observation =convertEventRecordToObservationForEval(eventRecord);- await scheduleObservationEvals({- observation,- configs: evalConfigs,- schedulerDeps: evalSchedulerDeps,- });+ if (isObservationAllowedForQueuedObservationEvals(observation)) {+ await scheduleObservationEvals({+ observation,+ configs: evalConfigs,+ schedulerDeps: evalSchedulerDeps,+ });+ }} catch (error) {traceException(error);